From 70771b42091e5f021482a4162f29ff77bc3a5ba7 Mon Sep 17 00:00:00 2001 From: lapy Date: Sun, 11 Oct 2026 17:58:15 +0100 Subject: [PATCH] chore(westernization): translate remaining Han text across code, UI and docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Final localization pass over everything the audit covers, driven by the local qwen3.8:instruct endpoint (thinking disabled) with placeholder- masked, cached, resumable batches: - Python server: comments, docstrings, log/error messages, prompt text - manager-api Java: javadoc, exception messages, Swagger summaries, westernized test fixtures (locale strings, signed-URL examples) - manager-web / manager-mobile: component comments and misc leftovers (functional split regexes such as /[、;;,,]/ left byte-identical) - digital-human: HTML/UI text, JS comments, wake-word defaults aligned with the server canonical English wake words - docs: device-call guide, wakeword and search integration guides Also widens the westernization audit exception to the whole vendored generator bundle and retires the stale per-file exception list. --- docs/all-in-one-digital-human-setup.md | 184 ++--- docs/device-call-guide.md | 124 ++-- docs/digital-human-wakeword.md | 200 +++--- docs/web-search-integration.md | 80 +-- main/digital-human/index.html | 230 +++---- main/digital-human/js/app.js | 124 ++-- .../js/config/default-mcp-tools.json | 4 +- main/digital-human/js/config/manager.js | 24 +- main/digital-human/js/core/audio/recorder.js | 44 +- .../js/core/network/wakeword-bridge.js | 38 +- .../js/core/network/websocket.js | 222 +++--- main/digital-human/js/ui/controller.js | 170 ++--- main/digital-human/start.py | 2 +- .../wakeword_runtime/config/config_loader.py | 22 +- .../wakeword_runtime/runtime/http_server.py | 4 +- .../xiaozhi/common/constant/Constant.java | 114 +-- .../xiaozhi/common/exception/ErrorCode.java | 330 ++++----- .../java/xiaozhi/common/redis/RedisKeys.java | 2 +- .../agent/controller/AgentController.java | 86 +-- .../controller/AgentSnapshotController.java | 12 +- .../xiaozhi/modules/agent/dao/AgentDao.java | 12 +- .../agent/dto/AgentSnapshotDataDTO.java | 2 +- .../agent/dto/AgentSnapshotPageDTO.java | 8 +- .../agent/dto/AgentSnapshotRestoreDTO.java | 4 +- .../agent/dto/AgentSnapshotTagDTO.java | 2 +- .../modules/agent/dto/AgentUpdateDTO.java | 6 +- .../entity/AgentCorrectWordMappingEntity.java | 16 +- .../agent/entity/AgentSnapshotEntity.java | 26 +- .../service/AgentChatHistoryService.java | 12 +- .../service/AgentPluginMappingService.java | 10 +- .../agent/service/impl/AgentServiceImpl.java | 112 +-- .../impl/AgentSnapshotServiceImpl.java | 48 +- .../xiaozhi/modules/agent/vo/AgentInfoVO.java | 4 +- .../modules/agent/vo/AgentSnapshotVO.java | 14 +- .../config/controller/ConfigController.java | 2 +- .../modules/config/dto/CorrectWordsDTO.java | 6 +- .../modules/config/init/SystemInitConfig.java | 8 +- .../modules/config/service/ConfigService.java | 20 +- .../controller/CorrectWordController.java | 20 +- .../dto/CorrectWordFileCreateDTO.java | 12 +- .../entity/CorrectWordFileEntity.java | 18 +- .../entity/CorrectWordItemEntity.java | 10 +- .../service/CorrectWordFileService.java | 58 +- .../impl/CorrectWordFileServiceImpl.java | 34 +- .../correctword/vo/CorrectWordFileVO.java | 14 +- .../correctword/vo/CorrectWordSimpleVO.java | 6 +- .../device/controller/DeviceController.java | 42 +- .../device/dao/DeviceAddressBookDao.java | 10 +- .../device/dto/DeviceAddressBookAliasDTO.java | 12 +- .../dto/DeviceAddressBookPermissionDTO.java | 12 +- .../entity/DeviceAddressBookEntity.java | 18 +- .../service/DeviceAddressBookService.java | 22 +- .../modules/device/service/DeviceService.java | 76 +- .../impl/DeviceAddressBookServiceImpl.java | 30 +- .../service/impl/DeviceServiceImpl.java | 8 +- .../device/vo/UserShowDeviceListVO.java | 26 +- .../controller/KnowledgeFilesController.java | 66 +- .../knowledge/dto/KnowledgeBaseDTO.java | 40 +- .../knowledge/rag/impl/RAGFlowAdapter.java | 170 ++--- .../impl/KnowledgeBaseServiceImpl.java | 128 ++-- .../impl/KnowledgeFilesServiceImpl.java | 342 ++++----- .../impl/OpenAIStyleLLMServiceImpl.java | 108 +-- .../service/impl/ModelConfigServiceImpl.java | 14 +- .../sys/controller/SysParamsController.java | 2 +- .../modules/sys/service/SysParamsService.java | 10 +- .../service/impl/SysParamsServiceImpl.java | 50 +- .../impl/AgentSnapshotServiceImplTest.java | 20 +- .../controller/DeviceControllerTest.java | 4 +- .../service/impl/DeviceAutoUpdateTest.java | 6 +- .../impl/DeviceTimeSerializationTest.java | 26 +- .../impl/MqttGatewayAuthorizationTest.java | 18 +- .../service/impl/TimbreServiceImplTest.java | 14 +- main/manager-mobile/.editorconfig | 20 +- main/manager-mobile/.gitignore | 14 +- main/manager-mobile/src/api/agent/agent.ts | 48 +- main/manager-mobile/src/api/agent/types.ts | 12 +- main/manager-mobile/src/pages.json | 6 +- .../components/agentSnapshotUtils.test.mjs | 2 +- main/manager-mobile/src/pages/agent/edit.vue | 198 +++--- .../src/pages/agent/provider.vue | 2 +- .../src/pages/chat-history/detail.vue | 110 +-- .../src/pages/settings/index.vue | 86 +-- main/manager-mobile/src/store/index.ts | 4 +- main/manager-web/src/apis/api.js | 12 +- .../src/apis/module/addressBook.js | 6 +- .../src/apis/module/agentSnapshotApi.test.mjs | 4 +- .../src/apis/module/correctWord.js | 22 +- .../src/components/AddressBookDialog.vue | 2 +- .../src/components/AgentSnapshotDialog.vue | 2 +- .../src/components/ChatHistoryDialog.vue | 4 +- .../src/components/CustomDialog.vue | 6 +- .../src/components/CustomTable.vue | 42 +- .../src/components/FirmwareDialog.vue | 4 +- .../src/components/FunctionDialog.vue | 70 +- main/manager-web/src/components/HeaderBar.vue | 108 +-- .../src/components/ModelEditDialog.vue | 2 +- .../src/components/ProviderDialog.vue | 2 +- .../src/components/TtsAdvancedSettings.vue | 14 +- main/manager-web/src/router/index.js | 30 +- .../src/views/AddressBookManagement.vue | 44 +- .../src/views/AgentTemplateManagement.vue | 6 +- main/manager-web/src/views/DictManagement.vue | 22 +- .../src/views/FeatureManagement.vue | 70 +- .../src/views/KnowledgeBaseManagement.vue | 8 +- .../src/views/ParamsManagement.vue | 8 +- main/manager-web/src/views/UserManagement.vue | 2 +- .../src/views/VoiceCloneManagement.vue | 20 +- main/manager-web/src/views/home.vue | 44 +- main/manager-web/src/views/roleConfig.vue | 212 +++--- main/manager-web/vue.config.js | 64 +- main/xiaozhi-server/app.py | 74 +- main/xiaozhi-server/config/config_loader.py | 50 +- .../config/manage_api_client.py | 12 +- main/xiaozhi-server/core/connection.py | 650 +++++++++--------- .../core/handle/intentHandler.py | 8 +- .../core/handle/reportHandle.py | 14 +- .../core/handle/sendAudioHandle.py | 162 ++--- .../textHandler/listenMessageHandler.py | 44 +- .../xiaozhi-server/core/providers/asr/base.py | 4 +- .../providers/intent/intent_llm/intent_llm.py | 8 +- .../providers/memory/powermem/powermem.py | 8 +- .../tools/server_plugins/plugin_executor.py | 30 +- .../xiaozhi-server/core/providers/tts/base.py | 190 ++--- .../core/providers/vad/silero.py | 2 +- .../core/utils/audioRateController.py | 2 +- main/xiaozhi-server/core/utils/dialogue.py | 42 +- .../core/utils/prompt_manager.py | 104 +-- main/xiaozhi-server/core/websocket_server.py | 74 +- .../plugins_func/functions/hass_state.py | 24 +- .../functions/search_from_ragflow.py | 10 +- main/xiaozhi-server/plugins_func/register.py | 2 +- .../core/utils/test_instance_creators.py | 2 +- .../tests/core/utils/test_textUtils.py | 12 +- main/xiaozhi-server/tests/test_llm.py | 72 +- main/xiaozhi-server/tests/test_memory.py | 36 +- main/xiaozhi-server/tests/test_rag.py | 36 +- main/xiaozhi-server/tests/test_stt.py | 74 +- main/xiaozhi-server/tests/test_tts.py | 66 +- scripts/westernization_audit.sh | 14 +- 139 files changed, 3465 insertions(+), 3467 deletions(-) diff --git a/docs/all-in-one-digital-human-setup.md b/docs/all-in-one-digital-human-setup.md index ebee66d5d..b08939c6c 100644 --- a/docs/all-in-one-digital-human-setup.md +++ b/docs/all-in-one-digital-human-setup.md @@ -1,32 +1,32 @@ -# 一体机数字人配置指南 +# All-in-one Digital Human Configuration Guide -本项目用于在 x86 架构设备(如迷你主机、工控机、普通电脑等)上部署一套完整的数字人展示系统,实现以下功能: -- 开机自动进入 Kiosk 全屏浏览器,展示指定网页 -- 后台运行唤醒词检测服务,支持语音交互 +This project deploys a complete digital human display system on x86 devices (e.g., mini PCs, industrial PCs, standard computers), implementing the following features: +- Auto-launch Kiosk full-screen browser on boot to display the specified webpage +- Run wake word detection service in background, supporting voice interaction -> **说明**:本文档以 **Intel N100 迷你主机(天虹 QN10-100B4)** 为例进行部署演示,其他 x86 设备可参考调整(注意网络配置和声卡设备差异)。 +> **Note**: This document uses the **Intel N100 mini PC (Tianhong QN10-100B4)** as an example for deployment. Other x86 devices can refer to this guide with adjustments (note differences in network configuration and sound card devices). -## 适用环境 +## Environment -| 项目 | 说明 | +| Item | Description | |------|------| -| 示例硬件 | 天虹 QN10-100B4(Intel N100) | -| 操作系统 | Ubuntu 24.04 LTS (Noble Numbat) | -| 示例用户 | xz(请根据实际情况替换) | -| 网络 | Wi-Fi 连接,固定 IP(可按需改为有线) | +| Example Hardware | Tianhong QN10-100B4 (Intel N100) | +| OS | Ubuntu 24.04 LTS (Noble Numbat) | +| Example user | xz (replace as needed) | +| Network | Wi-Fi connection, static IP (can be changed to wired if needed) | -## 部署流程 +## Deployment Process -1. 系统初始化(换源、连网) -2. 安装图形组件与 Kiosk 浏览器 -3. 配置自动登录与图形界面 -4. 部署唤醒词服务(Python 环境 + 麦克风) -5. 优化开机速度与隐藏启动信息 +1. System initialization (switch source, connect network) +2. Install graphical components and Kiosk browser +3. Configure auto-login and GUI +4. Deploy wake word service (Python environment + microphone) +5. Optimize boot speed and hide startup info --- -### 系统初始化(换源、连网) +### System initialization (switch source, connect network) ``` sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak @@ -52,7 +52,7 @@ echo 'Acquire::ForceIPv4 "true";' | sudo tee /etc/apt/apt.conf.d/99force-ipv4 ``` -安装网络管理工具(若已存在可忽略) +Install network management tool (ignore if already exists) Bash @@ -64,9 +64,9 @@ sudo systemctl enable NetworkManager ``` -设置wifi密码,固定ip +Set Wi-Fi password and static IP -> **提醒**:以下命令中的 Wi-Fi 名称、密码、IP 地址均为示例,请务必替换为你自己的实际信息。 +> **Note**: The Wi-Fi name, password, and IP address in the following commands are examples. Replace them with your actual information. Bash @@ -79,9 +79,9 @@ sudo nmcli connection up "MERCURY_1812" ``` -### 第一步:安装核心图形组件与浏览器 +### Step 1: Install core graphics components and browser -这里我们坚持“极简主义”,坚决不装多余的桌面环境(如 GNOME/KDE),只装底层驱动、最轻量的窗口管理器(Openbox)、隐藏鼠标工具以及 Chromium 浏览器。 +We adhere to "minimalism", strictly avoiding unnecessary desktop environments (such as GNOME/KDE), installing only low-level drivers, the lightest window manager (Openbox), mouse hiding tools, and the Chromium browser. Bash @@ -100,11 +100,11 @@ sudo apt purge snapd -y ``` -### 第二步:配置 TTY1 开机免密自动登录 +### Step 2: Configure passwordless auto-login for TTY1 on boot -为了避免手动输入账号密码的尴尬,我们通过修改 systemd 服务,让系统一开机就自动以 `xz` 的身份登录。这里使用一键写入命令,彻底避开由于 `nano` 或 `vi` 操作不当导致的保存失败问题。 +To avoid the awkwardness of manually entering credentials, we modify the systemd service to automatically log in as `xz` on boot. Use the one-click write command to completely avoid save failures caused by improper `nano` or `vi` operations. -**1. 创建配置目录:** +**1. Create config directory:** Bash @@ -112,7 +112,7 @@ Bash sudo mkdir -p /etc/systemd/system/getty@tty1.service.d/ ``` -**2. 写入自动登录规则:** +**2. Write auto-login rules:** Bash @@ -120,7 +120,7 @@ Bash echo -e "[Service]\nExecStart=\nExecStart=-/sbin/agetty --autologin xz --noclear %I \$TERM" | sudo tee /etc/systemd/system/getty@tty1.service.d/override.conf ``` -**3. 重载服务并设置默认启动目标:** +**3. Reload service and set default startup target:** Bash @@ -129,13 +129,13 @@ sudo systemctl daemon-reload sudo systemctl set-default multi-user.target ``` -### 第三步:配置登录后自动启动图形界面 +### Step 3: Configure GUI to auto-start after login -系统自动登录后默认停留在黑底白字的命令行,我们需要配置脚本,让它一旦登录立马启动 X11 图形环境。 +After automatic system login, the default state is a black-background white-text command line. Configure a script to launch the X11 graphical environment immediately upon login. -**1. 触发 `startx` 的启动逻辑:** +**1. Trigger the startup logic for `startx`:** -直接将触发代码追加写入你的个人环境配置文件中: +Append trigger code directly to your personal environment config file: Bash @@ -147,7 +147,7 @@ fi EOF ``` -**2. 告诉 `startx` 去启动 Openbox:** +**2. Tell `startx` to start Openbox:** Bash @@ -155,11 +155,11 @@ Bash echo "exec openbox-session" > ~/.xinitrc ``` -### 第四步:配置“铜墙铁壁”的 Openbox 与浏览器 +### Step 4: Configure 'fortress-like' Openbox and browser -这是最核心的一步:关闭屏幕休眠、隐藏鼠标、全屏锁定浏览器,并写一个“死循环”保证浏览器被意外关闭后也能瞬间复活。 +Critical step: Disable screen sleep, hide the mouse, lock the browser in fullscreen, and implement a watchdog loop to instantly restart the browser if it closes unexpectedly. -**1. 创建 Openbox 配置目录:** +**1. Create Openbox config directory:** Bash @@ -167,23 +167,23 @@ Bash mkdir -p ~/.config/openbox ``` -**2. 写入自启动脚本 (`autostart`):** +**2. Write autostart script (`autostart`):** -复制以下整段代码并回车(这会自动把所有保护规则写进文件里): +Copy the entire code block below and press Enter (this automatically writes all protection rules to the file): Bash ``` cat << 'EOF' > ~/.config/openbox/autostart -# 关闭屏幕保护 +# Disable screensaver xset -dpms xset s noblank xset s off -# 隐藏鼠标 +# Hide Cursor unclutter -idle 0.1 -root & -# 死循环启动 Chromium(崩溃或被关也能秒重启) +# Infinite loop to launch Chromium (instant restart on crash or close) while true; do google-chrome \ --kiosk \ @@ -201,9 +201,9 @@ done & EOF ``` -**3. 屏蔽 `Alt+F4` 退出快捷键:** +**3. Disable the `Alt+F4` exit shortcut:** -为了防止别人插上键盘强行关掉窗口,我们把 Openbox 默认的系统快捷键干掉。 +To prevent others from closing the window via keyboard shortcuts, disable Openbox default system shortcuts. Bash @@ -212,9 +212,9 @@ cp /etc/xdg/openbox/rc.xml ~/.config/openbox/ sed -i '//,/<\/keybind>/d' ~/.config/openbox/rc.xml ``` -### 第五步:重启验收成果 +### Step 5: Restart to verify results -如果拔掉网线或不需要等待所有网络上线,可禁用网络等待服务,避免开机卡顿 +If the network cable is unplugged or waiting for all networks to come online is unnecessary, disable the network wait service to avoid boot lag Bash @@ -223,7 +223,7 @@ sudo systemctl mask systemd-networkd-wait-online.service sudo systemctl mask NetworkManager-wait-online.service ``` -隐藏开机信息(GRUB) +Hide boot info (GRUB) Bash @@ -236,7 +236,7 @@ echo 'GRUB_RECORDFAIL_TIMEOUT=0' | sudo tee -a /etc/default/grub sudo update-grub ``` -声音设置成100%,然后 重启: +Set volume to 100%, then restart: Bash @@ -245,11 +245,11 @@ amixer -q sset Master 100% unmute sudo reboot ``` -### 部署唤醒词服务 +### Deploy wake word service -在一体机上部署唤醒词检测服务,需要安装 Python 环境、上传项目文件、配置 Camera 麦克风和开机自启。 +To deploy the wake word detection service on an all-in-one device, install the Python environment, upload project files, configure the Camera microphone, and set up auto-start on boot. -#### 1. 安装 Miniconda +#### 1. Install Miniconda ```bash wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh @@ -260,7 +260,7 @@ rm Miniconda3-latest-Linux-x86_64.sh ``` -确保登录时自动进入conda环境 +Ensure automatic entry into the conda environment upon login ```bash if ! grep -q '.bashrc' ~/.bash_profile; then @@ -274,38 +274,38 @@ fi ``` -#### 2. 创建 Python 虚拟环境 +#### 2. Create Python virtual environment ```bash conda create -n test python=3.10 -y conda activate test ``` -若出现 Terms of Service have not been accepted 错误,执行: +If the 'Terms of Service have not been accepted' error occurs, run: ```bash conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/r ``` -#### 3. 上传项目文件 +#### 3. Upload project files -将开发机上的 `main/digital-human/` 整个目录上传到一体机的 `~/digital-human/` 目录: +Upload the entire `main/digital-human/` directory from the dev machine to the `~/digital-human/` directory on the all-in-one device: ```bash -# 在开发机上执行(将 <一体机IP> 替换为实际 IP) -scp -r main/digital-human/ xz@<一体机IP>:~/digital-human/ +# Execute on the development machine (replace with the actual IP) +scp -r main/digital-human/ xz@:~/digital-human/ ``` -#### 4. 安装系统依赖 +#### 4. Install system dependencies -唤醒词服务需要音频采集库和 ALSA PulseAudio 插件: +The wake word service requires audio capture libraries and ALSA PulseAudio plugins: ```bash sudo apt install libportaudio2 portaudio19-dev libasound2-plugins -y ``` -#### 5. 安装 Python 依赖 +#### 5. Install Python dependencies ```bash cd ~/digital-human/wakeword_runtime @@ -313,58 +313,58 @@ pip install numpy pip install -r requirements.txt ``` -#### 6. 下载唤醒词模型 +#### 6. Download wake word model -模型文件不包含在项目中,需要单独下载配置,详见 [docs/digital-human-wakeword.md](digital-human-wakeword.md) 中的“模型下载”章节。 +Model files are not included in the project and must be downloaded and configured separately. See the "Model Download" section in [docs/digital-human-wakeword.md](digital-human-wakeword.md). -#### 7. 修改 Openbox 自启动脚本 +#### 7. Modify Openbox autostart script -需要在 autostart 中加上 PulseAudio 和 Camera 麦克风配置,并将 Chrome 地址改为测试页面。 +Add PulseAudio and Camera microphone configs to autostart, and change Chrome URL to the test page. -先确认 Camera 麦克风在 PulseAudio 中的设备名: +First verify the Camera microphone device name in PulseAudio: ```bash pulseaudio --start pactl list sources short ``` -找到包含 `USB_Camera` 的那一行,记下完整名称,例如: +Find the line containing `USB_Camera`, note the full name, e.g.: ``` alsa_input.usb-SN0002_2K_USB_Camera_46435000_P030D00_SN0002-02.mono-fallback ``` -然后用完整内容覆盖 autostart(将 `TARGET_MIC` 替换为你的实际设备名): +Then overwrite autostart with the full content (replace `TARGET_MIC` with your actual device name): ```bash cat << 'EOF' > ~/.config/openbox/autostart -# 1. 启动声音服务并稍作等待 +# 1. Start the audio service and wait briefly pulseaudio --start sleep 1 -# 2. 锁定 Camera 的麦克风(请替换为你的实际设备名) +# 2. Lock Camera microphone (replace with your actual device name) TARGET_MIC="alsa_input.usb-SN0002_2K_USB_Camera_46435000_P030D00_SN0002-02.mono-fallback" -# 3. 设为系统默认麦克风 +# 3. Set as system default microphone pactl set-default-source "$TARGET_MIC" -# 4. 解除静音 +# 4. Unmute pactl set-source-mute "$TARGET_MIC" 0 -# 5. 音量拉到 100% +# 5. Set volume to 100% pactl set-source-volume "$TARGET_MIC" 100% -# --- 极简桌面与浏览器环境配置 --- +# --- Minimal desktop and browser environment configuration --- -# 关闭屏幕保护 +# Disable screensaver xset -dpms xset s noblank xset s off -# 隐藏鼠标 +# Hide Cursor unclutter -idle 0.1 -root & -# 死循环启动浏览器(崩溃或被关也能秒重启) +# Start browser in infinite loop (restarts instantly on crash or close) while true; do google-chrome \ --kiosk \ @@ -382,17 +382,17 @@ done & EOF ``` -#### 8. 配置唤醒词服务开机自启 +#### 8. Configure wake word service to start on boot -创建 systemd 服务文件,让唤醒词服务开机自动运行。 +Create a systemd service file to enable the wake word service to run automatically on boot. -先确认当前用户的 UID: +First confirm the current user's UID: ```bash id -u $(whoami) ``` -然后用查到的 UID 替换下面 `1000`(通常第一个用户就是 1000): +Then replace the UID below with the one you found `1000` (the first user is usually 1000): ```bash sudo tee /etc/systemd/system/digital-human.service << 'EOF' @@ -416,13 +416,13 @@ WantedBy=multi-user.target EOF ``` -> **重要说明**: -> - `User=xz` — 替换为你的实际用户名 -> - `/run/user/1000` — 替换为你实际的 UID -> - `WorkingDirectory` 和 `ExecStart` 中的路径 — 替换为你的实际部署路径 -> - `Environment` 中的 PulseAudio 环境变量**必须保留**,否则唤醒词服务和浏览器无法同时使用 Camera 麦克风 +> **Important Note**: +> - `User=xz` - Replace with your actual username +> - `/run/user/1000` - Replace with your actual UID +> - Paths in `WorkingDirectory` and `ExecStart` - Replace with your actual deployment paths +> - The PulseAudio environment variables in `Environment` **must be preserved**, otherwise the wake word service and browser cannot simultaneously use the Camera microphone -启用并启动服务: +Enable and start service: ```bash sudo systemctl daemon-reload @@ -430,13 +430,13 @@ sudo systemctl enable digital-human sudo systemctl start digital-human ``` -#### 9. 常用服务管理命令 +#### 9. Common service management commands ```bash -sudo systemctl start digital-human # 立即启动 -sudo systemctl stop digital-human # 停止 -sudo systemctl restart digital-human # 重启 -sudo systemctl status digital-human # 查看状态 -journalctl -u digital-human -f # 查看实时日志 +sudo systemctl start digital-human # Start now +sudo systemctl stop digital-human # Stop +sudo systemctl restart digital-human # Restart +sudo systemctl status digital-human # View status +journalctl -u digital-human -f # View real-time logs ``` diff --git a/docs/device-call-guide.md b/docs/device-call-guide.md index c3e848400..0a4bbf220 100644 --- a/docs/device-call-guide.md +++ b/docs/device-call-guide.md @@ -1,60 +1,60 @@ -# 设备间相互呼叫插件使用指南 +# Inter-device mutual call plugin usage guide -## 概述 +## Overview -设备呼叫功能允许两个已配置设备之间通过语音/数据通道进行双向通信。设备A呼叫设备B时,系统通过以下流程实现: +The device call feature enables bidirectional communication between two configured devices via voice/data channels. When Device A calls Device B, the system follows this process: ``` -设备A → 授权校验 → MQTT网关 → 设备B远程唤醒 → 建立连接 → 通话建立 +Device A → Authorization Check → MQTT Gateway → Remote Wake-up of Device B → Connection Established → Call Established ``` -## 使用这个功能的前提条件 -1. 你必须要有至少两个设备,每个设备型号必须是`ESP32-S3`,因为只有`ESP32-S3`才支持远程唤醒功能。 -2. 你的设备必须要有`两个麦克风`。但是如果你的设备只有`单个麦克风`,你只是想体验一下这个功能,也是可以的,但是会有强烈的卡顿感。 -3. 你必须使用[全模块部署](Deployment_all.md)本项目,因为你需要`智控台`来管理设备的权限和通信。 -4. 你必须安装并配置好`2026年5月27日`以后的[MQTT网关服务](mqtt-gateway-integration.md),如果你已经部署了MQTT网关服务,请确认代码的版本是`2026年5月27日`之后的版本。 +## Prerequisites for using this feature +1. You must have at least two devices, each of model `ESP32-S3`, because only `ESP32-S3` supports remote wake-up. +2. Your device must have `two microphones`. If your device has only a `single microphone`, you can still try this feature, but expect significant lag. +3. You must use [Full Module Deployment](Deployment_all.md) for this project, as you need the `Console` to manage device permissions and communication. +4. You must install and configure the [MQTT Gateway Service ](mqtt-gateway-integration.md) after `May 27, 2026`. If you have already deployed the MQTT Gateway Service, ensure the code version is after `May 27, 2026`. -以上是使用这个功能的硬性条件,接下来会详细介绍。 +These are the mandatory prerequisites for using this feature. Detailed instructions follow. -## 配置步骤 +## Configuration steps -### 第一步:开启通讯录功能 +### Step 1: Enable the contacts feature -1. 确认你的智控台版本是`0.9.4`或以上版本。 -2. 登录智控台后台 -3. 进入 **系统功能配置** -4. 在左侧功能列表中勾选 **通讯录** -5. 点击 **保存配置** 确认 +1. Ensure your Console version is `0.9.4` or higher. +2. Log in to the Console backend +3. Go to **System Function Config** +4. Check the **Contacts** option in the left-side feature list +5. Click **Save Configuration** to confirm -### 第二步:配置设备间呼叫权限 +### Step 2: Configure inter-device call permissions -1. 在智控台顶部菜单点击 **通讯录** -2. 在左侧智能体下,设备列表中选择你的设备A(支持按 MAC地址 或 备注名 搜索) -3. 在右侧详情面板中,找到目标设备B的称呼设置,例如 **"小王"** -4. 勾选设备B的 **呼叫权限** 复选框 -5. 点击 **保存** +1. Click **Contacts** in the top menu of the Console +2. Under the Agent list on the left, select Device A from the device list (search by MAC address or remark name). +3. In the right-side details panel, find the nickname setting for target device B, e.g., **"Xiao Wang"** +4. Check the **Call Permission** checkbox for Device B +5. Click **Save** -**双向授权说明:** 如需设备A和设备B互相通信,必须在两侧智控台分别配置对方权限。例如: +**Bidirectional Authorization Note:** To enable communication between Device A and Device B, configure mutual permissions in the Console on both sides. For example: -- 在设备A的配置中勾选设备B → 设备A可与设备B通信 -- 在设备B的配置中勾选设备A → 设备B可与设备A通信 +- Check device B in device A's config → Device A can communicate with device B +- Check device A in device B's config → Device B can communicate with device A -### 第三步:在智能体配置添加呼叫工具 +### Step 3: Add the call tool in the Agent config -1. 在智控台顶部菜单点击 **智能体管理** -2. 在刚刚配置设备联系人的相关智能体中点击 **编辑角色** -3. 在右侧详情面板中,点击 **编辑功能** -4. 勾选 **设备呼叫设备** 工具 -5. 点击 **保存配置** 确认 -6. 在外侧再次点击 **保存配置** ,随即重启设备 +1. Click **Agent Management** in the top menu of the Console +2. In the Agent associated with the recently configured device contact, click **Edit Role** +3. In the right-side details panel, click **Edit Features** +4. Check the **Device-to-Device Call** tool +5. Click **Save Configuration** to confirm +6. Click **Save Config** again on the outer layer, then restart the device -### 第四步:固件端添加远程唤醒工具 +### Step 4: Add the remote wake-up tool on the firmware side -1. 在[xiaozhi-esp32](https://github.com/78/xiaozhi-esp32) 代码的基础上增加远程唤醒工具MCP,版本支持为2.1.0至2.2.6(2026年5月29日的版本) -2. 在application.h文件中添加远程唤醒函数声明 +1. Add the remote wake-up tool MCP to the [xiaozhi-esp32](https://github.com/78/xiaozhi-esp32) codebase. Supported versions are 2.1.0 to 2.2.6 (version from May 29, 2026). +2. Add the remote wake-up function declaration in application.h ```cpp void RemoteWakeup(const std::string& reason); ``` -3. 在application.cc文件中添加远程唤醒函数 +3. Add the remote wake-up function in application.cc ```cpp void Application::RemoteWakeup(const std::string& reason){ if (!protocol_) { @@ -96,7 +96,7 @@ } } ``` -4. 在mcp_server.cc文件中添加远程唤醒工具 +4. Add the remote wake-up tool in mcp_server.cc ```cpp AddUserOnlyTool("self.remote_wakeup", "Remote wakeup function with configurable parameters", PropertyList({ @@ -109,40 +109,40 @@ app.RemoteWakeup(reason); return true; ``` -5. 按照 [固件编译烧录指南](firmware-build.md) 完成固件烧录 -6. 无论你的设备是单麦还是双麦,请在编译环节,勾选开启AEC功能! -7. 无论你的设备是单麦还是双麦,请在编译环节,勾选开启AEC功能! -8. 无论你的设备是单麦还是双麦,请在编译环节,勾选开启AEC功能! +5. Complete firmware flashing according to the [Firmware Compilation and Flashing Guide](firmware-build.md) +6. Regardless of whether your device has a single or dual microphone, enable the AEC feature during compilation! +7. Regardless of whether your device has a single or dual microphone, enable the AEC feature during compilation! +8. Regardless of whether your device has a single or dual microphone, enable the AEC feature during compilation! -### 第五步:配置MQTT网关服务 +### Step 5: Configure the MQTT gateway service -1. 部署MQTT网关服务,参考 [MQTT网关集成文档](mqtt-gateway-integration.md) -2. 如果已经部署请确认代码的版本是2026年5月27日的版本 +1. Deploy the MQTT Gateway Service. Refer to [MQTT Gateway Integration Documentation](mqtt-gateway-integration.md) +2. If already deployed, confirm the code version is from May 27, 2026 -## 呼叫流程说明 +## Call flow description -准备两个设备,在智控台上面配置好通讯权限和在智能体中添加呼叫工具之后,在其中一个小智对话那里对他说:”呼叫XXX“,观察设备B是否响应。 +Prepare two devices. After configuring communication permissions in the Console and adding the call tool to the Agent, say "Call XXX" to one Xiaozhi device and observe if Device B responds. -## 常见问题 +## FAQ -### Q: 设备B没有响应呼叫? +### Q: Device B does not respond to the call? -- 检查设备B是否在线(智控台设备状态) -- 确认设备B的固件已正确集成远程唤醒工具 -- 检查MQTT网关连接是否正常 -- 验证双向权限配置是否完整 +- Check if Device B is online (Console device status) +- Ensure Device B's firmware correctly integrates the remote wake-up tool +- Check if the MQTT gateway connection is normal +- Verify if the bidirectional permission config is complete -### Q: 提示"无呼叫权限"? +### Q: Prompt shows "No call permission"? -- 在智控台确认设备A已勾选设备B的呼叫权限 -- 确认配置已保存(非仅修改未保存) +- Verify in the Console that Device A has granted call permissions to Device B +- Ensure the configuration is saved (not just modified) -### Q: 如何确认通讯录功能已开启? +### Q: How to confirm the contacts feature is enabled? -- 智控台顶部菜单如显示"通讯录"入口,则表示已开启 +- If the "Contacts" entry appears in the top menu of the Console, the feature is enabled -### Q: 我叫他呼叫"张山",但是他老是识别成"张三",怎么办? -- 可以查阅你使用的asr服务的文档,确认是否支持热词识别。 -- 如果你用的是`FunASRServer`,可以在容器里的`热词文件`里添加"张山",然后重启容器。 -- 如果你用的是`火山引擎`的服务,可以在`火山引擎的控制台`里添加`热词文件`,然后回到智控台的`模型配置页面`,把`热词文件名称`配置在`火山引擎的tts`上去。 +### Q: I ask it to call "Zhang Shan", but it always recognizes it as "Zhang San". What should I do? +- Check the documentation for your ASR service to confirm if hotword recognition is supported. +- If you use `FunASRServer`, add "Zhang Shan" to the `hotword file` in the container, then restart the container. +- If you use `Volcano Engine` services, add a `hotword file` in the `Volcano Engine Console`, then go to the `Model Configuration page` in the Console and configure the `hotword file name` for `Volcano Engine TTS`. diff --git a/docs/digital-human-wakeword.md b/docs/digital-human-wakeword.md index 613e61506..8a8d63ec0 100644 --- a/docs/digital-human-wakeword.md +++ b/docs/digital-human-wakeword.md @@ -1,33 +1,33 @@ -# 数字人digital-human启动方法 +# Digital human startup method -## 概述 +## Overview -测试页面集成了基于 **Sherpa-ONNX** 的高精度语音唤醒功能,支持自定义唤醒词和实时检测。使用轻量级关键词检测模型,提供毫秒级响应速度。 +The test page integrates high-precision voice wake-up based on **Sherpa-ONNX**, supporting custom wake words and real-time detection. It uses a lightweight keyword spotting model for millisecond-level response times. -## 唤醒词模型 +## Wake word model -### 模型下载(必需) +### Model download (required) -**重要说明**: 项目不包含模型文件,需要提前下载配置。 +**Important note**: The project does not include model files; download and configure them in advance. -### 官方模型下载地址 +### Official model download URL -- **官方模型列表**: -- **推荐模型**: `sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01` +- **Official model list**: +- **Recommended model**: `sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01` -### 下载和配置步骤 +### Download and configuration steps -#### 1. 下载模型包 +#### 1. Download model package ```bash -# 方法1:直接下载(推荐) +# Method 1: Direct download (recommended) cd main/digital-human/wakeword_runtime/ wget https://github.com/k2-fsa/sherpa-onnx/releases/download/kws-models/sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01.tar.bz2 -# 解压 +# Unzip tar xvf sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01.tar.bz2 -# 方法2:使用ModelScope +# Method 2: Use ModelScope pip install modelscope python -c " from modelscope import snapshot_download @@ -35,112 +35,112 @@ snapshot_download('pkufool/sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01 " ``` -#### 2. 配置模型文件 +#### 2. Configure model files -模型包下载后包含以下文件: +Model package contains the following files after download: ``` sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01/ -├── encoder-epoch-12-avg-2-chunk-16-left-64.int8.onnx # 速度优先 +├── encoder-epoch-12-avg-2-chunk-16-left-64.int8.onnx # Speed Priority ├── encoder-epoch-12-avg-2-chunk-16-left-64.onnx -├── encoder-epoch-99-avg-1-chunk-16-left-64.int8.onnx # 速度优先 -├── encoder-epoch-99-avg-1-chunk-16-left-64.onnx # 精度优先 +├── encoder-epoch-99-avg-1-chunk-16-left-64.int8.onnx # Speed Priority +├── encoder-epoch-99-avg-1-chunk-16-left-64.onnx # Accuracy priority ├── decoder-epoch-12-avg-2-chunk-16-left-64.onnx -├── decoder-epoch-99-avg-1-chunk-16-left-64.onnx # 精度优先 -├── joiner-epoch-12-avg-2-chunk-16-left-64.int8.onnx # 速度优先 +├── decoder-epoch-99-avg-1-chunk-16-left-64.onnx # Accuracy priority +├── joiner-epoch-12-avg-2-chunk-16-left-64.int8.onnx # Speed Priority ├── joiner-epoch-12-avg-2-chunk-16-left-64.onnx -├── joiner-epoch-99-avg-1-chunk-16-left-64.int8.onnx # 速度优先 -├── joiner-epoch-99-avg-1-chunk-16-left-64.onnx # 精度优先 -├── tokens.txt # Token映射表(必需) -├── keywords_raw.txt # 模型包里可能附带(可选,runtime 不依赖) -├── keywords.txt # 现成的 -├── test_wavs/ # 测试音频(可选) -├── configuration.json # 模型元信息(可选) -└── README.md # 说明文档(可选) +├── joiner-epoch-99-avg-1-chunk-16-left-64.int8.onnx # Speed Priority +├── joiner-epoch-99-avg-1-chunk-16-left-64.onnx # Accuracy priority +├── tokens.txt # Token mapping table (required) +├── keywords_raw.txt # Model package may include optional assets (runtime does not depend on them) +├── keywords.txt # Ready-made +├── test_wavs/ # Test audio (optional) +├── configuration.json # Model metadata (optional) +└── README.md # Documentation (optional) ``` -#### 3. 选择配置方案 +#### 3. Select config scheme -**方案一:精度优先(推荐)** +**Option 1: Prioritize accuracy (recommended)** ```bash cd sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01 -# 创建模型目录 +# Create model directory mkdir -p ../models -# 复制精度优先的epoch-99 fp32三件套 +# Copy the accuracy-priority epoch-99 fp32 triplet cp encoder-epoch-99-avg-1-chunk-16-left-64.onnx ../models/encoder.onnx cp decoder-epoch-99-avg-1-chunk-16-left-64.onnx ../models/decoder.onnx cp joiner-epoch-99-avg-1-chunk-16-left-64.onnx ../models/joiner.onnx -# 复制配套文件 +# Copy companion files cp tokens.txt ../models/tokens.txt -# keywords_raw.txt 如果模型包里附带,可自行保留;runtime 不依赖它 +# keywords_raw.txt can be kept if included in the model package; runtime does not depend on it ``` -**方案二:速度优先** +**Option 2: Speed priority** ```bash cd sherpa-onnx-kws-zipformer-wenetspeech-3.3M-2024-01-01 -# 创建模型目录 +# Create model directory mkdir -p ../models -# 复制速度优先的epoch-99 int8三件套 +# Copy the speed-priority epoch-99 int8 triplet cp encoder-epoch-99-avg-1-chunk-16-left-64.int8.onnx ../models/encoder.onnx cp decoder-epoch-99-avg-1-chunk-16-left-64.onnx ../models/decoder.onnx cp joiner-epoch-99-avg-1-chunk-16-left-64.int8.onnx ../models/joiner.onnx -# 复制配套文件 +# Copy companion files cp tokens.txt ../models/tokens.txt ``` -**注意事项**: +**Notes: -- **不要混用 fp32 与 int8**:三个模型文件必须保持一致的精度 -- **优先选择 epoch-99**:比 epoch-12 训练更充分,精度更高 -- **必需文件**:`encoder.onnx` + `decoder.onnx` + `joiner.onnx` + `tokens.txt` + `keywords.txt` +- **Do not mix fp32 and int8**: all three model files must use the same precision +- **Prefer epoch-99**: trained more thoroughly than epoch-12, with higher accuracy +- **Required Files**: `encoder.onnx` + `decoder.onnx` + `joiner.onnx` + `tokens.txt` + `keywords.txt` -### 最终模型文件结构 +### Final model file structure -配置完成后,模型文件应放在 `wakeword_runtime/models/` 目录下,完整路径为 `main/digital-human/wakeword_runtime/models/`: +After configuration, model files should be placed in the `wakeword_runtime/models/` directory. The full path is `main/digital-human/wakeword_runtime/models/`: ``` wakeword_runtime/models/ -├── encoder.onnx # 编码器模型(重命名后) -├── decoder.onnx # 解码器模型(重命名后) -├── joiner.onnx # 连接器模型(重命名后) -├── tokens.txt # 拼音 Token 映射表(228行版本) -├── keywords.txt # 关键词配置文件(首次启动自动生成) -└── keywords_raw.txt # 可选,runtime 不依赖 +├── encoder.onnx # Encoder model (after renaming) +├── decoder.onnx # Decoder model (after renaming) +├── joiner.onnx # Connector model (after rename) +├── tokens.txt # Pinyin token mapping table (228-line version) +├── keywords.txt # Keyword config file (auto-generated on first launch) +└── keywords_raw.txt # Optional, runtime independent ``` -## 启动方式 +## Startup method -在 `main/digital-human` 目录执行: +Execute in `main/digital-human` directory: ```bash pip install -r wakeword_runtime/requirements.txt python start.py ``` -启动后默认地址: +Default address after startup: -- 页面地址:`http://127.0.0.1:8006/index.html` -- 事件桥地址:`ws://127.0.0.1:8006/wakeword-ws` -- 健康检查:`http://127.0.0.1:8006/health` +- Page address: `http://127.0.0.1:8006/index.html` +- Event bridge address: `ws://127.0.0.1:8006/wakeword-ws` +- Health check: `http://127.0.0.1:8006/health` -停止方式: +Stop Method: -- 在运行终端按 `Ctrl+C` -- 会同时停止静态页面服务、事件桥和唤醒词检测流程 +- Press `Ctrl+C` in the running terminal +- Simultaneously stops static page service, event bridge, and wake word detection process -## 配置文件说明 +## Config file description -配置文件位于 [main/digital-human/wakeword_runtime/config.json](../main/digital-human/wakeword_runtime/config.json)。 +The config file is located at [main/digital-human/wakeword_runtime/config.json](../main/digital-human/wakeword_runtime/config.json). -当前主要配置项: +Current main configuration items: ```json { @@ -170,51 +170,51 @@ python start.py } ``` -各字段含义: +Field descriptions: -| 参数 | 说明 | +| Parameter | Description | | --- | --- | -| `wakeword.enabled` | 是否启用本地唤醒词检测 | -| `model_dir` | 模型和词表所在目录 | -| `audio.input_device` | 麦克风输入设备,默认使用系统默认设备 | -| `audio.sample_rate` | 采样率,默认 `16000` | -| `audio.channels` | 声道数,默认 `1` | -| `detector.num_threads` | 检测器线程数 | -| `detector.provider` | 推理 provider,当前通常为 `cpu` | -| `detector.max_active_paths` | 搜索路径数 | -| `detector.keywords_score` | 关键词增强分数 | -| `detector.keywords_threshold` | 检测阈值 | -| `detector.num_trailing_blanks` | 尾随空白数量 | -| `detector.cooldown_seconds` | 连续触发冷却时间 | -| `logging.level` | 日志等级 | -| `logging.dir` | 日志目录 | -| `logging.file` | 日志文件名 | +| `wakeword.enabled` | Enable local wake word detection | +| `model_dir` | Directory containing the model and vocabulary | +| `audio.input_device` | Microphone input device, defaults to system default device | +| `audio.sample_rate` | Sample rate, default `16000` | +| `audio.channels` | Number of channels, default `1` | +| `detector.num_threads` | Detector thread count | +| `detector.provider` | Inference provider, currently usually `cpu` | +| `detector.max_active_paths` | Search path count | +| `detector.keywords_score` | Keyword enhancement score | +| `detector.keywords_threshold` | Detection threshold | +| `detector.num_trailing_blanks` | Trailing whitespace count | +| `detector.cooldown_seconds` | Continuous trigger cooldown time | +| `logging.level` | Log level | +| `logging.dir` | Log directory | +| `logging.file` | Log file name | -## 推荐使用流程 +## Recommended workflow -### 首次使用 +### First Use -1. 准备 `models/` 目录下的模型文件和 `tokens.txt` -2. 确认 `models/keywords.txt` 存在 -3. 在 `digital-human` 目录运行 `python start.py` -4. 浏览器打开 `http://127.0.0.1:8006/index.html` -5. 进入设置页检查“唤醒词”配置 +1. Prepare model files and `tokens.txt` in the `models/` directory +2. Verify `models/keywords.txt` exists +3. Run `python start.py` in the `digital-human` directory +4. Open `http://127.0.0.1:8006/index.html` in the browser +5. Go to the settings page and check the "wake word" config -### 修改唤醒词 +### Modify Wake Word -1. 打开数字人页面设置 -2. 切到“唤醒词”页签 -3. 修改启用状态或唤醒词列表 -4. 点击“应用唤醒词” -5. 根据提示决定是否立即重启 +1. Open digital human page settings +2. Switch to "Wake Word" tab +3. Modify enabled status or wake word list +4. Click " to apply the wake word" +5. Decide whether to restart immediately based on prompt -### 禁用唤醒词 +### Disable wake word -1. 将“启用本地唤醒词”改成禁用 -2. 点击“应用唤醒词” -3. 建议立即重启一次 +1. Change "Enable local wake word" to disabled +2. Click " to apply the wake word" +3. Recommend immediate restart -禁用后: +When disabled: -- 页面与事件桥仍然可用 -- 唤醒词检测不会继续运行 +- Page and event bridge remain available +- Wake word detection will not continue running diff --git a/docs/web-search-integration.md b/docs/web-search-integration.md index cb694e912..8e3bcb713 100644 --- a/docs/web-search-integration.md +++ b/docs/web-search-integration.md @@ -1,74 +1,74 @@ -# 联网搜索插件使用指南 +# Web search plugin usage guide -## 功能简介 +## Feature description -联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持三个搜索源:秘塔(Metaso)、Tavily和Serply,用户可根据需要选择其中一个。 +The web search plugin `web_search` supports real-time web search during conversations and returns results. The plugin supports three search sources: Metaso, Tavily, and Serply. Users can choose one as needed. -## API Key申请指南 +## API Key Application Guide -目前我们适配了`秘塔搜索`、`Tavily搜索`和`Serply搜索`。 -- Tavily搜索:每个月1000次免费额度。 -- 秘塔搜索:拥有较为优质的国内数据源。 -- Serply搜索:返回谷歌搜索结果,注册赠送2500次免费额度,额度用完后需要付费。 +We currently support `Mita Search `,`Tavily Search` and `Serply Search`. +- Tavily Search: 1000 free requests per month. +- Metaso Search: Offers high-quality domestic data sources. +- Serply Search: Returns Google search results. Registration grants 2500 free credits; payment is required after credits are exhausted. -## API Key申请指南 +## API Key Application Guide -### 方式一:使用秘塔搜索 +### Method 1: Use Metaso Search -- 访问 [秘塔搜索API](https://metaso.cn/search-api/api-keys),注册并登录账号 -- 在API密钥管理页面,点击"创建新的Key" -- 复制生成的API Key(以 `mk-` 为前缀),这是配置所需的关键信息 +- Visit [Metaso Search API](https://metaso.cn/search-api/api-keys), register and log in +- On the API key management page, click " to create a new Key" +- Copy the generated API Key (prefixed with `mk-`), which is essential for configuration -### 方式二:使用Tavily搜索 +### Method 2: Use Tavily search -- 访问 [Tavily控制台](https://app.tavily.com/home),注册并登录账号 -- 在控制台中创建API Key -- 复制生成的API Key(以 `tvly-` 为前缀),这是配置所需的关键信息 +- Visit [Tavily Console ](https://app.tavily.com/home), register and log in +- Create an API Key in the Console +- Copy the generated API Key (prefixed with `tvly-`); this is critical for configuration -### 方式三:使用Serply搜索 +### Method 3: Use Serply search -- 访问 [Serply](https://serply.io),注册并登录账号 -- 在控制台中创建API Key -- 复制生成的API Key,这是配置所需的关键信息 -- 接口说明见 [Serply文档](https://serply.io/docs) +- Visit [Serply](https://serply.io), register and log in to your account +- Create an API Key in the Console +- Copy the generated API Key; this is critical information for configuration +- See [Serply documentation ](https://serply.io/docs) for interface details -## 配置方式 +## Configuration Method -### 方式1. 使用智控台部署(推荐) +### Method 1. Deploy via Console (recommended) -- 登录智控台 -- 进入"配置角色"页面,选择要配置的智能体 -- 点击"编辑功能"按钮,在右侧参数配置区域找到"联网搜索"插件 -- 勾选"联网搜索" -- 填入搜索源(`metaso`、`tavily`或`serply`),并将对应的`API Key`填入配置项 -- 保存配置,再保存智能体配置 +- Log in to Console +- Go to the "Configure Role" page and select the Agent to configure +- Click the "Edit Function" button, find the "Web Search" plugin in the parameter configuration area on the right +- Check " for online search" +- Fill in the search source (`metaso`, `tavily`, or `serply`) and enter the corresponding `API Key` in the config +- Save config, then save agent config -### 方式2. 单模块xiaozhi-server部署 +### Method 2. Single-module xiaozhi-server deployment -在 `data/.config.yaml` 中配置: +Configure in `data/.config.yaml`: -- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily` 或 `serply` -- 将申请到的API Key填入 `api_key` +- Fill search source into `provider`, valid values are `metaso`, `tavily` or `serply` +- Enter the obtained API Key into `api_key` ```yaml plugins: web_search: provider: "metaso" - api_key: "你的API Key" + api_key: "your API Key" ``` -如需自定义返回结果数量和工具描述,可额外配置 `max_results` 和 `description`: +To customize the number of returned results and tool descriptions, additionally configure `max_results` and `description`: ```yaml plugins: web_search: provider: "metaso" - description: "联网搜索工具。当用户明确需要联网搜索问题时使用此工具。" + description: " web search tool. Use this tool when the user explicitly needs to search the web." max_results: 5 - api_key: "你的API Key" + api_key: "your API Key" ``` -同时在 `functions` 列表中确保已启用 `web_search`: +Also ensure `web_search` is enabled in the `functions` list: ```yaml plugins: @@ -76,4 +76,4 @@ plugins: - web_search ``` -配置完成后重启服务即可生效。 +Restart service after configuration to apply changes. diff --git a/main/digital-human/index.html b/main/digital-human/index.html index cfb72637f..88587a808 100644 --- a/main/digital-human/index.html +++ b/main/digital-human/index.html @@ -1,34 +1,34 @@ - + - 小智数字人页面 + Xiaozhi Digital Human Page - + - + - + - + - + diff --git a/main/digital-human/js/app.js b/main/digital-human/js/app.js index 09ab35063..de03b8845 100644 --- a/main/digital-human/js/app.js +++ b/main/digital-human/js/app.js @@ -1,4 +1,4 @@ -// 主应用入口 +// Main App Entry import { checkOpusLoaded, initOpusEncoder } from './core/audio/opus-codec.js?v=0205'; import { getAudioPlayer } from './core/audio/player.js?v=0205'; import { checkMicrophoneAvailability, isHttpNonLocalhost } from './core/audio/recorder.js?v=0205'; @@ -7,7 +7,7 @@ import { startWakewordBridgeListener } from './core/network/wakeword-bridge.js?v import { uiController } from './ui/controller.js?v=0205'; import { log } from './utils/logger.js?v=0205'; -// 辅助函数:将Base64数据转换为Blob +// Helper function: Convert Base64 data to Blob function dataURItoBlob(dataURI) { const byteString = atob(dataURI.split(',')[1]); const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; @@ -19,7 +19,7 @@ function dataURItoBlob(dataURI) { return new Blob([ab], { type: mimeString }); } -// 应用类 +// Application type class App { constructor() { this.uiController = null; @@ -29,64 +29,64 @@ class App { this.currentFacingMode = 'user'; } - // 初始化应用 + // Initialize application async init() { - log('正在初始化应用...', 'info'); - // 初始化UI控制器 + log('Initializing application...', 'info'); + // Initialize UI controller this.uiController = uiController; this.uiController.init(); - // 检查Opus库 + // Check Opus library checkOpusLoaded(); - // 初始化Opus编码器 + // Initialize Opus encoder initOpusEncoder(); - // 初始化音频播放器 + // Initialize audio player this.audioPlayer = getAudioPlayer(); await this.audioPlayer.start(); - // 初始化MCP工具 + // Initialize MCP tools initMcpTools(); - // 初始化本地唤醒事件监听 + // Initialize local wake event listener startWakewordBridgeListener(); - // 检查麦克风可用性 + // Check microphone availability await this.checkMicrophoneAvailability(); - // 检查摄像头可用性 + // Check camera availability this.checkCameraAvailability(); - // 初始化Live2D + // Initialize Live2D await this.initLive2D(); - // 初始化摄像头 + // Initialize camera this.initCamera(); - // 关闭加载loading + // Close loading indicator this.setModelLoadingStatus(false); - log('应用初始化完成', 'success'); + log('Application initialization complete', 'success'); } - // 初始化Live2D + // Initialize Live2D async initLive2D() { try { - // 检查Live2DManager是否已加载 + // Check if Live2DManager is loaded if (typeof window.Live2DManager === 'undefined') { - throw new Error('Live2DManager未加载,请检查脚本引入顺序'); + throw new Error('Live2DManager not loaded, check script import order'); } this.live2dManager = new window.Live2DManager(); await this.live2dManager.initializeLive2D(); - // 更新UI状态 + // Update UI state const live2dStatus = document.getElementById('live2dStatus'); if (live2dStatus) { - live2dStatus.textContent = '● 已加载'; + live2dStatus.textContent = '● Loaded'; live2dStatus.className = 'status loaded'; } - log('Live2D初始化完成', 'success'); + log('Live2D initialization complete', 'success'); } catch (error) { - log(`Live2D初始化失败: ${error.message}`, 'error'); - // 更新UI状态 + log(`Live2D initialization failed: ${error.message}`, 'error'); + // Update UI state const live2dStatus = document.getElementById('live2dStatus'); if (live2dStatus) { - live2dStatus.textContent = '● 加载失败'; + live2dStatus.textContent = '● Load failed'; live2dStatus.className = 'status error'; } } } - // 设置model加载状态 + // Set model loading status setModelLoadingStatus(isLoading) { const modelLoading = document.getElementById('modelLoading'); if (modelLoading) { @@ -95,24 +95,24 @@ class App { } /** - * 检查麦克风可用性 - * 在应用初始化时调用,检查麦克风是否可用并更新UI状态 + * Check microphone availability + * Call during app initialization to check microphone availability and update UI state */ async checkMicrophoneAvailability() { try { const isAvailable = await checkMicrophoneAvailability(); const isHttp = isHttpNonLocalhost(); - // 保存可用性状态到全局变量 + // Save availability status to global variable window.microphoneAvailable = isAvailable; window.isHttpNonLocalhost = isHttp; - // 更新UI + // Update UI if (this.uiController) { this.uiController.updateMicrophoneAvailability(isAvailable, isHttp); } - log(`麦克风可用性检查完成: ${isAvailable ? '可用' : '不可用'}`, isAvailable ? 'success' : 'warning'); + log(`Microphone availability check complete: ${isAvailable ? 'Available' : 'Unavailable'}`, isAvailable ? 'success' : 'warning'); } catch (error) { - log(`检查麦克风可用性失败: ${error.message}`, 'error'); - // 默认设置为不可用 + log(`Failed to check microphone availability: ${error.message}`, 'error'); + // Set default to unavailable window.microphoneAvailable = false; window.isHttpNonLocalhost = isHttpNonLocalhost(); if (this.uiController) { @@ -121,13 +121,13 @@ class App { } } - // 检查摄像头可用性 + // Check camera availability checkCameraAvailability() { window.cameraAvailable = true; - log('摄像头可用性检查完成: 默认已绑定验证码', 'success'); + log('Camera availability check complete: default verification code bound', 'success'); } - // 初始化摄像头 + // Initialize camera async initCamera() { const cameraContainer = document.getElementById('cameraContainer'); const cameraVideo = document.getElementById('cameraVideo'); @@ -136,7 +136,7 @@ class App { const dialBtn = document.getElementById('dialBtn'); if (!cameraContainer || !cameraVideo) { - log('摄像头元素未找到,跳过初始化', 'warning'); + log('Camera element not found, skipping initialization', 'warning'); return Promise.resolve(false); } @@ -190,10 +190,10 @@ class App { window.startCamera = async () => { try { if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - log('浏览器不支持摄像头API', 'warning'); + log('Browser does not support camera API', 'warning'); return false; } - log('正在请求摄像头权限...', 'info'); + log('Requesting camera permission...', 'info'); this.cameraStream = await navigator.mediaDevices.getUserMedia({ video: { width: 180, height: 240, facingMode: this.currentFacingMode }, audio: false @@ -206,23 +206,23 @@ class App { } cameraContainer.classList.add('active'); - // 切换时挂断情况 + // Hang up on switch const hasActive = dialBtn.classList.contains('dial-active'); if (!hasActive) { cameraContainer.classList.remove('active'); cameraSwitch.classList.remove('active'); window.stopCamera(); } - log('摄像头已启动', 'success'); + log('Camera started', 'success'); return true; } catch (error) { - log(`启动摄像头失败: ${error.name} - ${error.message}`, 'error'); + log(`Failed to start camera: ${error.name} - ${error.message}`, 'error'); if (error.name === 'NotAllowedError') { - log('摄像头权限被拒绝,请检查浏览器设置', 'warning'); + log('Camera permission denied, check browser settings', 'warning'); } else if (error.name === 'NotFoundError') { - log('未找到摄像头设备', 'warning'); + log('Camera device not found', 'warning'); } else if (error.name === 'NotReadableError') { - log('摄像头已被其他程序占用', 'warning'); + log('Camera is occupied by another program', 'warning'); } return false; } @@ -233,7 +233,7 @@ class App { this.cameraStream.getTracks().forEach(track => track.stop()); this.cameraStream = null; cameraVideo.srcObject = null; - log('摄像头已关闭', 'info'); + log('Camera closed', 'info'); } }; @@ -263,16 +263,16 @@ class App { } }; - window.takePhoto = (question = '描述一下看到的物品') => { + window.takePhoto = (question = 'Describe the visible object') => { return new Promise(async (resolve) => { const canvas = document.createElement('canvas'); const video = cameraVideo; if (!video || video.readyState !== video.HAVE_ENOUGH_DATA) { - log('无法拍照:摄像头未就绪', 'warning'); + log('Unable to capture photo: camera not ready', 'warning'); resolve({ success: false, - error: '摄像头未就绪,请确保已连接且摄像头已启动' + error: 'Camera not ready, ensure it is connected and started' }); return; } @@ -283,7 +283,7 @@ class App { ctx.drawImage(video, 0, 0, canvas.width, canvas.height); const photoData = canvas.toDataURL('image/jpeg', 0.8); - log(`拍照成功,图像数据长度: ${photoData.length}`, 'success'); + log(`Photo captured successfully, image data length: ${photoData.length}`, 'success'); try { const xz_tester_vision = localStorage.getItem('xz_tester_vision'); @@ -293,15 +293,15 @@ class App { try { visionInfo = JSON.parse(xz_tester_vision); } catch (err) { - throw new Error(`视觉配置解析失败`); + throw new Error(`Failed to parse vision config`); } const { url, token } = visionInfo || {}; if (!url || !token) { - throw new Error('视觉分析失败:配置缺少接口地址(url)或令牌(token)'); + throw new Error('Visual analysis failed: config missing url or token'); } - log(`正在发送图片到视觉分析接口: ${url}`, 'info'); + log(`Sending image to vision analysis API: ${url}`, 'info'); const deviceId = document.getElementById('deviceMac')?.value || ''; const clientId = document.getElementById('clientId')?.value || 'web_test_client'; @@ -325,7 +325,7 @@ class App { } const analysisResult = await response.json(); - log(`视觉分析完成: ${JSON.stringify(analysisResult).substring(0, 200)}...`, 'success'); + log(`Visual analysis complete: ${JSON.stringify(analysisResult).substring(0, 200)}...`, 'success'); resolve({ success: true, @@ -336,10 +336,10 @@ class App { vision_analysis: analysisResult }); } else { - log('未配置视觉分析服务', 'warning'); + log('Visual analysis service not configured', 'warning'); } } catch (error) { - log(`视觉分析失败: ${error.message}`, 'error'); + log(`Visual analysis failed: ${error.message}`, 'error'); resolve({ success: true, message: question, @@ -349,25 +349,25 @@ class App { vision_analysis: { success: false, error: error.message, - fallback: '无法连接到视觉分析服务' + fallback: 'Unable to connect to visual analysis service' } }); } }); }; - log('摄像头初始化完成', 'success'); + log('Camera initialization complete', 'success'); resolve(true); }); } } -// 创建并启动应用 +// Create and start app const app = new App(); -// 将应用实例暴露到全局,供其他模块访问 +// Expose the application instance globally for access by other modules window.chatApp = app; document.addEventListener('DOMContentLoaded', () => { - // 初始化应用 + // Initialize application app.init(); }); export default app; diff --git a/main/digital-human/js/config/default-mcp-tools.json b/main/digital-human/js/config/default-mcp-tools.json index 13ee66681..02d8fda04 100644 --- a/main/digital-human/js/config/default-mcp-tools.json +++ b/main/digital-human/js/config/default-mcp-tools.json @@ -62,7 +62,7 @@ "mockResponse": { "success": true, "volume": "${volume}", - "message": "音量已设置为 ${volume}" + "message": "Volume set to ${volume}" } }, { @@ -84,7 +84,7 @@ "mockResponse": { "success": true, "brightness": "${brightness}", - "message": "亮度已设置为 ${brightness}" + "message": "Brightness set to ${brightness}" } } ] \ No newline at end of file diff --git a/main/digital-human/js/config/manager.js b/main/digital-human/js/config/manager.js index 50a0c18a0..1d8fd6b2b 100644 --- a/main/digital-human/js/config/manager.js +++ b/main/digital-human/js/config/manager.js @@ -1,9 +1,9 @@ -// 配置管理模块 +// Config management module -// 默认唤醒词列表 -export const DEFAULT_WAKE_WORDS = '你好小智\n你好小志\n小爱同学\n你好小鑫\n你好小新\n小美同学\n小龙小龙\n喵喵同学\n小滨小滨\n小冰小冰\n嘿你好呀'; +// Default wake word list +export const DEFAULT_WAKE_WORDS = 'Alexa\nHi ESP\nJarvis\ncomputer\nHey Willow\nSophia\nHey Wanda\nHi Jolly\nHi Fairy\nHey Printer\nMycroft\nHi Joy\nHi Jason\nAstrolabe\nHey Ily\nBlue Chip\nHi Lily'; -// 生成随机MAC地址 +// Generate random MAC address function generateRandomMac() { const hexDigits = '0123456789ABCDEF'; let mac = ''; @@ -16,7 +16,7 @@ function generateRandomMac() { return mac; } -// 加载配置 +// Load config export function loadConfig() { const deviceMacInput = document.getElementById('deviceMac'); const deviceNameInput = document.getElementById('deviceName'); @@ -26,7 +26,7 @@ export function loadConfig() { const wakewordEnabledInput = document.getElementById('wakewordEnabled'); const wakewordListInput = document.getElementById('wakewordList'); - // 从localStorage加载MAC地址,如果没有则生成新的 + // Load MAC address from localStorage, generate a new one if missing let savedMac = localStorage.getItem('xz_tester_deviceMac'); if (!savedMac) { savedMac = generateRandomMac(); @@ -34,7 +34,7 @@ export function loadConfig() { } deviceMacInput.value = savedMac; - // 从localStorage加载其他配置 + // Load other configs from localStorage const savedDeviceName = localStorage.getItem('xz_tester_deviceName'); if (savedDeviceName) { deviceNameInput.value = savedDeviceName; @@ -74,7 +74,7 @@ export function loadConfig() { } } -// 保存配置 +// Save config export function saveConfig() { const deviceMacInput = document.getElementById('deviceMac'); const deviceNameInput = document.getElementById('deviceName'); @@ -101,16 +101,16 @@ export function saveConfig() { } } -// 获取配置值 +// Get config value export function getConfig() { - // 从DOM获取值 + // Get value from DOM const deviceMac = document.getElementById('deviceMac')?.value.trim() || ''; const deviceName = document.getElementById('deviceName')?.value.trim() || ''; const clientId = document.getElementById('clientId')?.value.trim() || ''; const emojiEnabled = document.getElementById('emojiEnabled')?.value !== 'false'; return { - deviceId: deviceMac, // 使用MAC地址作为deviceId + deviceId: deviceMac, // Use MAC address as deviceId deviceName, deviceMac, clientId, @@ -118,7 +118,7 @@ export function getConfig() { }; } -// 保存连接URL +// Save connection URL export function saveConnectionUrls() { const otaUrl = document.getElementById('otaUrl').value.trim(); const wsUrl = document.getElementById('serverUrl').value.trim(); diff --git a/main/digital-human/js/core/audio/recorder.js b/main/digital-human/js/core/audio/recorder.js index 3a3279333..7ca91adb9 100644 --- a/main/digital-human/js/core/audio/recorder.js +++ b/main/digital-human/js/core/audio/recorder.js @@ -102,18 +102,18 @@ export class AudioRecorder { this.processPCMBuffer(event.data.buffer); } }; - log('使用AudioWorklet处理音频', 'success'); + log('Processing audio with AudioWorklet', 'success'); const silent = this.audioContext.createGain(); silent.gain.value = 0; audioProcessor.connect(silent); silent.connect(this.audioContext.destination); return { node: audioProcessor, type: 'worklet' }; } else { - log('AudioWorklet不可用,使用ScriptProcessorNode作为后备方案', 'warning'); + log('AudioWorklet unavailable, falling back to ScriptProcessorNode', 'warning'); return this.createScriptProcessor(); } } catch (error) { - log(`创建音频处理器失败: ${error.message},尝试后备方案`, 'error'); + log(`Failed to create audio processor: ${error.message}, trying fallback`, 'error'); return this.createScriptProcessor(); } } @@ -136,10 +136,10 @@ export class AudioRecorder { silent.gain.value = 0; scriptProcessor.connect(silent); silent.connect(this.audioContext.destination); - log('使用ScriptProcessorNode作为后备方案成功', 'warning'); + log('Successfully used ScriptProcessorNode as fallback', 'warning'); return { node: scriptProcessor, type: 'processor' }; } catch (fallbackError) { - log(`后备方案也失败: ${fallbackError.message}`, 'error'); + log(`Fallback also failed: ${fallbackError.message}`, 'error'); return null; } } @@ -162,7 +162,7 @@ export class AudioRecorder { // Encode and send Opus data encodeAndSendOpus(pcmData = null) { if (!this.opusEncoder) { - log('Opus编码器未初始化', 'error'); + log('Opus encoder not initialized', 'error'); return; } try { @@ -175,11 +175,11 @@ export class AudioRecorder { try { this.websocket.send(opusData.buffer); } catch (error) { - log(`WebSocket发送错误: ${error.message}`, 'error'); + log(`WebSocket send error: ${error.message}`, 'error'); } } } else { - log('Opus编码失败,未返回有效数据', 'error'); + log('Opus encoding failed, no valid data returned', 'error'); } } else { if (this.pcmDataBuffer.length > 0) { @@ -195,7 +195,7 @@ export class AudioRecorder { } } } catch (error) { - log(`Opus编码错误: ${error.message}`, 'error'); + log(`Opus encoding error: ${error.message}`, 'error'); } } @@ -204,10 +204,10 @@ export class AudioRecorder { if (this.isRecording) return false; try { if (!this.initEncoder()) { - log('无法开始录音: Opus编码器初始化失败', 'error'); + log('Cannot start recording: Opus encoder initialization failed', 'error'); return false; } - log('请至少录制1-2秒音频以确保收集足够的数据', 'info'); + log('Record at least 1-2 seconds to ensure sufficient data collection', 'info'); const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, sampleRate: 16000, channelCount: 1 } }); this.audioContext = this.getAudioContext(); if (this.audioContext.state === 'suspended') { @@ -215,7 +215,7 @@ export class AudioRecorder { } const processorResult = await this.createAudioProcessor(); if (!processorResult) { - log('无法创建音频处理器', 'error'); + log('Failed to create audio processor', 'error'); return false; } this.audioProcessor = processorResult.node; @@ -234,9 +234,9 @@ export class AudioRecorder { } // Send listening start message if (this.websocket && this.websocket.readyState === WebSocket.OPEN) { - log(`已发送录音开始消息`, 'info'); + log(`Sent recording start message`, 'info'); } else { - log('WebSocket未连接,无法发送开始消息', 'error'); + log('WebSocket not connected, cannot send start message', 'error'); return false; } // Start visualization @@ -256,10 +256,10 @@ export class AudioRecorder { this.onRecordingStart(recordingSeconds); } }, 100); - log('已开始PCM直接录音', 'success'); + log('PCM direct recording started', 'success'); return true; } catch (error) { - log(`直接录音启动错误: ${error.message}`, 'error'); + log(`Direct recording start error: ${error.message}`, 'error'); this.isRecording = false; return false; } @@ -308,15 +308,15 @@ export class AudioRecorder { if (this.websocket && this.websocket.readyState === WebSocket.OPEN) { const emptyOpusFrame = new Uint8Array(0); this.websocket.send(emptyOpusFrame); - log('已发送录音停止信号', 'info'); + log('Recording stop signal sent', 'info'); } if (this.onRecordingStop) { this.onRecordingStop(); } - log('已停止PCM直接录音', 'success'); + log('PCM direct recording stopped', 'success'); return true; } catch (error) { - log(`直接录音停止错误: ${error.message}`, 'error'); + log(`Direct recording stop error: ${error.message}`, 'error'); return false; } } @@ -344,7 +344,7 @@ export function getAudioRecorder() { export async function checkMicrophoneAvailability() { // Check if browser supports getUserMedia API if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - log('浏览器不支持getUserMedia API', 'warning'); + log('Browser does not support getUserMedia API', 'warning'); return false; } try { @@ -352,10 +352,10 @@ export async function checkMicrophoneAvailability() { const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, sampleRate: 16000, channelCount: 1 } }); // Immediately stop all tracks to release microphone stream.getTracks().forEach(track => track.stop()); - log('麦克风可用性检查成功', 'success'); + log('Microphone availability check succeeded', 'success'); return true; } catch (error) { - log(`麦克风不可用: ${error.message}`, 'warning'); + log(`Microphone unavailable: ${error.message}`, 'warning'); return false; } } diff --git a/main/digital-human/js/core/network/wakeword-bridge.js b/main/digital-human/js/core/network/wakeword-bridge.js index ea4087a82..cc69ddbbf 100644 --- a/main/digital-human/js/core/network/wakeword-bridge.js +++ b/main/digital-human/js/core/network/wakeword-bridge.js @@ -16,7 +16,7 @@ export function startWakewordBridgeListener() { } shouldReconnect = true; - log('正在连接本地唤醒事件桥...', 'info'); + log('Connecting to local wake event bridge...', 'info'); tryConnect(); return wakewordSocket; } @@ -28,15 +28,15 @@ function tryConnect() { wakewordSocket = new WebSocket(bridgeUrl); wakewordSocket.onopen = () => { reconnectAttempts = 0; - log(`本地唤醒事件桥已连接: ${bridgeUrl}`, 'success'); - // 连接成功后自动保存地址,刷新后仍能记住 + log(`Local wake event bridge connected: ${bridgeUrl}`, 'success'); + // Auto-save address after successful connection, persists after refresh localStorage.setItem('xz_tester_wakewordWsUrl', bridgeUrl); const urlInput = document.getElementById('wakewordWsUrl'); if (urlInput) urlInput.value = bridgeUrl; }; wakewordSocket.onerror = () => { - log(`本地唤醒事件桥连接失败: ${bridgeUrl}`, 'error'); + log(`Local wake event bridge connection failed: ${bridgeUrl}`, 'error'); }; wakewordSocket.onmessage = async (event) => { @@ -48,12 +48,12 @@ function tryConnect() { } if (message.success === false) { - log(`本地唤醒事件桥返回错误: ${message.error || '未知错误'}`, 'error'); + log(`Local wake event bridge returned error: ${message.error || 'Unknown error'}`, 'error'); return; } if (message.type === 'bridge_connected') { - log('本地唤醒监听已就绪', 'info'); + log('Local wake word listener ready', 'info'); if (onNextBridgeConnectedCallback) { const cb = onNextBridgeConnectedCallback; onNextBridgeConnectedCallback = null; @@ -63,28 +63,28 @@ function tryConnect() { } if (message.type === 'service_ready') { - log('本地唤醒服务已启动', 'info'); + log('Local wake word service started', 'info'); return; } if (message.type === 'wakeword_config') { uiController.applyWakewordConfig(message.payload || {}); - log('已同步本地唤醒词配置', 'info'); + log('Local wake word configuration synced', 'info'); return; } if (message.type === 'service_stopping') { - log('本地唤醒服务正在停止', 'warning'); + log('Local wake word service stopping', 'warning'); return; } if (message.type === 'wake_word_detected') { - const wakeWord = message.payload?.wake_word || '唤醒词'; - log(`检测到本地唤醒事件: ${wakeWord}`, 'info'); + const wakeWord = message.payload?.wake_word || 'wake word'; + log(`Local wake event detected: ${wakeWord}`, 'info'); await uiController.triggerWakewordDial(wakeWord); } } catch (error) { - log(`解析本地唤醒事件失败: ${error.message}`, 'error'); + log(`Failed to parse local wake word event: ${error.message}`, 'error'); } }; @@ -93,7 +93,7 @@ function tryConnect() { wakewordSocket = null; } - rejectAllWakewordRequests('本地唤醒事件桥已断开'); + rejectAllWakewordRequests('Local wake event bridge disconnected'); if (!shouldReconnect) { return; @@ -105,7 +105,7 @@ function tryConnect() { reconnectAttempts += 1; const delay = Math.min(1000 * reconnectAttempts, 5000); - log(`本地唤醒事件桥将在 ${delay}ms 后重连: ${bridgeUrl}`, 'warning'); + log(`Local wake event bridge will reconnect in ${delay}ms: ${bridgeUrl}`, 'warning'); reconnectTimer = window.setTimeout(() => { reconnectTimer = null; tryConnect(); @@ -114,7 +114,7 @@ function tryConnect() { return wakewordSocket; } catch (error) { - log(`启动本地唤醒监听失败: ${error.message}`, 'error'); + log(`Failed to start local wake word listener: ${error.message}`, 'error'); return null; } } @@ -138,7 +138,7 @@ export function stopWakewordBridgeListener() { export function sendWakewordBridgeMessage(type, payload = {}, requestId = null) { if (!wakewordSocket || wakewordSocket.readyState !== WebSocket.OPEN) { - log('本地唤醒事件桥未连接,无法发送消息', 'warning'); + log('Local wake event bridge not connected, cannot send message', 'warning'); return false; } @@ -156,7 +156,7 @@ export function requestWakewordBridge(type, payload = {}, timeout = 5000) { return new Promise((resolve, reject) => { const timer = window.setTimeout(() => { pendingWakewordRequests.delete(requestId); - reject(new Error('本地唤醒服务响应超时')); + reject(new Error('Local wake service response timed out')); }, timeout); pendingWakewordRequests.set(requestId, { resolve, reject, timer }); @@ -164,7 +164,7 @@ export function requestWakewordBridge(type, payload = {}, timeout = 5000) { if (!sendWakewordBridgeMessage(type, payload, requestId)) { window.clearTimeout(timer); pendingWakewordRequests.delete(requestId); - reject(new Error('本地唤醒事件桥未连接')); + reject(new Error('Local wake event bridge not connected')); } }); } @@ -209,7 +209,7 @@ function settleWakewordRequest(message) { pendingWakewordRequests.delete(message.requestId); if (message.success === false) { - pendingRequest.reject(new Error(message.error || '本地唤醒服务返回失败')); + pendingRequest.reject(new Error(message.error || 'Local wake service returned failure')); return; } diff --git a/main/digital-human/js/core/network/websocket.js b/main/digital-human/js/core/network/websocket.js index ee7238c1d..f0f9100bb 100644 --- a/main/digital-human/js/core/network/websocket.js +++ b/main/digital-human/js/core/network/websocket.js @@ -1,4 +1,4 @@ -// WebSocket消息处理模块 +// WebSocket message handling module import { getConfig, saveConnectionUrls } from '../../config/manager.js?v=0205'; import { uiController } from '../../ui/controller.js?v=0205'; import { log } from '../../utils/logger.js?v=0205'; @@ -7,7 +7,7 @@ import { getAudioRecorder } from '../audio/recorder.js?v=0205'; import { executeMcpTool, getMcpTools, setWebSocket as setMcpWebSocket } from '../mcp/tools.js?v=0205'; import { webSocketConnect } from './ota-connector.js?v=0205'; -// WebSocket处理器类 +// WebSocket handler class export class WebSocketHandler { constructor() { this.websocket = null; @@ -15,12 +15,12 @@ export class WebSocketHandler { this.onRecordButtonStateChange = null; this.onSessionStateChange = null; this.onSessionEmotionChange = null; - this.onChatMessage = null; // 新增:聊天消息回调 + this.onChatMessage = null; // Added: chat message callback this.currentSessionId = null; this.isRemoteSpeaking = false; } - // 发送hello握手消息 + // Send hello handshake message async sendHelloMessage() { if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) return false; @@ -39,13 +39,13 @@ export class WebSocketHandler { } }; - log('发送hello握手消息', 'info'); + log('Send hello handshake message', 'info'); this.websocket.send(JSON.stringify(helloMessage)); return new Promise(resolve => { const timeout = setTimeout(() => { - log('等待hello响应超时', 'error'); - log('提示: 请尝试点击"测试认证"按钮进行连接排查', 'info'); + log('Timeout waiting for hello response', 'error'); + log('Hint: try clicking the "Test authentication" button to troubleshoot the connection', 'info'); resolve(false); }, 5000); @@ -53,20 +53,20 @@ export class WebSocketHandler { try { const response = JSON.parse(event.data); if (response.type === 'hello' && response.session_id) { - log(`服务器握手成功,会话ID: ${response.session_id}`, 'success'); + log(`Server handshake successful, session ID: ${response.session_id}`, 'success'); clearTimeout(timeout); this.websocket.removeEventListener('message', onMessageHandler); resolve(true); } } catch (e) { - // 忽略非JSON消息 + // Ignore non-JSON messages } }; this.websocket.addEventListener('message', onMessageHandler); }); } catch (error) { - log(`发送hello消息错误: ${error.message}`, 'error'); + log(`Error sending hello message: ${error.message}`, 'error'); return false; } } @@ -79,26 +79,26 @@ export class WebSocketHandler { session_id: sessionId, type: 'listen', state: 'detect', - text: '嘿,你好呀' + text: 'Hey, hello' })); - log('发送listen detect消息,唤醒词: 嘿,你好呀', 'info'); + log('Sending listen detect message, wake word: Hey, Hello', 'info'); - // listen start:开始监听 + // listen start: Begin listening this.websocket.send(JSON.stringify({ session_id: sessionId, type: 'listen', state: 'start', mode: 'auto' })); - log('发送listen start消息', 'info'); + log('Sending listen start message', 'info'); } - // 处理文本消息 + // Process text message handleTextMessage(message) { if (message.type === 'hello') { - log(`服务器回应:${JSON.stringify(message, null, 2)}`, 'success'); + log(`Server response: ${JSON.stringify(message, null, 2)}`, 'success'); window.cameraAvailable = true; - log('连接成功,摄像头已可用', 'success'); + log('Connection successful, camera available', 'success'); uiController.updateDialButton(true); this._sendWakeupMessages(message.session_id); @@ -107,54 +107,54 @@ export class WebSocketHandler { } else if (message.type === 'tts') { this.handleTTSMessage(message); } else if (message.type === 'audio') { - log(`收到音频控制消息: ${JSON.stringify(message)}`, 'info'); + log(`Received audio control message: ${JSON.stringify(message)}`, 'info'); } else if (message.type === 'stt') { - log(`识别结果: ${message.text}`, 'info'); - // 检查是否需要绑定设备 - if (message.text && (message.text.includes('绑定') || message.text.includes('bind'))) { - log('收到设备绑定提示,更新摄像头状态', 'warning'); + log(`Recognition result: ${message.text}`, 'info'); + // Check if device binding is required + if (message.text && (message.text.includes('bind') || message.text.includes('bind'))) { + log('Received device binding prompt, updating camera status', 'warning'); window.cameraAvailable = false; - // 关闭摄像头 + // Close camera if (typeof window.stopCamera === 'function') { window.stopCamera(); } - // 更新摄像头按钮状态 + // Update camera button state const cameraBtn = document.getElementById('cameraBtn'); if (cameraBtn) { cameraBtn.classList.remove('camera-active'); - cameraBtn.querySelector('.btn-text').textContent = '摄像头'; + cameraBtn.querySelector('.btn-text').textContent = 'Camera'; cameraBtn.disabled = true; - cameraBtn.title = '请先绑定验证码'; + cameraBtn.title = 'Bind verification code first'; } } - // 使用新的聊天消息回调显示STT消息 + // Use new chat message callback to display STT messages if (this.onChatMessage && message.text) { this.onChatMessage(message.text, true); } } else if (message.type === 'llm') { - log(`大模型回复: ${message.text}`, 'info'); - // 使用新的聊天消息回调显示LLM回复 + log(`LLM response: ${message.text}`, 'info'); + // Use new chat message callback to display LLM replies if (this.onChatMessage && message.text) { this.onChatMessage(message.text, false); } - // 如果包含表情,更新sessionStatus表情并触发Live2D动作 + // If emojis are included, update sessionStatus emoji and trigger Live2D action if (message.text && /[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/u.test(message.text)) { - // 提取表情符号 + // Extract emojis const emojiMatch = message.text.match(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/u); if (emojiMatch && this.onSessionEmotionChange) { this.onSessionEmotionChange(emojiMatch[0]); } - // 触发Live2D情绪动作 + // Trigger Live2D emotion action if (message.emotion) { - console.log(`收到情绪消息: emotion=${message.emotion}, text=${message.text}`); + console.log(`Received emotion message: emotion=${message.emotion}, text=${message.text}`); this.triggerLive2DEmotionAction(message.emotion); } } - // 只有当文本不仅仅是表情时,才添加到对话中 - // 移除文本中的表情后检查是否还有内容 + // Add to conversation only if text is not just an emoji + // Remove emojis from text and check if content remains const textWithoutEmoji = message.text ? message.text.replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu, '').trim() : ''; if (textWithoutEmoji && this.onChatMessage) { this.onChatMessage(message.text, false); @@ -162,46 +162,46 @@ export class WebSocketHandler { } else if (message.type === 'mcp') { this.handleMCPMessage(message); } else { - log(`未知消息类型: ${message.type}`, 'info'); + log(`Unknown message type: ${message.type}`, 'info'); if (this.onChatMessage) { - this.onChatMessage(`未知消息类型: ${message.type}\n${JSON.stringify(message, null, 2)}`, false); + this.onChatMessage(`Unknown message type: ${message.type} \n ${JSON.stringify(message, null, 2)}`, false); } } } - // 处理TTS消息 + // Process TTS message handleTTSMessage(message) { if (message.state === 'start') { - log('服务器开始发送语音', 'info'); + log('Server started sending audio', 'info'); this.currentSessionId = message.session_id; this.isRemoteSpeaking = true; if (this.onSessionStateChange) { this.onSessionStateChange(true); } - // 启动Live2D说话动画 + // Start Live2D speaking animation this.startLive2DTalking(); } else if (message.state === 'sentence_start') { - log(`服务器发送语音段: ${message.text}`, 'info'); + log(`Server sent voice segment: ${message.text}`, 'info'); this.ttsSentenceCount = (this.ttsSentenceCount || 0) + 1; if (message.text && this.onChatMessage) { this.onChatMessage(message.text, false); } - // 确保动画在句子开始时运行 + // Ensure animation starts at the beginning of the sentence const live2dManager = window.chatApp?.live2dManager; if (live2dManager && !live2dManager.isTalking) { this.startLive2DTalking(); } } else if (message.state === 'sentence_end') { - log(`语音段结束: ${message.text}`, 'info'); + log(`Voice segment ended: ${message.text}`, 'info'); - // 句子结束时不清除动画,等待下一个句子或最终停止 + // Do not clear animation at sentence end, wait for the next sentence or final stop } else if (message.state === 'stop') { - log('服务器语音传输结束,清空所有音频缓冲', 'info'); + log('Server voice transmission ended, clearing all audio buffers', 'info'); - // 清空所有音频缓冲并停止播放 + // Clear all audio buffers and stop playback const audioPlayer = getAudioPlayer(); audioPlayer.clearAllAudio(); @@ -213,63 +213,63 @@ export class WebSocketHandler { this.onSessionStateChange(false); } - // 延迟停止Live2D说话动画,确保所有句子都播放完毕 + // Delay stopping Live2D speaking animation to ensure all sentences finish playing setTimeout(() => { this.stopLive2DTalking(); - this.ttsSentenceCount = 0; // 重置计数器 - }, 1000); // 1秒延迟,确保所有句子都完成 + this.ttsSentenceCount = 0; // Reset counter + }, 1000); // 1-second delay to ensure all sentences are completed } } - // 启动Live2D说话动画 + // Start Live2D speaking animation startLive2DTalking() { try { - // 获取Live2D管理器实例 + // Get Live2D manager instance const live2dManager = window.chatApp?.live2dManager; if (live2dManager && live2dManager.live2dModel) { - // 使用音频播放器的分析器节点 + // Use the analyzer node of the audio player live2dManager.startTalking(); - log('Live2D说话动画已启动', 'info'); + log('Live2D speaking animation started', 'info'); } } catch (error) { - log(`启动Live2D说话动画失败: ${error.message}`, 'error'); + log(`Failed to start Live2D speaking animation: ${error.message}`, 'error'); } } - // 停止Live2D说话动画 + // Stop Live2D speaking animation stopLive2DTalking() { try { const live2dManager = window.chatApp?.live2dManager; if (live2dManager) { live2dManager.stopTalking(); - log('Live2D说话动画已停止', 'info'); + log('Live2D speaking animation stopped', 'info'); } } catch (error) { - log(`停止Live2D说话动画失败: ${error.message}`, 'error'); + log(`Failed to stop Live2D speaking animation: ${error.message}`, 'error'); } } - // 初始化Live2D音频分析器 + // Initialize Live2D audio analyzer initializeLive2DAudioAnalyzer() { try { const live2dManager = window.chatApp?.live2dManager; if (live2dManager) { - // 初始化音频分析器(使用音频播放器的上下文) + // Initialize audio analyzer (using audio player context) if (live2dManager.initializeAudioAnalyzer()) { - log('Live2D音频分析器初始化完成,已连接到音频播放器', 'success'); + log('Live2D audio analyzer initialized, connected to audio player', 'success'); } else { - log('Live2D音频分析器初始化失败,将使用模拟动画', 'warning'); + log('Live2D audio analyzer initialization failed, using simulated animation', 'warning'); } } } catch (error) { - log(`初始化Live2D音频分析器失败: ${error.message}`, 'error'); + log(`Failed to initialize Live2D audio analyzer: ${error.message}`, 'error'); } } - // 处理MCP消息 + // Process MCP message handleMCPMessage(message) { const payload = message.payload || {}; - log(`服务器下发: ${JSON.stringify(message)}`, 'info'); + log(`Server sent: ${JSON.stringify(message)}`, 'info'); if (payload.method === 'tools/list') { const tools = getMcpTools(); @@ -285,15 +285,15 @@ export class WebSocketHandler { } } }); - log(`客户端上报: ${replyMessage}`, 'info'); + log(`Client report: ${replyMessage}`, 'info'); this.websocket.send(replyMessage); - log(`回复MCP工具列表: ${tools.length} 个工具`, 'info'); + log(`Replying with MCP tool list: ${tools.length} tools`, 'info'); } else if (payload.method === 'tools/call') { const toolName = payload.params?.name; const toolArgs = payload.params?.arguments; - log(`调用工具: ${toolName} 参数: ${JSON.stringify(toolArgs)}`, 'info'); + log(`Calling tool: ${toolName} Args: ${JSON.stringify(toolArgs)}`, 'info'); executeMcpTool(toolName, toolArgs).then(result => { const replyMessage = JSON.stringify({ @@ -314,10 +314,10 @@ export class WebSocketHandler { } }); - log(`客户端上报: ${replyMessage}`, 'info'); + log(`Client report: ${replyMessage}`, 'info'); this.websocket.send(replyMessage); }).catch(error => { - log(`工具执行失败: ${error.message}`, 'error'); + log(`Tool execution failed: ${error.message}`, 'error'); const errorReply = JSON.stringify({ "session_id": message.session_id || "", "type": "mcp", @@ -333,8 +333,8 @@ export class WebSocketHandler { this.websocket.send(errorReply); }); } else if (payload.method === 'initialize') { - log(`收到工具初始化请求: ${JSON.stringify(payload.params)}`, 'info'); - // 保存视觉分析接口地址 + log(`Received tool initialization request: ${JSON.stringify(payload.params)}`, 'info'); + // Save visual analysis API address const visionUrl = document.getElementById('visionUrl'); const visionConfig = payload?.params?.capabilities?.vision; if (visionConfig && typeof visionConfig === 'object' && visionConfig.url && visionConfig.token) { @@ -364,14 +364,14 @@ export class WebSocketHandler { } } }); - log(`回复初始化响应`, 'info'); + log(`Reply initialization response`, 'info'); this.websocket.send(replyMessage); } else { - log(`未知的MCP方法: ${payload.method}`, 'warning'); + log(`Unknown MCP method: ${payload.method}`, 'warning'); } } - // 处理二进制消息 + // Process binary message async handleBinaryMessage(data) { try { let arrayBuffer; @@ -379,9 +379,9 @@ export class WebSocketHandler { arrayBuffer = data; } else if (data instanceof Blob) { arrayBuffer = await data.arrayBuffer(); - log(`收到Blob音频数据,大小: ${arrayBuffer.byteLength}字节`, 'debug'); + log(`Received Blob audio data, size: ${arrayBuffer.byteLength} bytes`, 'debug'); } else { - log(`收到未知类型的二进制数据: ${typeof data}`, 'warning'); + log(`Received unknown binary data type: ${typeof data}`, 'warning'); return; } @@ -389,14 +389,14 @@ export class WebSocketHandler { const audioPlayer = getAudioPlayer(); audioPlayer.enqueueAudioData(opusData); } catch (error) { - log(`处理二进制消息出错: ${error.message}`, 'error'); + log(`Error processing binary message: ${error.message}`, 'error'); } } - // 连接WebSocket服务器 + // Connect to WebSocket server async connect() { const config = getConfig(); - log('正在检查OTA状态...', 'info'); + log('Checking OTA status...', 'info'); saveConnectionUrls(); try { @@ -407,13 +407,13 @@ export class WebSocketHandler { } this.websocket = ws; - // 设置接收二进制数据的类型为ArrayBuffer + // Set binary data reception type to ArrayBuffer this.websocket.binaryType = 'arraybuffer'; - // 设置 MCP 模块的 WebSocket 实例 + // Set the WebSocket instance for the MCP module setMcpWebSocket(this.websocket); - // 设置录音器的WebSocket + // Set WebSocket for recorder const audioRecorder = getAudioRecorder(); audioRecorder.setWebSocket(this.websocket); @@ -421,7 +421,7 @@ export class WebSocketHandler { return true; } catch (error) { - log(`连接错误: ${error.message}`, 'error'); + log(`Connection error: ${error.message}`, 'error'); if (this.onConnectionStateChange) { this.onConnectionStateChange(false); } @@ -429,30 +429,30 @@ export class WebSocketHandler { } } - // 设置事件处理器 + // Set event handler setupEventHandlers() { this.websocket.onopen = async () => { const url = document.getElementById('serverUrl').value; - log(`已连接到服务器: ${url}`, 'success'); + log(`Connected to server: ${url}`, 'success'); if (this.onConnectionStateChange) { this.onConnectionStateChange(true); } - // 连接成功后,默认状态为聆听中 + // After successful connection, default state is listening this.isRemoteSpeaking = false; if (this.onSessionStateChange) { this.onSessionStateChange(false); } - // 在WebSocket连接成功时初始化Live2D音频分析器 + // Initialize the Live2D audio analyzer upon successful WebSocket connection this.initializeLive2DAudioAnalyzer(); await this.sendHelloMessage(); }; this.websocket.onclose = () => { - log('已断开连接', 'info'); + log('Disconnected', 'info'); if (this.onConnectionStateChange) { this.onConnectionStateChange(false); @@ -461,12 +461,12 @@ export class WebSocketHandler { const audioRecorder = getAudioRecorder(); audioRecorder.stop(); - // 关闭摄像头 + // Close camera if (typeof window.stopCamera === 'function') { window.stopCamera(); } - // 隐藏摄像头显示区域 + // Hide camera display area const cameraContainer = document.getElementById('cameraContainer'); if (cameraContainer) { cameraContainer.classList.remove('active'); @@ -474,8 +474,8 @@ export class WebSocketHandler { }; this.websocket.onerror = (error) => { - log(`WebSocket错误: ${error.message || '未知错误'}`, 'error'); - uiController.addChatMessage(`⚠️ WebSocket错误: ${error.message || '未知错误'}`, false); + log(`WebSocket error: ${error.message || 'Unknown error'}`, 'error'); + uiController.addChatMessage(`⚠️ WebSocket error: ${error.message || 'Unknown error'}`, false); if (this.onConnectionStateChange) { this.onConnectionStateChange(false); } @@ -490,14 +490,14 @@ export class WebSocketHandler { this.handleBinaryMessage(event.data); } } catch (error) { - log(`WebSocket消息处理错误: ${error.message}`, 'error'); - // 不再使用旧的addMessage函数,因为conversationDiv元素不存在 - // 错误消息将通过其他方式显示 + log(`WebSocket message processing error: ${error.message}`, 'error'); + // No longer using the old addMessage function because the conversationDiv element does not exist + // Error messages will be displayed via other means } }; } - // 断开连接 + // Disconnect disconnect() { if (!this.websocket) return; @@ -505,26 +505,26 @@ export class WebSocketHandler { const audioRecorder = getAudioRecorder(); audioRecorder.stop(); - // 关闭摄像头 + // Close camera if (typeof window.stopCamera === 'function') { window.stopCamera(); } - // 隐藏摄像头显示区域 + // Hide camera display area const cameraContainer = document.getElementById('cameraContainer'); if (cameraContainer) { cameraContainer.classList.remove('active'); } } - // 发送文本消息 + // Send text message sendTextMessage(text) { if (text === '' || !this.websocket || this.websocket.readyState !== WebSocket.OPEN) { return false; } try { - // 如果对方正在说话,先发送打断消息 + // If the other party is speaking, send an interrupt message first if (this.isRemoteSpeaking && this.currentSessionId) { const abortMessage = { session_id: this.currentSessionId, @@ -532,7 +532,7 @@ export class WebSocketHandler { reason: 'wake_word_detected' }; this.websocket.send(JSON.stringify(abortMessage)); - log('发送打断消息', 'info'); + log('Sending interrupt message', 'info'); } const listenMessage = { @@ -542,45 +542,45 @@ export class WebSocketHandler { }; this.websocket.send(JSON.stringify(listenMessage)); - log(`发送文本消息: ${text}`, 'info'); + log(`Sending text message: ${text}`, 'info'); return true; } catch (error) { - log(`发送消息错误: ${error.message}`, 'error'); + log(`Error sending message: ${error.message}`, 'error'); return false; } } /** - * 触发Live2D情绪动作 - * @param {string} emotion - 情绪名称 + * Trigger Live2D emotion action + * @param {string} emotion - Emotion name */ triggerLive2DEmotionAction(emotion) { try { const live2dManager = window.chatApp?.live2dManager; if (live2dManager && typeof live2dManager.triggerEmotionAction === 'function') { live2dManager.triggerEmotionAction(emotion); - log(`触发Live2D情绪动作: ${emotion}`, 'info'); + log(`Trigger Live2D emotion action: ${emotion}`, 'info'); } else { - log(`无法触发Live2D情绪动作: Live2D管理器未找到或方法不可用`, 'warning'); + log(`Cannot trigger Live2D emotion action: Live2D manager not found or method unavailable`, 'warning'); } } catch (error) { - log(`触发Live2D情绪动作失败: ${error.message}`, 'error'); + log(`Failed to trigger Live2D emotion action: ${error.message}`, 'error'); } } - // 获取WebSocket实例 + // Get WebSocket instance getWebSocket() { return this.websocket; } - // 检查是否已连接 + // Check connection status isConnected() { return this.websocket && this.websocket.readyState === WebSocket.OPEN; } } -// 创建单例 +// Create Singleton let wsHandlerInstance = null; export function getWebSocketHandler() { diff --git a/main/digital-human/js/ui/controller.js b/main/digital-human/js/ui/controller.js index b71ababc0..508377a83 100644 --- a/main/digital-human/js/ui/controller.js +++ b/main/digital-human/js/ui/controller.js @@ -165,36 +165,36 @@ class UIController { cameraTimer = setTimeout(() => { const cameraContainer = document.getElementById('cameraContainer'); if (!cameraContainer) { - log('摄像头容器不存在', 'warning'); + log('Camera container does not exist', 'warning'); return; } const isActive = cameraContainer.classList.contains('active'); if (isActive) { - // 关闭摄像头 + // Close camera if (typeof window.stopCamera === 'function') { if (cameraSwitch) cameraSwitch.classList.remove('active'); window.stopCamera(); } cameraContainer.classList.remove('active'); cameraBtn.classList.remove('camera-active'); - cameraBtn.querySelector('.btn-text').textContent = '摄像头'; - log('摄像头已关闭', 'info'); + cameraBtn.querySelector('.btn-text').textContent = 'Camera'; + log('Camera closed', 'info'); } else { - // 打开摄像头 + // Open camera if (typeof window.startCamera === 'function') { window.startCamera().then(success => { if (success) { cameraBtn.classList.add('camera-active'); - cameraBtn.querySelector('.btn-text').textContent = '关闭'; + cameraBtn.querySelector('.btn-text').textContent = 'Close'; } else { - this.addChatMessage('⚠️ 摄像头启动失败,请检查浏览器权限', false); + this.addChatMessage('⚠️ Camera startup failed, check browser permissions', false); } }).catch(error => { - log(`启动摄像头异常: ${error.message}`, 'error'); + log(`Camera startup exception: ${error.message}`, 'error'); }); } else { - log('startCamera函数未定义', 'warning'); + log('startCamera function undefined', 'warning'); } } }, 300); @@ -216,11 +216,11 @@ class UIController { audioRecorder.stop(); // Restore record button to normal state recordBtn.classList.remove('recording'); - recordBtn.querySelector('.btn-text').textContent = '录音'; + recordBtn.querySelector('.btn-text').textContent = 'Record'; } else { // Update button state to recording recordBtn.classList.add('recording'); - recordBtn.querySelector('.btn-text').textContent = '录音中'; + recordBtn.querySelector('.btn-text').textContent = 'Recording'; // Start recording, update button state after delay setTimeout(() => { @@ -274,15 +274,15 @@ class UIController { applyWakewordBtn.addEventListener('click', this.handleApplyWakeword); } - // 点击模态框背景关闭(仅对特定模态框禁用此功能) + // Close modal by clicking background (disabled for specific modals) const modals = document.querySelectorAll('.modal'); modals.forEach(modal => { modal.addEventListener('click', (e) => { if (e.target === modal) { - // settingsModal、mcpToolModal、mcpPropertyModal 只能通过点击X关闭 + // settingsModal, mcpToolModal, and mcpPropertyModal can only be closed by clicking X const nonClosableModals = ['settingsModal', 'mcpToolModal', 'mcpPropertyModal']; if (nonClosableModals.includes(modal.id)) { - return; // 禁止点击背景关闭 + return; // Prevent closing by clicking background } this.hideModal(modal.id); } @@ -308,12 +308,12 @@ class UIController { if (connectionStatus) { if (isConnected) { - connectionStatus.textContent = '已连接'; + connectionStatus.textContent = 'Connected'; if (statusDot) { statusDot.className = 'status-dot status-connected'; } } else { - connectionStatus.textContent = '离线'; + connectionStatus.textContent = 'Offline'; if (statusDot) { statusDot.className = 'status-dot status-disconnected'; } @@ -330,14 +330,14 @@ class UIController { if (dialBtn) { if (isConnected) { dialBtn.classList.add('dial-active'); - dialBtn.querySelector('.btn-text').textContent = '挂断'; + dialBtn.querySelector('.btn-text').textContent = 'Hang up'; // Update dial button icon to hang up icon dialBtn.querySelector('svg').innerHTML = ` `; } else { dialBtn.classList.remove('dial-active'); - dialBtn.querySelector('.btn-text').textContent = '拨号'; + dialBtn.querySelector('.btn-text').textContent = 'Dial'; // Restore dial button icon dialBtn.querySelector('svg').innerHTML = ` @@ -352,10 +352,10 @@ class UIController { cameraContainer.classList.remove('active'); } cameraBtn.classList.remove('camera-active'); - cameraBtn.querySelector('.btn-text').textContent = '摄像头'; + cameraBtn.querySelector('.btn-text').textContent = 'Camera'; cameraBtn.disabled = true; - cameraBtn.title = '请先连接服务器'; - // 关闭摄像头 + cameraBtn.title = 'Connect to server first'; + // Close camera if (typeof window.stopCamera === 'function') { window.stopCamera(); } @@ -365,10 +365,10 @@ class UIController { if (cameraBtn && isConnected) { if (window.cameraAvailable) { cameraBtn.disabled = false; - cameraBtn.title = '打开/关闭摄像头'; + cameraBtn.title = 'Toggle camera'; } else { cameraBtn.disabled = true; - cameraBtn.title = '请先绑定验证码'; + cameraBtn.title = 'Bind verification code first'; } } @@ -377,19 +377,19 @@ class UIController { const microphoneAvailable = window.microphoneAvailable !== false; if (isConnected && microphoneAvailable) { recordBtn.disabled = false; - recordBtn.title = '开始录音'; + recordBtn.title = 'Start Recording'; // Restore record button to normal state - recordBtn.querySelector('.btn-text').textContent = '录音'; + recordBtn.querySelector('.btn-text').textContent = 'Record'; recordBtn.classList.remove('recording'); } else { recordBtn.disabled = true; if (!microphoneAvailable) { - recordBtn.title = window.isHttpNonLocalhost ? '当前由于是http访问,无法录音,只能用文字交互' : '麦克风不可用'; + recordBtn.title = window.isHttpNonLocalhost ? 'Recording unavailable due to HTTP access; text interaction only' : 'Microphone unavailable'; } else { - recordBtn.title = '请先连接服务器'; + recordBtn.title = 'Please connect to server first'; } // Restore record button to normal state - recordBtn.querySelector('.btn-text').textContent = '录音'; + recordBtn.querySelector('.btn-text').textContent = 'Record'; recordBtn.classList.remove('recording'); } } @@ -400,10 +400,10 @@ class UIController { const recordBtn = document.getElementById('recordBtn'); if (recordBtn) { if (isRecording) { - recordBtn.querySelector('.btn-text').textContent = `录音中`; + recordBtn.querySelector('.btn-text').textContent = `Recording`; recordBtn.classList.add('recording'); } else { - recordBtn.querySelector('.btn-text').textContent = '录音'; + recordBtn.querySelector('.btn-text').textContent = 'Record'; recordBtn.classList.remove('recording'); } // Only enable button when microphone is available @@ -423,15 +423,15 @@ class UIController { // Disable record button recordBtn.disabled = true; // Update button text and title - recordBtn.querySelector('.btn-text').textContent = '录音'; - recordBtn.title = isHttpNonLocalhost ? '当前由于是http访问,无法录音,只能用文字交互' : '麦克风不可用'; + recordBtn.querySelector('.btn-text').textContent = 'Record'; + recordBtn.title = isHttpNonLocalhost ? 'Recording unavailable over HTTP; use text input only' : 'Microphone unavailable'; } else { // If connected, enable record button const wsHandler = getWebSocketHandler(); if (wsHandler && wsHandler.isConnected()) { recordBtn.disabled = false; - recordBtn.title = '开始录音'; + recordBtn.title = 'Start Recording'; } } } @@ -464,7 +464,7 @@ class UIController { switchLive2DModel() { const modelSelect = document.getElementById('live2dModelSelect'); if (!modelSelect) { - console.error('模型选择下拉框不存在'); + console.error('Model selection dropdown not found'); return; } @@ -475,17 +475,17 @@ class UIController { app.live2dManager.switchModel(selectedModel) .then(success => { if (success) { - this.addChatMessage(`已切换到模型: ${selectedModel}`, false); + this.addChatMessage(`Switched to model: ${selectedModel}`, false); } else { - this.addChatMessage('模型切换失败', false); + this.addChatMessage('Model switch failed', false); } }) .catch(error => { - console.error('模型切换错误:', error); - this.addChatMessage('模型切换出错', false); + console.error('Model switch error:', error); + this.addChatMessage('Model switch error', false); }); } else { - this.addChatMessage('Live2D管理器未初始化', false); + this.addChatMessage('Live2D manager not initialized', false); } } @@ -561,47 +561,47 @@ class UIController { }; if (payload.enabled && payload.wakeWords.length === 0) { - this.addChatMessage('启用唤醒词时,至少需要填写一个唤醒词。', false); + this.addChatMessage('At least one wake word is required when enabling wake word detection.', false); return; } const applyWakewordBtn = document.getElementById('applyWakewordBtn'); if (applyWakewordBtn) { applyWakewordBtn.disabled = true; - applyWakewordBtn.textContent = '应用中...'; + applyWakewordBtn.textContent = 'Applying...'; } try { - // 保存地址到 localStorage + // Save address to localStorage if (wakewordWsUrlInput && wakewordWsUrlInput.value.trim()) { localStorage.setItem('xz_tester_wakewordWsUrl', wakewordWsUrlInput.value.trim()); } - // 比较新地址和当前连接地址 + // Compare new address with current connection address const newWsUrl = localStorage.getItem('xz_tester_wakewordWsUrl'); const currentWsUrl = getWakewordBridgeUrl(); const urlChanged = newWsUrl !== currentWsUrl; if (urlChanged) { - // 地址变了,先确认 - const shouldRestart = window.confirm('地址已变更,是否继续?(将断开旧连接并重新连接)'); + // Address changed, please confirm + const shouldRestart = window.confirm('Address changed. Continue? (This will disconnect the old connection and reconnect)'); if (!shouldRestart) { - // 恢复 localStorage 里的旧地址 + // Restore old address from localStorage localStorage.setItem('xz_tester_wakewordWsUrl', currentWsUrl); - this.addChatMessage('已取消地址变更。', false); + this.addChatMessage('Address change cancelled.', false); return; } - // 断开旧连接 + // Disconnect old connection stopWakewordBridgeListener(); - // 启动新连接(自动用新地址) + // Start new connection (automatically use new address) startWakewordBridgeListener(); - // 等 bridge_connected + // Wait for bridge_connected await new Promise((resolve, reject) => { const timeout = setTimeout(() => { - reject(new Error('连接新服务器超时')); + reject(new Error('Connection to new server timed out')); }, 5000); onNextBridgeConnected(() => { @@ -610,44 +610,44 @@ class UIController { }); }); - // 发配置和重启 + // Send config and restart await requestWakewordBridge('set_wakeword_config', payload); this.applyWakewordConfig(payload); await requestWakewordBridge('restart_wakeword_service'); - this.addChatMessage('唤醒词配置已保存,唤醒词服务正在重启。', false); + this.addChatMessage('Wake word config saved, restarting wake word service.', false); } else { - // 地址没变:直接在当前连接操作 + // Address unchanged: operate on current connection const response = await requestWakewordBridge('set_wakeword_config', payload); this.applyWakewordConfig(response.payload || payload); - const shouldRestart = window.confirm('唤醒词已保存。是否现在重启唤醒词服务以立即生效?'); + const shouldRestart = window.confirm('Wake word saved. Restart the wake word service now to apply changes?'); if (!shouldRestart) { - this.addChatMessage('唤醒词配置已保存,可稍后手动重启服务后生效。', false); + this.addChatMessage('Wake word config saved. Restart the service manually later for changes to take effect.', false); return; } await requestWakewordBridge('restart_wakeword_service'); - this.addChatMessage('唤醒词配置已保存,唤醒词服务正在重启。', false); + this.addChatMessage('Wake word config saved, restarting wake word service.', false); } } catch (error) { - this.addChatMessage(`应用唤醒词失败: ${error.message}`, false); + this.addChatMessage(`Failed to apply wake word: ${error.message}`, false); } finally { if (applyWakewordBtn) { applyWakewordBtn.disabled = false; - applyWakewordBtn.textContent = '应用唤醒词'; + applyWakewordBtn.textContent = 'Apply Wake Word'; } } } // Start AI chat session after connection startAIChatSession() { - this.addChatMessage('连接成功,开始聊天吧~😊', false); + this.addChatMessage('Connection successful, start chatting~😊', false); // Check microphone availability and show error messages if needed if (!window.microphoneAvailable) { if (window.isHttpNonLocalhost) { - this.addChatMessage('⚠️ 当前由于是http访问,无法录音,只能用文字交互', false); + this.addChatMessage('⚠️ Recording is unavailable over HTTP; text interaction only', false); } else { - this.addChatMessage('⚠️ 麦克风不可用,请检查权限设置,只能用文字交互', false); + this.addChatMessage('⚠️ Microphone unavailable. Check permissions. Text-only interaction enabled.', false); } } // Start recording only if microphone is available @@ -664,13 +664,13 @@ class UIController { const cameraBtn = document.getElementById('cameraBtn'); if (cameraBtn) { cameraBtn.classList.add('camera-active'); - cameraBtn.querySelector('.btn-text').textContent = '关闭'; + cameraBtn.querySelector('.btn-text').textContent = 'Close'; } } else { - this.addChatMessage('⚠️ 摄像头启动失败,可能被浏览器拒绝', false); + this.addChatMessage('⚠️ Camera startup failed, possibly denied by browser', false); } }).catch(error => { - log(`启动摄像头异常: ${error.message}`, 'error'); + log(`Camera startup exception: ${error.message}`, 'error'); }); } } @@ -679,7 +679,7 @@ class UIController { async handleConnect() { const wsHandler = getWebSocketHandler(); if (this.isConnecting || (wsHandler && wsHandler.isConnected())) { - log('连接已存在或正在进行,忽略本次拨号请求', 'info'); + log('Connection exists or is in progress, ignoring this dial request', 'info'); return; } @@ -698,7 +698,7 @@ class UIController { console.log('otaUrl element:', otaUrlInput); if (!otaUrlInput || !otaUrlInput.value) { - this.addChatMessage('请输入OTA服务器地址', false); + this.addChatMessage('Please enter the OTA server address', false); return; } @@ -709,12 +709,12 @@ class UIController { const dialBtn = document.getElementById('dialBtn'); if (dialBtn) { dialBtn.classList.add('dial-active'); - dialBtn.querySelector('.btn-text').textContent = '连接中...'; + dialBtn.querySelector('.btn-text').textContent = 'Connecting...'; dialBtn.disabled = true; } // Show connecting message - this.addChatMessage('正在连接服务器...', false); + this.addChatMessage('Connecting to server...', false); const chatIpt = document.getElementById('chatIpt'); if (chatIpt) { @@ -739,10 +739,10 @@ class UIController { if (recordBtn) { if (isRecording) { recordBtn.classList.add('recording'); - recordBtn.querySelector('.btn-text').textContent = '录音中'; + recordBtn.querySelector('.btn-text').textContent = 'Recording'; } else { recordBtn.classList.remove('recording'); - recordBtn.querySelector('.btn-text').textContent = '录音'; + recordBtn.querySelector('.btn-text').textContent = 'Record'; } } }; @@ -757,7 +757,7 @@ class UIController { if (!micAvailable) { const isHttp = window.isHttpNonLocalhost; if (isHttp) { - this.addChatMessage('⚠️ 当前由于是http访问,无法录音,只能用文字交互', false); + this.addChatMessage('⚠️ Recording is unavailable over HTTP; text interaction only', false); } // Update global state window.microphoneAvailable = false; @@ -769,13 +769,13 @@ class UIController { if (!this.dialBtnDisabled) { dialBtn.disabled = false; } - dialBtn.querySelector('.btn-text').textContent = '挂断'; + dialBtn.querySelector('.btn-text').textContent = 'Hang up'; dialBtn.classList.add('dial-active'); } this.hideModal('settingsModal'); } else { - throw new Error('OTA连接失败'); + throw new Error('OTA connection failed'); } } catch (error) { console.error('Connection error details:', { @@ -786,8 +786,8 @@ class UIController { // Show error message const errorMessage = error.message.includes('Cannot set properties of null') - ? '连接失败:请检查设备连接' - : `连接失败: ${error.message}`; + ? 'Connection failed: check device connection' + : `Connection failed: ${error.message}`; this.addChatMessage(errorMessage, false); @@ -797,7 +797,7 @@ class UIController { if (!this.dialBtnDisabled) { dialBtn.disabled = false; } - dialBtn.querySelector('.btn-text').textContent = '拨号'; + dialBtn.querySelector('.btn-text').textContent = 'Dial'; dialBtn.classList.remove('dial-active'); console.log('Dial button state restored successfully'); } @@ -806,27 +806,27 @@ class UIController { } } - async triggerWakewordDial(wakeWord = '唤醒词') { + async triggerWakewordDial(wakeWord = 'wake word') { const wsHandler = getWebSocketHandler(); const now = Date.now(); if (wsHandler && wsHandler.isConnected()) { - log('页面已连接,忽略自动拨号', 'info'); + log('Page already connected, ignoring auto-dial', 'info'); return false; } if (this.isConnecting || this.dialBtnDisabled) { - log('页面正在连接中,忽略重复唤醒', 'info'); + log('Page is connecting, ignoring duplicate wake', 'info'); return false; } if (now - this.lastWakewordDialTime < 3000) { - log('唤醒触发过于频繁,忽略本次自动拨号', 'warning'); + log('Wake trigger too frequent, ignoring this auto-dial', 'warning'); return false; } this.lastWakewordDialTime = now; - this.addChatMessage(`检测到唤醒词“${wakeWord}”,准备连接服务器...`, false); + this.addChatMessage(`Wake word "${wakeWord}" detected, connecting to server...`, false); await this.handleConnect(); return true; } @@ -841,9 +841,9 @@ class UIController { toolDiv.className = 'properties-container'; toolDiv.innerHTML = `
- - - + + +
`; diff --git a/main/digital-human/start.py b/main/digital-human/start.py index 251bfc8f8..6f7e1f9af 100644 --- a/main/digital-human/start.py +++ b/main/digital-human/start.py @@ -39,7 +39,7 @@ def main() -> int: app.setup() app.start() except Exception as e: - print(f"警告: 唤醒词服务启动失败({e}),测试页面仍可正常使用") + print(f"Warning: Wake word service failed to start ({e}), test page remains usable") http_server.serve_forever() except KeyboardInterrupt: print("test runtime stopped") diff --git a/main/digital-human/wakeword_runtime/config/config_loader.py b/main/digital-human/wakeword_runtime/config/config_loader.py index bfab853cd..07517ab04 100644 --- a/main/digital-human/wakeword_runtime/config/config_loader.py +++ b/main/digital-human/wakeword_runtime/config/config_loader.py @@ -121,17 +121,17 @@ def load_config(runtime_root: Path) -> RuntimeConfig: DEFAULT_WAKE_WORDS = [ - "你好小智", - "你好小志", - "小爱同学", - "你好小鑫", - "你好小新", - "小美同学", - "小龙小龙", - "喵喵同学", - "小滨小滨", - "小冰小冰", - "嘿你好呀", + "Hello Xiaozhi", + "Hello Xiaozhi", + "XiaoAi", + "Hello Xiaoxin", + "Hello Xiaoxin", + "Xiaomei", + "Xiaolong", + "MeowMeow", + "XiaoBin XiaoBin", + "XiaoBing XiaoBing", + "Hey there", ] diff --git a/main/digital-human/wakeword_runtime/runtime/http_server.py b/main/digital-human/wakeword_runtime/runtime/http_server.py index 19ce12330..69d5d7978 100644 --- a/main/digital-human/wakeword_runtime/runtime/http_server.py +++ b/main/digital-human/wakeword_runtime/runtime/http_server.py @@ -162,7 +162,7 @@ class TestRuntimeHttpServer: "wakeword_config", {}, success=False, - error=f"读取唤醒词配置失败: {exc}", + error=f"Failed to read wake word config: {exc}", ) def _handle_bridge_request(self, bridge: WakewordEventBridge, raw_message: str) -> str | None: @@ -191,7 +191,7 @@ class TestRuntimeHttpServer: {}, request_id=request_id, success=False, - error=f"保存唤醒词配置失败: {exc}", + error=f"Failed to save wake word config: {exc}", ) if message_type == "restart_wakeword_service": 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 664cb9b48..735e51f59 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. + * Constant + * Copyright (c) RenRen Open Source All rights reserved. * Website: https://www.renren.io */ public interface Constant { /** - * 成功 + * Success */ int SUCCESS = 1; /** - * 失败 + * Failed */ int FAIL = 0; /** @@ -21,177 +21,177 @@ public interface Constant { */ String OK = "OK"; /** - * 用户标识 + * User ID */ String USER_KEY = "userId"; /** - * 菜单根节点标识 + * Menu root node identifier */ Long MENU_ROOT = 0L; /** - * 部门根节点标识 + * Department root node ID */ Long DEPT_ROOT = 0L; /** - * 数据字典根节点标识 + * Root node identifier for data dictionary */ Long DICT_ROOT = 0L; /** - * 升序 + * Ascending */ String ASC = "asc"; /** - * 降序 + * Descending */ String DESC = "desc"; /** - * 创建时间字段名 + * Creation time field name */ String CREATE_DATE = "create_date"; /** - * 创建时间字段名 + * Creation time field name */ String ID = "id"; /** - * 数据权限过滤 + * Filter by data permissions */ String SQL_FILTER = "sqlFilter"; /** - * 当前页码 + * Current page */ String PAGE = "page"; /** - * 每页显示记录数 + * Records per page */ String LIMIT = "limit"; /** - * 排序字段 + * Sort field */ String ORDER_FIELD = "orderField"; /** - * 排序方式 + * Sort order */ String ORDER = "order"; /** - * 请求头授权标识 + * Request header authorization token */ String AUTHORIZATION = "Authorization"; /** - * 服务器密钥 + * Server key */ 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 address */ String SERVER_WEBSOCKET = "server.websocket"; /** - * mqtt gateway 配置 + * MQTT gateway config */ String SERVER_MQTT_GATEWAY = "server.mqtt_gateway"; /** - * ota地址 + * OTA URL */ String SERVER_OTA = "server.ota"; /** - * 是否允许用户注册 + * Allow user registration */ String SERVER_ALLOW_USER_REGISTER = "server.allow_user_register"; /** - * 下发六位验证码时显示的控制面板地址 + * Control panel address displayed when sending a 6-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接入点路径 + * MCP endpoint path */ String SERVER_VOICE_PRINT = "server.voice_print"; /** - * mqtt密钥 + * MQTT key */ String SERVER_MQTT_SECRET = "server.mqtt_signature_key"; /** - * WebSocket认证开关 + * WebSocket authentication toggle */ String SERVER_AUTH_ENABLED = "server.auth.enabled"; /** - * 系统功能菜单配置 + * System function menu config */ String SYSTEM_WEB_MENU = "system-web.menu"; /** - * 无记忆 + * No memory */ String MEMORY_NO_MEM = "Memory_nomem"; /** - * 仅上报聊天记录(不总结记忆) + * Report chat history only (no memory summarization) */ String MEMORY_MEM_REPORT_ONLY = "Memory_mem_report_only"; /** - * Mem0AI记忆 + * Mem0AI memory */ String MEMORY_MEM0AI = "Memory_mem0ai"; /** - * PowerMem记忆 + * PowerMem Memory */ String MEMORY_POWERMEM = "Memory_powermem"; /** - * 火山引擎双声道语音克隆 + * Volcano Engine dual-channel voice cloning */ String VOICE_CLONE_HUOSHAN_DOUBLE_STREAM = "huoshan_double_stream"; /** - * RAG配置类型 + * RAG config type */ String RAG_CONFIG_TYPE = "RAG"; enum SysBaseParam { /** - * ICP备案号 + * ICP license number */ BEIAN_ICP_NUM("server.beian_icp_num"), /** - * GA备案号 + * GA Filing Number */ BEIAN_GA_NUM("server.beian_ga_num"), /** - * 系统名称 + * System name */ SERVER_NAME("server.name"); @@ -207,23 +207,23 @@ public interface Constant { } /** - * 训练状态 + * Training status */ enum TrainStatus { /** - * 未训练 + * Not trained */ NOT_TRAINED(0), /** - * 训练中 + * Training */ TRAINING(1), /** - * 已训练 + * Trained */ TRAINED(2), /** - * 训练失败 + * Training failed */ TRAIN_FAILED(3); @@ -279,19 +279,19 @@ public interface Constant { } /** - * 数据状态 + * Data status */ enum DataOperation { /** - * 插入 + * Insert */ INSERT("I"), /** - * 已修改 + * Modified */ UPDATE("U"), /** - * 已删除 + * Deleted */ DELETE("D"); @@ -308,9 +308,9 @@ public interface Constant { @Getter enum ChatHistoryConfEnum { - IGNORE(0, "不记录"), - RECORD_TEXT(1, "记录文本"), - RECORD_TEXT_AUDIO(2, "文本音频都记录"); + IGNORE(0, "Do Not Log"), + RECORD_TEXT(1, "Record text"), + RECORD_TEXT_AUDIO(2, "Log text and audio"); private final int code; private final String name; @@ -322,21 +322,21 @@ public interface Constant { } /** - * 版本号 + * Version */ public static final String VERSION = "0.9.7"; /** - * 无效固件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 type */ enum DictType { /** - * 手机区号 + * Country code */ MOBILE_AREA("MOBILE_AREA"); 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 134b66c5f..4feba985c 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,11 @@ package xiaozhi.common.exception; /** - * 错误编码,由5位数字组成,前2位为模块编码,后3位为业务编码 + * Error code: 5 digits, first 2 for module, last 3 for business logic *

- * 如:10001(10代表系统模块,001代表业务代码) + * e.g., 10001 (10 represents the system module, 001 represents the 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 +44,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 +56,7 @@ public interface ErrorCode { int OTA_DEVICE_NOT_FOUND = 10041; int OTA_DEVICE_NEED_BIND = 10042; - // 新增错误编码 + // Add error code int DELETE_DATA_FAILED = 10043; int USER_NOT_LOGIN = 10044; int WEB_SOCKET_CONNECT_FAILED = 10045; @@ -67,7 +67,7 @@ public interface ErrorCode { int TOKEN_GENERATE_ERROR = 10050; int RESOURCE_NOT_FOUND = 10051; - // 新增错误编码 + // Add error code int DEFAULT_AGENT_NOT_FOUND = 10052; int AGENT_NOT_FOUND = 10053; int VOICEPRINT_API_NOT_CONFIGURED = 10054; @@ -80,184 +80,184 @@ public interface ErrorCode { int ACTIVATION_CODE_EMPTY = 10061; int ACTIVATION_CODE_ERROR = 10062; int DEVICE_ALREADY_ACTIVATED = 10063; - // 默认模型删除错误 + // Error deleting default model 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 verification code error + int MOBILE_REGISTER_DISABLED = 10068; // Mobile registration not enabled + int USERNAME_NOT_PHONE = 10069; // Username is not a phone number + int PHONE_ALREADY_REGISTERED = 10070; // Phone number already registered + int PHONE_NOT_REGISTERED = 10071; // Phone number not registered + int USER_REGISTER_DISABLED = 10072; // User registration not allowed + int RETRIEVE_PASSWORD_DISABLED = 10073; // Password recovery feature is disabled + int PHONE_FORMAT_ERROR = 10074; // Invalid phone number format + int SMS_CODE_ERROR = 10075; // Incorrect phone verification code - // 字典类型相关错误码 - 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; // Duplicate dictionary type code - // 资源处理相关错误码 - int RESOURCE_READ_ERROR = 10078; // 读取资源失败 + // Resource processing error codes + int RESOURCE_READ_ERROR = 10078; // Failed to Load Resource - // 智能体相关错误码 - int LLM_INTENT_PARAMS_MISMATCH = 10079; // LLM大模型和Intent意图识别,选择参数不匹配 + // Agent-related error codes + int LLM_INTENT_PARAMS_MISMATCH = 10079; // LLM and Intent recognition parameter mismatch - // 声纹相关错误码 - 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; // Voiceprint for this voice is already registered + int VOICEPRINT_DELETE_ERROR = 10081; // Error deleting voiceprint + int VOICEPRINT_UPDATE_NOT_ALLOWED = 10082; // Voiceprint modification not allowed; voice already registered + int VOICEPRINT_UPDATE_ADMIN_ERROR = 10083; // Voiceprint modification error, please contact the administrator + int VOICEPRINT_API_URI_ERROR = 10084; // Invalid voiceprint API address + 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 deregistration request failed + int VOICEPRINT_UNREGISTER_PROCESS_ERROR = 10090; // Voiceprint deregistration processing failed + int VOICEPRINT_IDENTIFY_REQUEST_ERROR = 10091; // Voiceprint recognition 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; // Configured LLM does not exist + int MODEL_REFERENCED_BY_AGENT = 10093; // This model config is referenced by an Agent and cannot be deleted + int LLM_REFERENCED_BY_INTENT = 10094; // This LLM model is referenced by intent recognition config 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-related error codes + int INVALID_SERVER_ACTION = 10095; // Invalid server operation + int SERVER_WEBSOCKET_NOT_CONFIGURED = 10096; // Server WebSocket address 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 verification 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; // Invalid WebSocket address format + 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; // OTA API access failed + int OTA_INTERFACE_FORMAT_ERROR = 10107; // OTA interface returned invalid content format + int OTA_INTERFACE_VALIDATION_FAILED = 10108; // OTA API 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; // MCP interface access failed + int MCP_INTERFACE_FORMAT_ERROR = 10113; // MCP interface returned invalid content format + int MCP_INTERFACE_VALIDATION_FAILED = 10114; // MCP interface validation failed + int VOICEPRINT_URL_EMPTY = 10115; // Voiceprint API address cannot be empty + int VOICEPRINT_URL_LOCALHOST = 10116; // The voiceprint API address must not use localhost or 127.0.0.1 + int VOICEPRINT_URL_INVALID = 10117; // Invalid voiceprint API endpoint + int VOICEPRINT_URL_PROTOCOL_ERROR = 10118; // Voiceprint API address must start with http or https + int VOICEPRINT_INTERFACE_ACCESS_FAILED = 10119; // Failed to access voiceprint API + int VOICEPRINT_INTERFACE_FORMAT_ERROR = 10120; // Invalid response format from voiceprint API + int VOICEPRINT_INTERFACE_VALIDATION_FAILED = 10121; // Voiceprint API validation failed + int MQTT_SECRET_EMPTY = 10122; // MQTT key cannot be empty + int MQTT_SECRET_LENGTH_INSECURE = 10123; // MQTT key length is insecure + int MQTT_SECRET_CHARACTER_INSECURE = 10124; // MQTT key must contain both uppercase and lowercase letters + int MQTT_SECRET_WEAK_PASSWORD = 10125; // MQTT key contains weak password + int DICT_LABEL_DUPLICATE = 10128; // Duplicate dictionary tag + int SM2_KEY_NOT_CONFIGURED = 10129; // SM2 key 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 related 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 expired or invalid + int DOWNLOAD_LINK_INVALID = 10137; // Invalid download link + 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; // Audio files only supported + int VOICE_CLONE_AUDIO_TOO_LARGE = 10142; // Audio file size must not exceed 10MB + int VOICE_CLONE_UPLOAD_FAILED = 10143; // Upload failed + int VOICE_CLONE_RECORD_NOT_EXIST = 10144; // Voice cloning record does not exist + int VOICE_RESOURCE_INFO_EMPTY = 10145; // Voice resource info 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 ID cannot be empty + int VOICE_RESOURCE_DELETE_ID_EMPTY = 10149; // Voice resource ID for deletion 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; // Please upload an audio file first + int VOICE_CLONE_MODEL_CONFIG_NOT_FOUND = 10152; // Model config not found + int VOICE_CLONE_MODEL_TYPE_NOT_FOUND = 10153; // Model type not found + int VOICE_CLONE_TRAINING_FAILED = 10154; // Training failed + int VOICE_CLONE_HUOSHAN_CONFIG_MISSING = 10155; // Volcano Engine configuration missing + int VOICE_CLONE_RESPONSE_FORMAT_ERROR = 10156; // Invalid response format + 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; // Invalid voice ID format for Volcano Engine - // 设备相关错误码 - 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 config not found + int RAG_CONFIG_TYPE_ERROR = 10165; // Invalid RAG config type + int RAG_DEFAULT_CONFIG_NOT_FOUND = 10166; // Default RAG config 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 RAG config, please complete the configuration + int RAG_API_ERROR_API_KEY_NULL = 10172; // api_key is empty in RAG config, please complete the configuration + int RAG_API_ERROR_API_KEY_INVALID = 10173; // The api_key in RAG config contains a placeholder; replace it with the actual API key + int RAG_API_ERROR_URL_INVALID = 10174; // Invalid base_url format in RAG config; check protocol + int RAG_DATASET_ID_NOT_NULL = 10176; // dataset_id cannot be empty in RAG config + int RAG_MODEL_ID_NOT_NULL = 10177; // model_id cannot be empty in RAG config + int RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL = 10178; // dataset_id and model_id cannot be empty in RAG config + 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地址不能为空 + // Device-related error codes (supplementary) + int MCA_NOT_NULL = 10175; // MAC address cannot be empty - // 音色克隆(补充) - int VOICE_CLONE_NAME_NOT_NULL = 10181; // 音色克隆名称不能为空 - int VOICE_CLONE_AUDIO_NOT_FOUND = 10182; // 音色克隆音频不存在 + // Voice cloning (supplement) + int VOICE_CLONE_NAME_NOT_NULL = 10181; // Voice clone name cannot be empty + int VOICE_CLONE_AUDIO_NOT_FOUND = 10182; // Voice cloning audio does not exist - // 智能体模板相关错误码(补充) - int AGENT_TEMPLATE_NOT_FOUND = 10183; // 默认智能体未找到 + // Agent template error codes (supplementary) + int AGENT_TEMPLATE_NOT_FOUND = 10183; // Default Agent 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; // Unsupported adapter type + int RAG_CONFIG_VALIDATION_FAILED = 10185; // RAG config validation failed + int RAG_ADAPTER_CREATION_FAILED = 10186; // Adapter creation failed + int RAG_ADAPTER_INIT_FAILED = 10187; // Adapter initialization failed + 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 Not Found + int RAG_ADAPTER_CACHE_ERROR = 10191; // Adapter cache error + int RAG_ADAPTER_TYPE_NOT_FOUND = 10192; // Adapter type 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 not found + int OTA_UPLOAD_COUNT_EXCEED = 10195; // OTA upload count exceeds limit - // 智能体标签相关错误码 - int AGENT_TAG_NAME_DUPLICATE = 10196; // 标签名称已存在 - int AGENT_TAG_NAME_EMPTY = 10197; // 标签名称不能为空 - int AGENT_TAG_NOT_EXIST = 10198; // 标签不存在 + // Agent tag-related 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; // Document parsing in progress, deletion prohibited - // 智能体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 the MCP endpoint address for this Agent + int MCP_ACCESS_POINT_ADDRESS_NOT_CONFIGURED = 10201; // Contact admin to configure MCP endpoint address in parameter management + int MCP_ACCESS_POINT_TOOLS_LIST_NO_PERMISSION = 10202; // No permission to view the MCP tool list for this Agent - // 替换词相关错误码 - int CORRECT_WORD_FILE_NAME_EXISTS = 10203; // 文件名已存在 - int FILE_SIZE_OVER_LIMIT = 10204; // 文件大小超过限制 + // Replacement word-related error codes + int CORRECT_WORD_FILE_NAME_EXISTS = 10203; // File name already exists + int FILE_SIZE_OVER_LIMIT = 10204; // File size exceeds limit } 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 2bfb6d353..db43b333f 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 @@ -189,7 +189,7 @@ public class RedisKeys { } /** - * 设备通讯录缓存Key + * Device contacts cache key */ public static String getAddressBookKey() { return "device:address_book:all"; 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 0961fe7b7..0c14dd6aa 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 @@ -57,7 +57,7 @@ import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO; import xiaozhi.modules.agent.vo.AgentInfoVO; import xiaozhi.modules.security.user.SecurityUser; -@Tag(name = "智能体管理") +@Tag(name = "Agent management") @AllArgsConstructor @RestController @RequestMapping("/agent") @@ -97,24 +97,24 @@ public class AgentController { } @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方法,无需再区分搜索和普通查询 + // Directly call the integrated getUserAgents method, no need to distinguish between search and standard queries List agents = agentService.getUserAgents(user.getId(), keyword, searchType); return new Result>().ok(agents); } @GetMapping("/all") - @Operation(summary = "智能体列表(管理员)") + @Operation(summary = "Agent list (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) { @@ -123,7 +123,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, SecurityUser.getUserId()); @@ -131,7 +131,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); @@ -139,7 +139,7 @@ public class AgentController { } @PutMapping("/saveMemory/{macAddress}") - @Operation(summary = "根据设备id更新智能体") + @Operation(summary = "Update agent by device ID") @RequiresPermissions("sys:role:normal") public Result updateByDeviceId(@PathVariable String macAddress, @RequestBody @Valid AgentMemoryDTO dto) { agentService.updateAgentMemoryByDeviceMacAddress(macAddress, dto, SecurityUser.getUserId()); @@ -147,29 +147,29 @@ public class AgentController { } @PostMapping("/chat-summary/{sessionId}/save") - @Operation(summary = "根据会话ID生成聊天记录总结并保存(异步执行)") + @Operation(summary = "Generate and save chat history summary based on session ID (async execution)") public Result generateAndSaveChatSummary(@PathVariable String sessionId) { requireSessionAgent(sessionId); try { - // 异步执行总结生成任务,立即返回成功响应 + // Execute summary generation asynchronously and return success immediately new Thread(() -> { try { agentChatSummaryService.generateAndSaveChatSummary(sessionId); - System.out.println("异步执行会话 " + sessionId + " 的聊天记录总结完成"); + System.out.println("Async chat history summary completed for session " + sessionId); } catch (Exception e) { - System.err.println("异步执行会话 " + sessionId + " 的聊天记录总结失败: " + e.getMessage()); + System.err.println("Failed to summarize chat history for async session " + sessionId + ": " + e.getMessage()); } }).start(); - // 立即返回成功响应,不等待总结生成完成 + // Return success response immediately without waiting for summary generation return new Result().ok(null); } catch (Exception e) { - return new Result().error("启动异步总结生成任务失败: " + e.getMessage()); + return new Result().error("Failed to start async summary generation task: " + e.getMessage()); } } @PostMapping("/chat-title/{sessionId}/generate") - @Operation(summary = "根据会话ID生成聊天标题") + @Operation(summary = "Generate chat title based on session ID") public Result generateAndSaveChatTitle(@PathVariable String sessionId) { requireSessionAgent(sessionId); agentChatSummaryService.generateAndSaveChatTitle(sessionId); @@ -177,7 +177,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, SecurityUser.getUserId()); @@ -185,7 +185,7 @@ public class AgentController { } @DeleteMapping("/{id}") - @Operation(summary = "删除智能体") + @Operation(summary = "Delete Agent") @RequiresPermissions("sys:role:normal") public Result delete(@PathVariable String id) { agentService.deleteAgentById(id, SecurityUser.getUserId()); @@ -193,7 +193,7 @@ public class AgentController { } @GetMapping("/template") - @Operation(summary = "智能体模板模板列表") + @Operation(summary = "Agent template list") @RequiresPermissions("sys:role:normal") public Result> templateList() { List list = agentTemplateService @@ -202,11 +202,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, @@ -218,61 +218,61 @@ 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) { - // 获取当前用户 + // Get current user UserDetail user = SecurityUser.getUser(); - // 检查权限 + // Check permissions if (!agentService.checkAgentPermission(id, user.getId())) { - return new Result>().error("没有权限查看该智能体的聊天记录"); + return new Result>().error("No 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) { - // 获取当前用户 + // Get current user UserDetail user = SecurityUser.getUser(); - // 检查权限 + // Check permissions if (!agentService.checkAgentPermission(id, user.getId())) { - return new Result>().error("没有权限查看该智能体的聊天记录"); + return new Result>().error("No 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) { requireAudioPermission(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) { requireAudioPermission(audioId); byte[] audioData = agentChatAudioService.getAudio(audioId); if (audioData == null) { - return new Result().error("音频不存在"); + return new Result().error("Audio not found"); } String uuid = UUID.randomUUID().toString(); redisUtils.set(RedisKeys.getAgentAudioIdKey(uuid), audioId, AUDIO_PLAY_TOKEN_EXPIRE_SECONDS); @@ -280,7 +280,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)); @@ -300,19 +300,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 list") @RequiresPermissions("sys:role:normal") public Result> getAllTags() { List tags = agentTagService.getAllTags(); @@ -320,7 +320,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); @@ -328,7 +328,7 @@ public class AgentController { } @GetMapping("/{id}/tags") - @Operation(summary = "获取智能体的标签") + @Operation(summary = "Get agent tags") @RequiresPermissions("sys:role:normal") public Result> getAgentTags(@PathVariable String id) { requireAgentPermission(id); @@ -337,7 +337,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) { requireAgentPermission(id); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentSnapshotController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentSnapshotController.java index de4b57b29..f9a4c2a24 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentSnapshotController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentSnapshotController.java @@ -25,7 +25,7 @@ import xiaozhi.modules.agent.service.AgentSnapshotService; import xiaozhi.modules.agent.vo.AgentSnapshotVO; import xiaozhi.modules.security.user.SecurityUser; -@Tag(name = "智能体快照") +@Tag(name = "Agent snapshot") @AllArgsConstructor @RestController @RequestMapping("/agent/{agentId}/snapshots") @@ -34,7 +34,7 @@ public class AgentSnapshotController { private final AgentService agentService; @GetMapping - @Operation(summary = "获取智能体快照列表") + @Operation(summary = "Get Agent snapshot list") @RequiresPermissions("sys:role:normal") public Result> page( @PathVariable String agentId, @@ -44,7 +44,7 @@ public class AgentSnapshotController { } @GetMapping("/{snapshotId}") - @Operation(summary = "获取智能体快照详情") + @Operation(summary = "Get agent snapshot details") @RequiresPermissions("sys:role:normal") public Result getSnapshot(@PathVariable String agentId, @PathVariable String snapshotId) { checkPermission(agentId); @@ -52,7 +52,7 @@ public class AgentSnapshotController { } @PostMapping("/{snapshotId}/restore") - @Operation(summary = "恢复智能体快照") + @Operation(summary = "Restore agent snapshot") @RequiresPermissions("sys:role:normal") public Result restore(@PathVariable String agentId, @PathVariable String snapshotId, @RequestBody @Valid AgentSnapshotRestoreDTO request) { @@ -62,7 +62,7 @@ public class AgentSnapshotController { } @DeleteMapping("/{snapshotId}") - @Operation(summary = "删除智能体历史快照") + @Operation(summary = "Delete agent history snapshot") @RequiresPermissions("sys:role:normal") public Result deleteSnapshot(@PathVariable String agentId, @PathVariable String snapshotId) { checkPermission(agentId); @@ -73,7 +73,7 @@ public class AgentSnapshotController { private void checkPermission(String agentId) { UserDetail user = SecurityUser.getUser(); if (user == null || !agentService.checkAgentPermission(agentId, user.getId())) { - throw new RenException("没有权限访问该智能体快照"); + throw new RenException("No permission to access this agent snapshot"); } } } 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 82d7ef29a..1d6b935ca 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 @@ -38,18 +38,18 @@ public interface AgentDao extends BaseDao { AgentInfoVO selectAgentInfoById(@Param("agentId") String agentId); /** - * 锁定智能体主记录,用于串行化同一智能体的配置写入 + * Lock Agent main record to serialize config writes for the same Agent * - * @param agentId 智能体ID + * @param agentId Agent ID */ AgentEntity selectByIdForUpdate(@Param("agentId") String agentId); /** - * 精确写入快照覆盖的智能体字段,包括目标快照中的 null 值。 - * 不更新所属用户、创建信息等不属于快照的字段。 + * Precisely overwrite Agent fields in the snapshot, including null values from the target snapshot. + * Do not update fields not included in the snapshot, such as owner user and creation info * - * @param agent 已应用目标快照的智能体 - * @return 受影响行数 + * @param agent Agent with target snapshot applied + * @return Number of affected rows */ int updateSnapshotFields(@Param("agent") AgentEntity agent); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotDataDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotDataDTO.java index 328c73cf3..de5abcf91 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotDataDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotDataDTO.java @@ -7,7 +7,7 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data -@Schema(description = "智能体快照数据") +@Schema(description = "Agent snapshot data") public class AgentSnapshotDataDTO implements Serializable { private static final long serialVersionUID = 1L; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotPageDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotPageDTO.java index 3f3f5d655..12e1b44ac 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotPageDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotPageDTO.java @@ -4,15 +4,15 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data -@Schema(description = "智能体快照分页查询参数") +@Schema(description = "Agent snapshot pagination parameters") public class AgentSnapshotPageDTO { - @Schema(description = "当前页码,从1开始", example = "1") + @Schema(description = "Current page number, starting from 1", example = "1") private Integer page = 1; - @Schema(description = "每页数量", example = "10") + @Schema(description = "Items per page", example = "10") private Integer limit = 10; - @Schema(description = "版本锚点,只查询小于等于该版本号的历史快照", example = "20") + @Schema(description = "Version anchor; query only historical snapshots with version <= this value", example = "20") private Integer maxVersionNo; public int pageOrDefault() { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotRestoreDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotRestoreDTO.java index aa003fa4e..16e7e6e9b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotRestoreDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotRestoreDTO.java @@ -5,9 +5,9 @@ import jakarta.validation.constraints.NotBlank; import lombok.Data; @Data -@Schema(description = "智能体快照恢复请求") +@Schema(description = "Agent snapshot restore request") public class AgentSnapshotRestoreDTO { @NotBlank - @Schema(description = "预览时由服务端生成的当前配置状态指纹") + @Schema(description = "Current config state fingerprint generated by server during preview") private String currentStateToken; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotTagDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotTagDTO.java index 6e93dd0e5..f61b0d6a1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotTagDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentSnapshotTagDTO.java @@ -6,7 +6,7 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data -@Schema(description = "智能体快照标签") +@Schema(description = "Agent snapshot tag") public class AgentSnapshotTagDTO implements Serializable { private static final long serialVersionUID = 1L; 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 f034023d4..fc15e50a5 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 @@ -91,13 +91,13 @@ public class AgentUpdateDTO implements Serializable { @Schema(description = "Context-provider configuration", nullable = true) private List contextProviders; - @Schema(description = "替换词文件ID列表", nullable = true) + @Schema(description = "List of replacement word file IDs", nullable = true) private List correctWordFileIds; - @Schema(description = "标签名称列表", nullable = true) + @Schema(description = "Tag name list", nullable = true) private List tagNames; - @Schema(description = "标签ID列表", nullable = true) + @Schema(description = "Tag ID list", nullable = true) private List tagIds; @Data diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentCorrectWordMappingEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentCorrectWordMappingEntity.java index 6b7d0c5ac..ebea7341e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentCorrectWordMappingEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentCorrectWordMappingEntity.java @@ -11,28 +11,28 @@ import lombok.Data; @Data @TableName("ai_agent_correct_word_mapping") -@Schema(description = "智能体替换词文件关联") +@Schema(description = "Agent replacement word file association") public class AgentCorrectWordMappingEntity { @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 = "Replacement word file ID") private String fileId; - @Schema(description = "创建者") + @Schema(description = "Creator") private Long creator; - @Schema(description = "创建时间") + @Schema(description = "Creation Time") private Date createdAt; - @Schema(description = "更新者") + @Schema(description = "Updated by") private Long updater; - @Schema(description = "更新时间") + @Schema(description = "Update time") private Date updatedAt; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentSnapshotEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentSnapshotEntity.java index c4ad695df..56228be80 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentSnapshotEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentSnapshotEntity.java @@ -11,43 +11,43 @@ import lombok.Data; @Data @TableName("ai_agent_snapshot") -@Schema(description = "智能体配置快照") +@Schema(description = "Agent config snapshot") public class AgentSnapshotEntity { @TableId(type = IdType.ASSIGN_UUID) - @Schema(description = "快照ID") + @Schema(description = "Snapshot ID") private String id; - @Schema(description = "智能体ID") + @Schema(description = "Agent ID") private String agentId; - @Schema(description = "所属用户ID") + @Schema(description = "User ID") private Long userId; - @Schema(description = "版本号") + @Schema(description = "Version") private Integer versionNo; - @Schema(description = "快照数据JSON") + @Schema(description = "Snapshot data JSON") private String snapshotData; - @Schema(description = "变更字段JSON") + @Schema(description = "Change field JSON") private String changedFields; - @Schema(description = "快照来源") + @Schema(description = "Snapshot source") private String source; - @Schema(description = "恢复来源快照ID") + @Schema(description = "Source snapshot ID for restoration") private String restoreFromSnapshotId; - @Schema(description = "恢复来源版本号") + @Schema(description = "Restore source version") private Integer restoreFromVersionNo; - @Schema(description = "创建者") + @Schema(description = "Creator") private Long creator; - @Schema(description = "创建时间") + @Schema(description = "Creation Time") private Date createdAt; - @Schema(description = "快照数据脱敏规则版本") + @Schema(description = "Snapshot data masking rule version") private Integer redactionVersion; } 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 a5adb43c8..495aa72a1 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 @@ -38,10 +38,10 @@ public interface AgentChatHistoryService extends IRepository getChatHistoryBySessionId(String agentId, String sessionId); /** - * 根据会话ID获取智能体ID + * Get agent ID by session ID * - * @param sessionId 会话ID - * @return 智能体ID + * @param sessionId Session ID + * @return Agent ID */ String getAgentIdBySessionId(String sessionId); @@ -79,10 +79,10 @@ public interface AgentChatHistoryService extends IRepository { /** - * 根据智能体id获取插件参数 + * Get plugin parameters by agent ID * * @param agentId * @return @@ -21,16 +21,16 @@ public interface AgentPluginMappingService extends IRepository agentPluginParamsByAgentId(String agentId); /** - * 根据智能体id删除插件参数 + * Delete plugin parameters by agent ID * * @param agentId */ void deleteByAgentId(String agentId); /** - * 根据插件ID删除所有智能体的插件映射 + * Delete plugin mappings for all Agents by plugin ID * - * @param pluginId 插件ID + * @param pluginId Plugin ID */ void deleteByPluginId(String pluginId); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java index 8001c205f..72892d954 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java @@ -104,18 +104,18 @@ public class AgentServiceImpl extends BaseServiceImpl imp agent.setChatHistoryConf(Constant.ChatHistoryConfEnum.RECORD_TEXT_AUDIO.getCode()); } - // 查询上下文源配置 + // Query context source configuration AgentContextProviderEntity contextProviderEntity = agentContextProviderService.getByAgentId(id); if (contextProviderEntity != null) { agent.setContextProviders(contextProviderEntity.getContextProviders()); } - // 查询替换词文件ID列表 + // Query replacement word file ID list List correctWordFileIds = correctWordFileService.getAgentCorrectWordFileIds(id); agent.setCorrectWordFileIds(correctWordFileIds); agent.setCurrentVersionNo(agentSnapshotService.getCurrentVersionNo(id)); - // 无需额外查询插件列表,已通过SQL查询出来 + // No additional plugin list query needed; already retrieved via SQL return agent; } @@ -180,17 +180,17 @@ public class AgentServiceImpl extends BaseServiceImpl imp @Override public boolean insert(AgentEntity entity) { - // 如果ID为空,自动生成一个UUID作为ID + // If ID is empty, generate a UUID as ID if (entity.getId() == null || entity.getId().trim().isEmpty()) { entity.setId(UUID.randomUUID().toString().replace("-", "")); } - // 如果智能体编码为空,自动生成一个带前缀的编码 + // If the Agent code is empty, auto-generate a code with a prefix if (entity.getAgentCode() == null || entity.getAgentCode().trim().isEmpty()) { entity.setAgentCode("AGT_" + System.currentTimeMillis()); } - // 如果排序字段为空,设置默认值0 + // If sort field is empty, set default value to 0 if (entity.getSort() == null) { entity.setSort(0); } @@ -232,10 +232,10 @@ public class AgentServiceImpl extends BaseServiceImpl imp if (StringUtils.isNotBlank(keyword)) { queryWrapper.and(w -> { - // 按名称搜索 + // Search by name w.like("agent_name", keyword); - // 按MAC地址搜索:先查设备,再获取对应的智能体ID + // Search by MAC address: query device first, then retrieve the corresponding Agent ID List devices = Optional .ofNullable(deviceService.searchDevicesByMacAddress(keyword, userId)) .orElseGet(ArrayList::new); @@ -247,7 +247,7 @@ public class AgentServiceImpl extends BaseServiceImpl imp w.or().in("id", agentIds); } - // 按标签名搜索 + // Search by tag name List tagAgentIds = agentTagService.getAgentIdsByTagName(keyword); if (CollUtil.isNotEmpty(tagAgentIds)) { w.or().in("id", tagAgentIds); @@ -260,7 +260,7 @@ public class AgentServiceImpl extends BaseServiceImpl imp } /** - * 将AgentEntity转换为AgentDTO + * Convert AgentEntity to AgentDTO */ private AgentDTO buildAgentDTO(AgentEntity agent) { AgentDTO dto = new AgentDTO(); @@ -268,28 +268,28 @@ public class AgentServiceImpl extends BaseServiceImpl imp dto.setAgentName(agent.getAgentName()); dto.setSystemPrompt(agent.getSystemPrompt()); - // 获取 TTS 模型名称 + // Get TTS model name dto.setTtsModelName(modelConfigService.getModelNameById(agent.getTtsModelId())); - // 获取 LLM 模型名称 + // Get LLM model name dto.setLlmModelName(modelConfigService.getModelNameById(agent.getLlmModelId())); - // 获取 VLLM 模型名称 + // Get VLLM model name dto.setVllmModelName(modelConfigService.getModelNameById(agent.getVllmModelId())); - // 获取记忆模型名称 + // Get memory model name dto.setMemModelId(agent.getMemModelId()); - // 获取 TTS 音色名称 + // Get TTS voice name dto.setTtsVoiceName(timbreModelService.getTimbreNameById(agent.getTtsVoiceId())); - // 获取智能体最近的最后连接时长 + // Get the Agent's recent last connection duration dto.setLastConnectedAt(deviceService.getLatestLastConnectionTime(agent.getId())); - // 获取设备数量 + // Get device count dto.setDeviceCount(getDeviceCountByAgentId(agent.getId())); - // 获取标签列表 + // Get tag list List tags = agentTagDao.selectByAgentId(agent.getId()); if (CollUtil.isNotEmpty(tags)) { dto.setTags(tags.stream().map(this::convertTagToDTO).collect(Collectors.toList())); @@ -311,16 +311,16 @@ public class AgentServiceImpl extends BaseServiceImpl imp return 0; } - // 先从Redis中获取 + // Fetch from Redis first Integer cachedCount = (Integer) redisUtils.get(RedisKeys.getAgentDeviceCountById(agentId)); if (cachedCount != null) { return cachedCount; } - // 如果Redis中没有,则从数据库查询 + // If not found in Redis, query from the database Integer deviceCount = agentDao.getDeviceCountByAgentId(agentId); - // 将结果存入Redis + // Store result in Redis if (deviceCount != null) { redisUtils.set(RedisKeys.getAgentDeviceCountById(agentId), deviceCount, 60); } @@ -342,7 +342,7 @@ public class AgentServiceImpl extends BaseServiceImpl imp return hasAgentPermission(agent, userId); } - // 根据id更新智能体信息 + // Update agent info by ID @Override @Transactional(rollbackFor = Exception.class) public void updateAgentById(String agentId, AgentUpdateDTO dto) { @@ -355,7 +355,7 @@ public class AgentServiceImpl extends BaseServiceImpl imp updateAgentById(agentId, dto, userId, true); } - // 根据id更新智能体信息 + // Update agent info by ID @Override @Transactional(rollbackFor = Exception.class) public void updateAgentById(String agentId, AgentUpdateDTO dto, boolean createSnapshot) { @@ -373,14 +373,14 @@ public class AgentServiceImpl extends BaseServiceImpl imp requireAgentPermission(lockedAgent, userId); } - // 锁定后查询现有实体和关联配置 + // Query existing entities and associated configs after locking AgentEntity existingEntity = this.getAgentById(agentId); if (createSnapshot) { int currentVersionNo = agentSnapshotService.getCurrentVersionNo(agentId); agentSnapshotService.createSnapshot(agentId, currentVersionNo == 0 ? "initial" : "current"); } - // 只更新提供的非空字段 + // Update only provided non-empty fields if (dto.getAgentName() != null) { existingEntity.setAgentName(dto.getAgentName()); } @@ -445,22 +445,22 @@ public class AgentServiceImpl extends BaseServiceImpl imp existingEntity.setSort(dto.getSort()); } - // 更新函数插件信息 + // Update function plugin info List functions = dto.getFunctions(); if (functions != null) { - // 1. 收集本次提交的 pluginId + // 1. Collect pluginId for this commit List newPluginIds = functions.stream() .map(AgentUpdateDTO.FunctionInfo::getPluginId) .toList(); - // 2. 查询当前agent现有的所有映射 + // 2. Query all existing mappings for the current agent List existing = agentPluginMappingService.list( new QueryWrapper() .eq("agent_id", agentId)); Map existMap = existing.stream() .collect(Collectors.toMap(AgentPluginMapping::getPluginId, Function.identity())); - // 3. 构造所有要 保存或更新 的实体 + // 3. Construct all entities to save or update List allToPersist = functions.stream().map(info -> { AgentPluginMapping m = new AgentPluginMapping(); m.setAgentId(agentId); @@ -468,13 +468,13 @@ public class AgentServiceImpl extends BaseServiceImpl imp m.setParamInfo(JsonUtils.toJsonString(info.getParamInfo())); AgentPluginMapping old = existMap.get(info.getPluginId()); if (old != null) { - // 已存在,设置id表示更新 + // Already exists, setting id indicates update m.setId(old.getId()); } return m; }).toList(); - // 4. 拆分:已有ID的走更新,无ID的走插入 + // 4. Split: update existing IDs, insert new ones List toUpdate = allToPersist.stream() .filter(m -> m.getId() != null) .toList(); @@ -489,7 +489,7 @@ public class AgentServiceImpl extends BaseServiceImpl imp agentPluginMappingService.saveBatch(toInsert, IRepository.DEFAULT_BATCH_SIZE); } - // 5. 删除本次不在提交列表里的插件映射 + // 5. Remove plugin mappings not included in this commit list List toDelete = existing.stream() .filter(old -> !newPluginIds.contains(old.getPluginId())) .map(AgentPluginMapping::getId) @@ -499,23 +499,23 @@ public class AgentServiceImpl extends BaseServiceImpl imp } } - // 设置更新者信息 + // Set updater info UserDetail user = SecurityUser.getUser(); existingEntity.setUpdater(user.getId()); existingEntity.setUpdatedAt(new Date()); - // 更新记忆策略 - // 删除所有记录 + // Update memory policy + // Delete all records if (existingEntity.getMemModelId() != null && existingEntity.getMemModelId().equals(Constant.MEMORY_NO_MEM)) { agentChatHistoryService.deleteByAgentId(existingEntity.getId(), true, true); existingEntity.setSummaryMemory(""); - // 删除记忆 + // Delete memory } else if (existingEntity.getMemModelId() != null && existingEntity.getMemModelId().equals(Constant.MEMORY_MEM_REPORT_ONLY)) { existingEntity.setSummaryMemory(""); } - // 更新上下文源配置 + // Update context source config if (dto.getContextProviders() != null) { AgentContextProviderEntity contextEntity = new AgentContextProviderEntity(); contextEntity.setAgentId(agentId); @@ -523,12 +523,12 @@ public class AgentServiceImpl extends BaseServiceImpl imp agentContextProviderService.saveOrUpdateByAgentId(contextEntity); } - // 更新替换词文件关联 + // Update replacement word file associations if (dto.getCorrectWordFileIds() != null) { correctWordFileService.saveAgentCorrectWords(agentId, dto.getCorrectWordFileIds()); } - // 更新智能体标签 + // Update agent tag if (dto.getTagNames() != null || dto.getTagIds() != null) { agentTagService.saveAgentTags(agentId, dto.getTagIds(), dto.getTagNames()); } @@ -567,11 +567,11 @@ public class AgentServiceImpl extends BaseServiceImpl imp } /** - * 验证大语言模型和意图识别的参数是否符合匹配 + * Validate parameters for LLM and intent recognition * - * @param llmModelId 大语言模型id - * @param intentModelId 意图识别id - * @return T 匹配 : F 不匹配 + * @param llmModelId LLM model id + * @param intentModelId Intent recognition ID + * @return T match : F no match */ private boolean validateLLMIntentParams(String llmModelId, String intentModelId) { if (StringUtils.isBlank(llmModelId)) { @@ -579,24 +579,24 @@ public class AgentServiceImpl extends BaseServiceImpl imp } ModelConfigEntity llmModelData = modelConfigService.selectById(llmModelId); String type = llmModelData.getConfigJson().get("type").toString(); - // 如果查询大语言模型是openai或者ollama,意图识别选参数都可以 + // If the LLM is OpenAI or Ollama, any intent recognition parameter is acceptable if ("openai".equals(type) || "ollama".equals(type)) { return true; } - // 除了openai和ollama的类型,不可以选择id为Intent_function_call(函数调用)的意图识别 + // Except for openai and ollama types, do not select the intent recognition with id Intent_function_call (function call) return !"Intent_function_call".equals(intentModelId); } @Override @Transactional(rollbackFor = Exception.class) public String createAgent(AgentCreateDTO dto) { - // 转换为实体 + // Convert to entity AgentEntity entity = ConvertUtils.sourceToTarget(dto, AgentEntity.class); - // 获取默认模板 + // Get default template AgentTemplateEntity template = agentTemplateService.getDefaultTemplate(); if (template != null) { - // 设置模板中的默认值 + // Set default values in template entity.setAsrModelId(template.getAsrModelId()); entity.setVadModelId(template.getVadModelId()); entity.setLlmModelId(template.getLlmModelId()); @@ -630,13 +630,13 @@ public class AgentServiceImpl extends BaseServiceImpl imp entity.setSummaryMemory(""); } - // 根据记忆模型类型设置默认的chatHistoryConf值 + // Set the default chatHistoryConf value 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 text and voice by default entity.setChatHistoryConf(2); } } else { @@ -654,18 +654,18 @@ public class AgentServiceImpl extends BaseServiceImpl imp } } - // 设置用户ID和创建者信息 + // Set user ID and creator info UserDetail user = SecurityUser.getUser(); entity.setUserId(user.getId()); entity.setCreator(user.getId()); entity.setCreatedAt(new Date()); - // 保存智能体 + // Save Agent insert(entity); - // 设置默认插件 + // Set Default Plugin List toInsert = new ArrayList<>(); - // 播放音乐、查天气、查新闻 + // Play music, check weather, check news String[] pluginIds = new String[] { "SYSTEM_PLUGIN_MUSIC", "SYSTEM_PLUGIN_WEATHER", "SYSTEM_PLUGIN_NEWS_NEWSNOW" }; for (String pluginId : pluginIds) { @@ -687,7 +687,7 @@ public class AgentServiceImpl extends BaseServiceImpl imp mapping.setAgentId(entity.getId()); toInsert.add(mapping); } - // 保存默认插件 + // Save default plugin agentPluginMappingService.saveBatch(toInsert, IRepository.DEFAULT_BATCH_SIZE); agentSnapshotService.createSnapshot(entity.getId(), "initial"); return entity.getId(); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentSnapshotServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentSnapshotServiceImpl.java index 0cab47fb2..d02bb1728 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentSnapshotServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentSnapshotServiceImpl.java @@ -157,13 +157,13 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl 1) { - throw new RenException("智能体快照恢复失败"); + throw new RenException("Failed to restore agent snapshot"); } restoreFunctions(agentId, restoreData.getFunctions()); @@ -218,7 +218,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl rawData = JsonUtils.parseObject(snapshot.getSnapshotData(), OBJECT_MAP_TYPE); if (rawData == null) { - throw new RenException("历史快照数据无法解析,已中止脱敏迁移: " + snapshot.getId()); + throw new RenException("Failed to parse historical snapshot data, aborting desensitization migration: " + snapshot.getId()); } snapshot.setSnapshotData(JsonUtils.toJsonString(redactSensitiveMap(rawData))); } int affected = agentSnapshotDao.updateRedactedSnapshots(batch, CURRENT_REDACTION_VERSION); if (affected < 0 || affected > batch.size()) { - throw new RenException("历史快照批量脱敏迁移失败"); + throw new RenException("Failed to batch migrate and desensitize historical snapshots"); } migrated += affected; afterId = batch.get(batch.size() - 1).getId(); @@ -289,7 +289,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl map, String key) { @@ -1009,7 +1009,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl currentIdentities = structuredSensitiveDiscriminatorIdentities(current); if (targetIdentities.size() != 1 || currentIdentities.size() != 1 || !Objects.equals(targetIdentities.get(0), currentIdentities.get(0))) { - throw new RenException("快照结构化敏感值的类型标识无法与当前配置唯一匹配"); + throw new RenException("Type identifier for structured sensitive values in the snapshot cannot be uniquely matched with the current config"); } } @@ -1207,14 +1207,14 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl matchingCurrent = currentSensitiveParameters.getOrDefault(identity, Collections.emptyList()); if (matchingTargets.size() != 1 || matchingCurrent.size() != 1) { - throw new RenException("快照 URL 中的敏感参数无法与当前配置唯一匹配"); + throw new RenException("Sensitive parameters in the snapshot URL cannot be uniquely matched with the current config"); } UrlParameter currentParameter = matchingCurrent.get(0); if (currentParameter.rawValue().contains(SECRET_PLACEHOLDER)) { - throw new RenException("快照 URL 中的敏感信息无法与当前配置可靠匹配"); + throw new RenException("Sensitive information in the snapshot URL cannot be reliably matched with the current config"); } result.add(new UrlParameter(targetParameter.rawKey(), currentParameter.rawValue(), currentParameter.hasEquals())); @@ -1393,7 +1393,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl> currentSlots = current.slots().stream() @@ -1404,10 +1404,10 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl StringUtils.isBlank(secret) || secret.contains(SECRET_PLACEHOLDER))) { - throw new RenException("快照 URL 路径敏感信息无法与当前配置可靠匹配"); + throw new RenException("Sensitive information in the snapshot URL path cannot be reliably matched with the current config"); } if (replacements.put(targetSlot.identity(), matches.get(0)) != null) { - throw new RenException("快照 URL 路径敏感信息存在歧义,无法安全恢复"); + throw new RenException("Ambiguous sensitive information in the snapshot URL path; safe recovery not possible"); } } return rebuildSensitivePath(target, replacements); @@ -1704,7 +1704,7 @@ public class AgentSnapshotServiceImpl extends BaseServiceImpl contextProviders; - @Schema(description = "替换词文件ID列表") + @Schema(description = "List of replacement word file IDs") private List correctWordFileIds; - @Schema(description = "当前配置版本号") + @Schema(description = "Current config version") private Integer currentVersionNo; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentSnapshotVO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentSnapshotVO.java index d5a44e1da..82ad23288 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentSnapshotVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentSnapshotVO.java @@ -8,27 +8,27 @@ import lombok.Data; import xiaozhi.modules.agent.dto.AgentSnapshotDataDTO; @Data -@Schema(description = "智能体配置快照") +@Schema(description = "Agent config snapshot") public class AgentSnapshotVO { private String id; private String agentId; - @Schema(description = "所属用户ID,表示该快照归属的智能体所有者") + @Schema(description = "Owner user ID, indicating the Agent owner of this snapshot") private Long userId; private Integer versionNo; private List changedFields; private List fieldOrder; private String source; - @Schema(description = "恢复来源快照ID,仅恢复结果版本有值") + @Schema(description = "Restore source snapshot ID; only set for restored result versions") private String restoreFromSnapshotId; - @Schema(description = "恢复来源版本号,仅恢复结果版本有值") + @Schema(description = "Restore source version number, only restore if result version has value") private Integer restoreFromVersionNo; - @Schema(description = "创建者,表示触发本次快照写入的操作人") + @Schema(description = "Creator, indicating the operator who triggered this snapshot write") private Long creator; private Date createdAt; private AgentSnapshotDataDTO snapshotData; private AgentSnapshotDataDTO afterSnapshotData; - @Schema(description = "恢复预览对应的脱敏当前配置,仅详情接口有值") + @Schema(description = "Restore desensitized current config for preview; only populated in detail API") private AgentSnapshotDataDTO currentSnapshotData; - @Schema(description = "恢复预览对应的当前配置状态指纹,仅详情接口有值") + @Schema(description = "Fingerprint of current config state corresponding to restore preview, only present in detail API") private String currentStateToken; } 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 65c6a698f..504a8368f 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 @@ -46,7 +46,7 @@ public class ConfigController { } @PostMapping("correct-words") - @Operation(summary = "获取智能体替换词") + @Operation(summary = "Get agent replacement words") public Result getCorrectWords(@Valid @RequestBody CorrectWordsDTO dto) { ValidatorUtils.validateEntity(dto); List list = configService.getCorrectWords(dto.getMacAddress()); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/dto/CorrectWordsDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/config/dto/CorrectWordsDTO.java index 0c689d5d3..bd7d914b4 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/dto/CorrectWordsDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/dto/CorrectWordsDTO.java @@ -5,10 +5,10 @@ import jakarta.validation.constraints.NotBlank; import lombok.Data; @Data -@Schema(description = "获取智能体替换词DTO") +@Schema(description = "Get agent replacement word DTO") public class CorrectWordsDTO { - @NotBlank(message = "设备MAC地址不能为空") - @Schema(description = "设备MAC地址") + @NotBlank(message = "Device MAC address cannot be empty") + @Schema(description = "Device MAC address") private String macAddress; } 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 4299c9d54..be3c1f6b1 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 @@ -32,19 +32,19 @@ public class SystemInitConfig { @PostConstruct public void init() { - // 检查版本号 + // Check version String redisVersion = (String) redisUtils.get(RedisKeys.getVersionKey()); if (!Constant.VERSION.equals(redisVersion)) { - // 如果版本不一致,清空Redis + // If version mismatch, clear Redis redisUtils.emptyAll(); - // 存储新版本号 + // Store new version number redisUtils.set(RedisKeys.getVersionKey(), Constant.VERSION); } sysParamsService.initServerSecret(); configService.getConfig(false); - // 初始化设备通讯录缓存 + // Initialize device contact cache deviceAddressBookService.refreshCache(); } } 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 81f19853e..d5a9d97ae 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 @@ -5,27 +5,27 @@ import java.util.Map; public interface ConfigService { /** - * 获取服务器配置 + * Get server config * - * @param isCache 是否缓存 - * @return 配置信息 + * @param isCache Whether to cache + * @return Config info */ Map getConfig(Boolean isCache); /** - * 获取智能体模型配置 + * Get agent model config * - * @param macAddress MAC地址 - * @param selectedModule 客户端已实例化的模型 - * @return 模型配置信息 + * @param macAddress MAC address + * @param selectedModule Model instance initialized by the client + * @return Model configuration info */ Map getAgentModels(String macAddress, Map selectedModule); /** - * 获取智能体替换词 + * Get agent replacement words * - * @param macAddress 设备MAC地址 - * @return 替换词列表,格式如 ["模板1|模板01", "模板2|模板02"] + * @param macAddress Device MAC address + * @return List of replacement words, format: ["template1|template01", "template2|template02"] */ List getCorrectWords(String macAddress); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/correctword/controller/CorrectWordController.java b/main/manager-api/src/main/java/xiaozhi/modules/correctword/controller/CorrectWordController.java index 5569587fc..8e7db48c3 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/correctword/controller/CorrectWordController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/correctword/controller/CorrectWordController.java @@ -34,14 +34,14 @@ import xiaozhi.modules.correctword.vo.CorrectWordFileVO; @RestController @RequestMapping("/correct-word") -@Tag(name = "替换词管理") +@Tag(name = "Replacement word management") @AllArgsConstructor public class CorrectWordController { private final CorrectWordFileService correctWordFileService; @PostMapping("/file") - @Operation(summary = "创建替换词文件") + @Operation(summary = "Create replacement word file") @RequiresPermissions("sys:role:normal") public Result createFile(@Valid @RequestBody CorrectWordFileCreateDTO dto) { CorrectWordFileVO vo = correctWordFileService.createFile(dto); @@ -49,7 +49,7 @@ public class CorrectWordController { } @PutMapping("/file/{fileId}") - @Operation(summary = "修改替换词文件") + @Operation(summary = "Modify replacement word file") @RequiresPermissions("sys:role:normal") public Result updateFile(@PathVariable String fileId, @Valid @RequestBody CorrectWordFileCreateDTO dto) { correctWordFileService.updateFile(fileId, dto); @@ -57,11 +57,11 @@ public class CorrectWordController { } @GetMapping("/file/list") - @Operation(summary = "分页获取当前用户替换词文件列表") + @Operation(summary = "Paginate current user's replacement word file 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> listFiles( @Parameter(hidden = true) @RequestParam Map params) { @@ -70,7 +70,7 @@ public class CorrectWordController { } @GetMapping("/file/select") - @Operation(summary = "智能体获取当前用户替换词文件列表") + @Operation(summary = "Agent retrieves the current user's replacement word file list") @RequiresPermissions("sys:role:normal") public Result> listAllFiles() { List list = correctWordFileService.listAllFiles(); @@ -78,7 +78,7 @@ public class CorrectWordController { } @GetMapping("/file/download/{fileId}") - @Operation(summary = "下载替换词文件") + @Operation(summary = "Download replacement word file") @RequiresPermissions("sys:role:normal") public ResponseEntity downloadFile(@PathVariable String fileId) { CorrectWordFileVO vo = correctWordFileService.getFileContent(fileId); @@ -96,7 +96,7 @@ public class CorrectWordController { } @DeleteMapping("/file/{fileId}") - @Operation(summary = "删除替换词文件") + @Operation(summary = "Delete replacement word file") @RequiresPermissions("sys:role:normal") public Result deleteFile(@PathVariable String fileId) { correctWordFileService.deleteFile(fileId); @@ -104,7 +104,7 @@ public class CorrectWordController { } @PostMapping("/file/batch-delete") - @Operation(summary = "批量删除替换词文件") + @Operation(summary = "Batch delete replacement word files") @RequiresPermissions("sys:role:normal") public Result batchDeleteFiles(@RequestBody List fileIds) { if (fileIds == null || fileIds.isEmpty()) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/correctword/dto/CorrectWordFileCreateDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/correctword/dto/CorrectWordFileCreateDTO.java index 9941abda4..4cee652c2 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/correctword/dto/CorrectWordFileCreateDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/correctword/dto/CorrectWordFileCreateDTO.java @@ -8,17 +8,17 @@ import jakarta.validation.constraints.NotEmpty; import lombok.Data; @Data -@Schema(description = "创建替换词文件DTO") +@Schema(description = "Create replacement word file DTO") public class CorrectWordFileCreateDTO { - @NotBlank(message = "文件名不能为空") - @Schema(description = "文件名") + @NotBlank(message = "File name cannot be empty") + @Schema(description = "File name") private String fileName; - @NotEmpty(message = "替换词内容不能为空") - @Schema(description = "替换词内容,每条格式:原词|替换词") + @NotEmpty(message = "Replacement word content cannot be empty") + @Schema(description = "Replacement word content, format per line: original|replacement") private List content; - @Schema(description = "文件大小(字节),不能超过1MB") + @Schema(description = "File size (bytes), must not exceed 1MB") private Long fileSize; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/correctword/entity/CorrectWordFileEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/correctword/entity/CorrectWordFileEntity.java index 1d32623e8..0fb3ccd3e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/correctword/entity/CorrectWordFileEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/correctword/entity/CorrectWordFileEntity.java @@ -11,31 +11,31 @@ import lombok.Data; @Data @TableName("ai_agent_correct_word_file") -@Schema(description = "智能体替换词文件") +@Schema(description = "Agent replacement word file") public class CorrectWordFileEntity { @TableId(type = IdType.ASSIGN_UUID) - @Schema(description = "替换词文件ID") + @Schema(description = "Replacement word file ID") private String id; - @Schema(description = "原始文件名") + @Schema(description = "Original filename") private String fileName; - @Schema(description = "替换词数量") + @Schema(description = "Replacement word count") private Integer wordCount; - @Schema(description = "文件原始内容(用于下载)") + @Schema(description = "Original file content (for download)") private String content; - @Schema(description = "创建者") + @Schema(description = "Creator") private Long creator; - @Schema(description = "创建时间") + @Schema(description = "Creation Time") private Date createdAt; - @Schema(description = "更新者") + @Schema(description = "Updated by") private Long updater; - @Schema(description = "更新时间") + @Schema(description = "Update time") private Date updatedAt; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/correctword/entity/CorrectWordItemEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/correctword/entity/CorrectWordItemEntity.java index 42b9f188a..585b0ff74 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/correctword/entity/CorrectWordItemEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/correctword/entity/CorrectWordItemEntity.java @@ -9,19 +9,19 @@ import lombok.Data; @Data @TableName("ai_agent_correct_word_item") -@Schema(description = "替换词词条") +@Schema(description = "Replacement word entries") public class CorrectWordItemEntity { @TableId(type = IdType.ASSIGN_UUID) - @Schema(description = "词条ID") + @Schema(description = "Entry ID") private String id; - @Schema(description = "所属文件ID") + @Schema(description = "Associated file ID") private String fileId; - @Schema(description = "原词") + @Schema(description = "Original Word") private String sourceWord; - @Schema(description = "替换词") + @Schema(description = "Replacement word") private String targetWord; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/correctword/service/CorrectWordFileService.java b/main/manager-api/src/main/java/xiaozhi/modules/correctword/service/CorrectWordFileService.java index 31e29c8e5..dd1323b34 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/correctword/service/CorrectWordFileService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/correctword/service/CorrectWordFileService.java @@ -11,86 +11,86 @@ import xiaozhi.modules.correctword.vo.CorrectWordSimpleVO; public interface CorrectWordFileService { /** - * 创建替换词文件 + * Create replacement word file * - * @param dto 创建参数 - * @return 文件VO + * @param dto creation parameters + * @return File VO */ CorrectWordFileVO createFile(CorrectWordFileCreateDTO dto); /** - * 修改替换词文件(全量替换词条) + * Update replacement word file (full replacement) * - * @param fileId 文件ID - * @param dto 修改参数 + * @param fileId File ID + * @param dto Modification parameters */ void updateFile(String fileId, CorrectWordFileCreateDTO dto); /** - * 获取当前用户的替换词文件列表 + * Get the list of replacement-word files for the current user * - * @param params 分页参数 - * @return 分页数据 + * @param params Pagination parameters + * @return Paged data */ PageData listFiles(Map params); /** - * 获取当前用户的替换词文件列表(不分页,用于下拉选择) + * Get current user's replacement word file list (no pagination, for dropdown selection) * - * @return 文件列表 + * @return File list */ List listAllFiles(); /** - * 获取文件原始内容(用于下载) + * Get raw file content (for download) * - * @param fileId 文件ID - * @return 文件实体 + * @param fileId File ID + * @return File entity */ CorrectWordFileVO getFileContent(String fileId); /** - * 删除替换词文件及其所有词条和关联记录 + * Delete the replacement word file and all its entries and associated records * - * @param fileId 文件ID + * @param fileId File ID */ void deleteFile(String fileId); /** - * 删除智能体关联的替换词文件关联记录(不删文件本身) + * Delete replacement word file association records for Agent (do not delete files) * - * @param agentId 智能体ID + * @param agentId Agent ID */ void deleteMappingsByAgentId(String agentId); /** - * 获取智能体的所有替换词条(精简版,供设备端使用) + * Get all replacement terms for the Agent (simplified for device use) * - * @param agentId 智能体ID - * @return 替换词列表 + * @param agentId Agent ID + * @return List of replacement words */ List getAllItemsByAgentId(String agentId); /** - * 获取智能体关联的替换词文件ID列表 + * Get list of replacement word file IDs associated with the Agent * - * @param agentId 智能体ID - * @return 文件ID列表 + * @param agentId Agent ID + * @return List of file IDs */ List getAgentCorrectWordFileIds(String agentId); /** - * 保存智能体关联的替换词文件(全量替换) + * Save replacement words file associated with Agent (full replacement) * - * @param agentId 智能体ID - * @param fileIds 文件ID列表 + * @param agentId Agent ID + * @param fileIds List of file IDs */ void saveAgentCorrectWords(String agentId, List fileIds); /** - * 批量删除替换词文件 + * Batch delete replacement word files * - * @param fileIds 文件ID列表 + * @param fileIds List of file IDs */ void batchDeleteFiles(List fileIds); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/correctword/service/impl/CorrectWordFileServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/correctword/service/impl/CorrectWordFileServiceImpl.java index b35a0e094..0dd7d2bc3 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/correctword/service/impl/CorrectWordFileServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/correctword/service/impl/CorrectWordFileServiceImpl.java @@ -43,12 +43,12 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl 1024 * 1024) { throw new RenException(ErrorCode.FILE_SIZE_OVER_LIMIT); } - // 校验文件名是否重复 + // Validate if filename is duplicate Long userId = SecurityUser.getUserId(); LambdaQueryWrapper nameWrapper = new LambdaQueryWrapper<>(); nameWrapper.eq(CorrectWordFileEntity::getCreator, userId) @@ -59,7 +59,7 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl items = parseContent(dto.getContent()); - // 保存文件记录 + // Save file records CorrectWordFileEntity fileEntity = new CorrectWordFileEntity(); fileEntity.setFileName(dto.getFileName()); fileEntity.setWordCount(items.size()); @@ -68,7 +68,7 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl nameWrapper = new LambdaQueryWrapper<>(); nameWrapper.eq(CorrectWordFileEntity::getCreator, userId) .eq(CorrectWordFileEntity::getFileName, dto.getFileName()) .ne(CorrectWordFileEntity::getId, fileId); if (correctWordFileDao.selectCount(nameWrapper) > 0) { - throw new RenException("文件名已存在:" + dto.getFileName()); + throw new RenException("File name already exists:" + dto.getFileName()); } - // 先删除旧词条 + // Delete old entries first LambdaQueryWrapper deleteWrapper = new LambdaQueryWrapper<>(); deleteWrapper.eq(CorrectWordItemEntity::getFileId, fileId); correctWordItemDao.delete(deleteWrapper); - // 解析新词条并批量保存 + // Parse new entries and batch save List items = parseContent(dto.getContent()); if (!items.isEmpty()) { for (CorrectWordItemEntity item : items) { @@ -112,7 +112,7 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl wrapper = new LambdaQueryWrapper<>(); wrapper.eq(CorrectWordItemEntity::getFileId, fileId); correctWordItemDao.delete(wrapper); - // 删除文件 + // Delete File correctWordFileDao.deleteById(fileId); } @@ -173,7 +173,7 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl getAllItemsByAgentId(String agentId) { - // 通过关联表获取文件ID列表 + // Get file ID list via association table List mappings = agentCorrectWordMappingDao.selectByAgentId(agentId); if (mappings == null || mappings.isEmpty()) { return new ArrayList<>(); @@ -182,7 +182,7 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl wrapper = new LambdaQueryWrapper<>(); wrapper.in(CorrectWordItemEntity::getFileId, fileIds); List entities = correctWordItemDao.selectList(wrapper); @@ -203,14 +203,14 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl fileIds) { - // 先删除旧的关联记录 + // Delete old association records first agentCorrectWordMappingDao.deleteByAgentId(agentId); if (fileIds == null || fileIds.isEmpty()) { return; } - // 批量插入新的关联记录 + // Batch insert new association records Long userId = SecurityUser.getUserId(); Date now = new Date(); List mappings = new ArrayList<>(); @@ -242,7 +242,7 @@ public class CorrectWordFileServiceImpl extends BaseServiceImpl parseContent(List lines) { List items = new ArrayList<>(); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/correctword/vo/CorrectWordFileVO.java b/main/manager-api/src/main/java/xiaozhi/modules/correctword/vo/CorrectWordFileVO.java index a881b8d5c..9639ec5bf 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/correctword/vo/CorrectWordFileVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/correctword/vo/CorrectWordFileVO.java @@ -7,24 +7,24 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data -@Schema(description = "替换词文件列表VO") +@Schema(description = "Replacement word file list VO") public class CorrectWordFileVO { - @Schema(description = "替换词文件ID") + @Schema(description = "Replacement word file ID") private String id; - @Schema(description = "原始文件名") + @Schema(description = "Original filename") private String fileName; - @Schema(description = "替换词数量") + @Schema(description = "Replacement word count") private Integer wordCount; - @Schema(description = "替换词内容,每行一条") + @Schema(description = "Replacement word content, one per line") private List content; - @Schema(description = "创建时间") + @Schema(description = "Creation Time") private Date createdAt; - @Schema(description = "更新时间") + @Schema(description = "Update time") private Date updatedAt; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/correctword/vo/CorrectWordSimpleVO.java b/main/manager-api/src/main/java/xiaozhi/modules/correctword/vo/CorrectWordSimpleVO.java index 289b8a4ef..7ee378581 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/correctword/vo/CorrectWordSimpleVO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/correctword/vo/CorrectWordSimpleVO.java @@ -4,12 +4,12 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data -@Schema(description = "替换词精简VO(设备端使用)") +@Schema(description = "Simplified replacement-word VO (device-side)") public class CorrectWordSimpleVO { - @Schema(description = "原词") + @Schema(description = "Original Word") private String sourceWord; - @Schema(description = "替换词") + @Schema(description = "Replacement word") private String targetWord; } 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 f8a9b7025..6055e3365 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 @@ -37,7 +37,7 @@ import xiaozhi.modules.device.vo.UserShowDeviceListVO; import xiaozhi.modules.security.user.SecurityUser; import xiaozhi.modules.sys.service.SysParamsService; -@Tag(name = "设备管理") +@Tag(name = "Device Management") @RestController @RequestMapping("/device") public class DeviceController { @@ -55,7 +55,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); @@ -63,13 +63,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 6-digit verification code String code; String key; String existsMac = null; @@ -84,7 +84,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(); @@ -93,18 +93,18 @@ public class DeviceController { } @PostMapping("/bind/{agentId}") - @Operation(summary = "设备在线接口") + @Operation(summary = "Device online API") @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("Forward request failed: " + e.getMessage()); } } @PostMapping("/unbind") - @Operation(summary = "解绑设备") + @Operation(summary = "Unbind device") @RequiresPermissions("sys:role:normal") public Result unbindDevice(@RequestBody DeviceUnBindDTO unDeviveBind) { UserDetail user = SecurityUser.getUser(); @@ -113,16 +113,16 @@ public class DeviceController { } @PutMapping("/update/{id}") - @Operation(summary = "更新设备信息") + @Operation(summary = "Update device info") @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 not found"); } UserDetail user = SecurityUser.getUser(); if (!entity.getUserId().equals(user.getId())) { - return new Result().error("设备不存在"); + return new Result().error("Device not found"); } BeanUtils.copyProperties(deviceUpdateDTO, entity); if (!deviceService.updateById(entity)) { @@ -132,7 +132,7 @@ public class DeviceController { } @PostMapping("/manual-add") - @Operation(summary = "手动添加设备") + @Operation(summary = "Add device manually") @RequiresPermissions("sys:role:normal") public Result manualAddDevice(@RequestBody @Valid DeviceManualAddDTO dto) { UserDetail user = SecurityUser.getUser(); @@ -141,7 +141,7 @@ public class DeviceController { } @PostMapping("/tools/list/{deviceId}") - @Operation(summary = "获取设备工具列表") + @Operation(summary = "Get device tool list") @RequiresPermissions("sys:role:normal") public Result getDeviceTools(@PathVariable String deviceId) { Object toolsData = deviceService.getDeviceTools(deviceId); @@ -153,7 +153,7 @@ public class DeviceController { } @PostMapping("/tools/call/{deviceId}") - @Operation(summary = "调用设备工具") + @Operation(summary = "Invoke Device Tool") @RequiresPermissions("sys:role:normal") public Result callDeviceTool(@PathVariable String deviceId, @Valid @RequestBody DeviceToolsCallReqDTO request) { @@ -171,44 +171,44 @@ public class DeviceController { } @GetMapping("/address-book/{macAddress}") - @Operation(summary = "获取设备通讯录") + @Operation(summary = "Get device contacts") @RequiresPermissions("sys:role:normal") public Result getAddressBook(@PathVariable String macAddress) { return new Result().ok(deviceAddressBookService.getAddressBookList(macAddress)); } @GetMapping("/address-book/call") - @Operation(summary = "根据昵称发起呼叫") + @Operation(summary = "Initiate call by nickname") public Result> callByNickname(String callerMac, String nickname, @RequestParam(required = false, defaultValue = "false") boolean answer) { Map result = deviceAddressBookService.callByNickname(callerMac, nickname, answer); if (result == null) { - return new Result>().error("未找到对应设备"); + return new Result>().error("Corresponding device not found"); } return new Result>().ok(result); } @PutMapping("/address-book/alias") - @Operation(summary = "更新设备通讯录别名") + @Operation(summary = "Update device contact alias") @RequiresPermissions("sys:role:normal") public Result updateAlias(@Valid @RequestBody DeviceAddressBookAliasDTO dto) { UserDetail user = SecurityUser.getUser(); DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(dto.getMacAddress()); if (callerDevice == null || !callerDevice.getUserId().equals(user.getId())) { - return new Result().error("无权限操作该设备"); + return new Result().error("No permission to operate this device"); } deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), dto.getAlias(), null); return new Result(); } @PutMapping("/address-book/permission") - @Operation(summary = "更新设备通讯录权限") + @Operation(summary = "Update device contact permissions") @RequiresPermissions("sys:role:normal") public Result updatePermission(@Valid @RequestBody DeviceAddressBookPermissionDTO dto) { UserDetail user = SecurityUser.getUser(); DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(dto.getMacAddress()); if (callerDevice == null || !callerDevice.getUserId().equals(user.getId())) { - return new Result().error("无权限操作该设备"); + return new Result().error("No permission to operate this device"); } deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), null, dto.getHasPermission()); return new Result(); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceAddressBookDao.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceAddressBookDao.java index fc7d6428b..43686838e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceAddressBookDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dao/DeviceAddressBookDao.java @@ -13,27 +13,27 @@ import xiaozhi.modules.device.entity.DeviceAddressBookEntity; public interface DeviceAddressBookDao extends BaseMapper { /** - * 新增设备通讯录记录 + * Add device contact record */ int insertAddressBook(DeviceAddressBookEntity entity); /** - * 获取设备通讯录列表 + * Get device contacts list */ List getAddressBookList(@Param("macAddress") String macAddress); /** - * 更新别名 + * Update alias */ void updateAlias(@Param("macAddress") String macAddress, @Param("targetMac") String targetMac, @Param("alias") String alias); /** - * 更新权限 + * Update permissions */ void updatePermission(@Param("macAddress") String macAddress, @Param("targetMac") String targetMac, @Param("hasPermission") Boolean hasPermission); /** - * 批量删除设备相关的通讯录记录 + * Batch delete contact records associated with devices */ void deleteByMacAddresses(@Param("macAddresses") List macAddresses); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceAddressBookAliasDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceAddressBookAliasDTO.java index ef1ffe0ba..7354f49e9 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceAddressBookAliasDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceAddressBookAliasDTO.java @@ -5,17 +5,17 @@ import jakarta.validation.constraints.NotBlank; import lombok.Data; @Data -@Schema(description = "更新设备通讯录别名") +@Schema(description = "Update device contact alias") public class DeviceAddressBookAliasDTO { - @NotBlank(message = "MAC地址不能为空") - @Schema(description = "本设备MAC地址") + @NotBlank(message = "MAC address cannot be empty") + @Schema(description = "This device MAC address") private String macAddress; - @NotBlank(message = "目标MAC地址不能为空") - @Schema(description = "对方设备MAC地址") + @NotBlank(message = "Target MAC address cannot be empty") + @Schema(description = "Peer device MAC address") private String targetMac; - @Schema(description = "我对对方的称呼") + @Schema(description = "My name for the other party") private String alias; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceAddressBookPermissionDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceAddressBookPermissionDTO.java index 945f1085e..6a3346d30 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceAddressBookPermissionDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceAddressBookPermissionDTO.java @@ -5,17 +5,17 @@ import jakarta.validation.constraints.NotBlank; import lombok.Data; @Data -@Schema(description = "更新设备通讯录权限") +@Schema(description = "Update device contact permissions") public class DeviceAddressBookPermissionDTO { - @NotBlank(message = "MAC地址不能为空") - @Schema(description = "本设备MAC地址") + @NotBlank(message = "MAC address cannot be empty") + @Schema(description = "This device MAC address") private String macAddress; - @NotBlank(message = "目标MAC地址不能为空") - @Schema(description = "对方设备MAC地址") + @NotBlank(message = "Target MAC address cannot be empty") + @Schema(description = "Peer device MAC address") private String targetMac; - @Schema(description = "是否有权限呼叫") + @Schema(description = "Has call permission") private Boolean hasPermission; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/entity/DeviceAddressBookEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/device/entity/DeviceAddressBookEntity.java index 7c8bf007c..f86c1f6b5 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/entity/DeviceAddressBookEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/entity/DeviceAddressBookEntity.java @@ -15,35 +15,35 @@ import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = false) @TableName("ai_device_address_book") -@Schema(description = "设备通讯录") +@Schema(description = "Device contacts") public class DeviceAddressBookEntity { @TableId(type = IdType.INPUT) - @Schema(description = "本设备MAC地址") + @Schema(description = "This device MAC address") private String macAddress; - @Schema(description = "对方设备MAC地址") + @Schema(description = "Peer device MAC address") private String targetMac; - @Schema(description = "我对对方的称呼") + @Schema(description = "My name for the other party") private String alias; - @Schema(description = "是否有权限呼叫") + @Schema(description = "Has call permission") private Boolean hasPermission; @TableField(fill = FieldFill.INSERT) - @Schema(description = "创建人") + @Schema(description = "Creator") private Long creator; @TableField(fill = FieldFill.INSERT) - @Schema(description = "创建时间") + @Schema(description = "Creation Time") private Date createDate; @TableField(fill = FieldFill.INSERT_UPDATE) - @Schema(description = "更新人") + @Schema(description = "Updated by") private Long updater; @TableField(fill = FieldFill.INSERT_UPDATE) - @Schema(description = "更新时间") + @Schema(description = "Update time") private Date updateDate; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceAddressBookService.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceAddressBookService.java index d0b383940..9555fda6b 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceAddressBookService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceAddressBookService.java @@ -8,45 +8,45 @@ import xiaozhi.modules.device.entity.DeviceAddressBookEntity; public interface DeviceAddressBookService { /** - * 获取设备通讯录列表 + * Get device contacts list */ List getAddressBookList(String macAddress); /** - * 获取所有设备的通讯录(全局缓存用) + * Get contacts for all devices (for global cache) */ Map> getAllAddressBooks(); /** - * 更新别名 + * Update alias */ void updateAlias(String macAddress, String targetMac, String alias); /** - * 更新权限 + * Update permissions */ void updatePermission(String macAddress, String targetMac, Boolean hasPermission); /** - * 添加或更新通讯录记录 + * Add or update contact record */ void saveOrUpdate(String macAddress, String targetMac, String alias, Boolean hasPermission); /** - * 刷新通讯录缓存 + * Refresh contacts cache */ void refreshCache(); /** - * 根据昵称发起呼叫 - * @param callerMac 主叫方MAC地址 - * @param nickname 被叫方昵称 - * @param isAnswer 是否为接听模式(跳过权限检查) + * Initiate call by nickname + * @param callerMac Caller MAC address + * @param nickname Callee nickname + * @param isAnswer Whether in answer mode (skip permission check) */ Map callByNickname(String callerMac, String nickname, boolean isAnswer); /** - * 批量删除设备相关的通讯录记录 + * Batch delete contact records associated with devices */ void deleteByMacAddresses(List macAddresses); } \ 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 b663ceb60..1c02e5ddb 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,126 +15,126 @@ import xiaozhi.modules.device.vo.UserShowDeviceListVO; public interface DeviceService extends BaseService { /** - * 获取设备在线数据 + * Get device online data */ String getDeviceOnlineData(String agentId); /** - * 检查设备是否激活 + * Check if device is active */ DeviceReportRespDTO checkDeviceActive(String macAddress, String clientId, DeviceReportReqDTO deviceReport); /** - * 获取用户指定智能体的设备列表, + * Retrieve device list for user-specified Agent, */ List getUserDevices(Long userId, String agentId); /** - * 获取用户指定智能体的设备列表(带时区处理), + * Get device list for user-specified agent (with timezone handling), */ List getUserDeviceList(Long userId, String agentId); /** - * 解绑设备 + * Unbind device */ void unbindDevice(Long userId, String deviceId); /** - * 设备激活 + * Device Activation */ Boolean deviceActivation(String agentId, String activationCode); /** - * 删除此用户的所有设备 + * Delete all devices for this user * - * @param userId 用户id + * @param userId User ID */ void deleteByUserId(Long userId); /** - * 删除指定智能体关联的所有设备 + * Delete all devices associated with the specified Agent * - * @param agentId 智能体id + * @param agentId Agent ID */ void deleteByAgentId(String agentId); /** - * 获取指定用户的设备数量 + * Get device count for specified user * - * @param userId 用户id - * @return 设备数量 + * @param userId User ID + * @return Device count */ Long selectCountByUserId(Long userId); /** - * 分页获取全部设备信息 + * Paginate to retrieve all device information * - * @param dto 分页查找参数 - * @return 用户列表分页数据 + * @param dto Pagination search parameters + * @return Paginated user list data */ PageData page(DevicePageUserDTO dto); /** - * 根据MAC地址获取设备信息 + * Get device info by MAC address * - * @param macAddress MAC地址 - * @return 设备信息 + * @param macAddress MAC address + * @return Device info */ DeviceEntity getDeviceByMacAddress(String macAddress); /** - * 根据设备ID获取激活码 + * Get activation code by device ID * - * @param deviceId 设备ID - * @return 激活码 + * @param deviceId Device ID + * @return activation code */ String geCodeByDeviceId(String deviceId); /** - * 获取这个智能体设备理的最近的最后连接时间 + * Get the last connection time for this agent device * - * @param agentId 智能体id - * @return 返回设备最近的最后连接时间 + * @param agentId Agent ID + * @return Returns the device's most recent last connection time */ Date getLatestLastConnectionTime(String agentId); /** - * 手动添加设备 + * Add device manually */ void manualAddDevice(Long userId, DeviceManualAddDTO dto); /** - * 更新设备连接信息 + * Update device connection info */ void updateDeviceConnectionInfo(String agentId, String deviceId, String appVersion); /** - * 生成WebSocket认证token + * Generate WebSocket authentication token * - * @param clientId 客户端ID - * @param username 用户名(通常为deviceId) - * @return 认证token字符串 - * @throws Exception 生成token时的异常 + * @param clientId Client ID + * @param username Username (typically deviceId) + * @return Authentication token string + * @throws Exception Exception during token generation */ String generateWebSocketToken(String clientId, String username) throws Exception; /** - * 根据MAC地址搜索设备 + * Search device 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 device tool list */ Object getDeviceTools(String deviceId); /** - * 调用设备工具 + * Invoke Device Tool */ Object callDeviceTool(String deviceId, String toolName, Map arguments); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImpl.java index ff2e43176..1f0cd913a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImpl.java @@ -59,27 +59,27 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService { Map> allBooks = getAllAddressBooks(); if (isAnswer) { - return postToMqtt("/api/call/accept", Map.of("mac", callerMac), "接听"); + return postToMqtt("/api/call/accept", Map.of("mac", callerMac), "Answer"); } - // 主动呼叫模式 + // Active call mode Map callerBook = allBooks.get(callerMac.toLowerCase()); if (callerBook == null) { - return errorResult("未找到备注为'" + nickname + "'的设备"); + return errorResult("Device with nickname '" + nickname + "' not found"); } String targetMacWithPerm = callerBook.get(nickname); if (targetMacWithPerm == null) { - return errorResult("未找到备注为'" + nickname + "'的设备"); + return errorResult("Device with nickname '" + nickname + "' not found"); } String[] parts = targetMacWithPerm.split("\\|"); String targetMac = parts[0]; boolean hasPermission = parts.length > 1 && "1".equals(parts[1]); if (!hasPermission) { - return errorResult("呼叫失败,您没有权限呼叫该设备"); + return errorResult("Call failed: you do not have permission to call this device"); } - // 获取目标设备如何称呼主叫方 + // Get how the target device addresses the caller Map targetBook = allBooks.get(targetMac.toLowerCase()); String callerNickname = null; if (targetBook != null) { @@ -94,7 +94,7 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService { return postToMqtt("/api/call/request", Map.of("caller_mac", callerMac, "target_mac", targetMac, "caller_nickname", callerNickname), - "呼叫"); + "Call"); } @Override @@ -109,20 +109,20 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService { String alias = entity.getAlias(); Boolean hasPermission = entity.getHasPermission(); - // 构建正向映射: A对B的映射 nickname -> macB|permission + // Build forward mapping: A-to-B mapping nickname -> macB|permission if (alias != null && !alias.isEmpty()) { result.computeIfAbsent(macA, k -> new HashMap<>()); String permStr = (hasPermission != null && hasPermission) ? "1" : "0"; result.get(macA).put(alias, macB + "|" + permStr); } - // 构建反向记录用于查找B对A的称呼 + // Build reverse records to look up how B refers to A if (alias != null && !alias.isEmpty()) { reverseMap.put(macB + ":" + macA, alias); } } - // 构建反向映射: B对A的映射 macA -> nickname + // Build reverse mapping: B-to-A mapping macA -> nickname for (DeviceAddressBookEntity entity : allRecords) { String macA = entity.getMacAddress().toLowerCase(); String macB = entity.getTargetMac().toLowerCase(); @@ -159,11 +159,11 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService { DeviceAddressBookEntity entity = new DeviceAddressBookEntity(); entity.setMacAddress(macAddress); entity.setTargetMac(targetMac); - // 如果 alias 为空,就默认使用设备名称 + // If alias is empty, default to device name if (StringUtils.isBlank(alias)) { alias = deviceService.getDeviceByMacAddress(targetMac).getAlias(); } - // 检查重名 + // Check for duplicates alias = generateUniqueAlias(macAddress, targetMac, alias); entity.setAlias(alias); entity.setHasPermission(hasPermission); @@ -204,7 +204,7 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService { if (StringUtils.isBlank(mqttGatewayUrl) || "null".equals(mqttGatewayUrl) || MqttGatewayAuthorization.isMissingSignatureKey(mqttSignatureKey)) { - result.put("message", action + "失败,网关配置缺失"); + result.put("message", action + "Failed, gateway config missing"); return result; } @@ -224,7 +224,7 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService { } return result; } catch (Exception e) { - result.put("message", action + "失败,请稍后再试"); + result.put("message", action + "Failed, please try again later"); return result; } } @@ -234,7 +234,7 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService { return mac; } String lastTwo = mac.substring(mac.length() - 2); - return "尾号为" + lastTwo + "的设备"; + return "Device ending in " + lastTwo; } private String generateUniqueAlias(String macAddress, String targetMac, String alias) { 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 11e851ac8..b2975bf2e 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 @@ -342,7 +342,7 @@ public class DeviceServiceImpl extends BaseServiceImpl wrapper.eq("id", deviceId); baseDao.delete(wrapper); - // 删除设备相关的通讯录权限记录 + // Delete contact permissions related to the device deviceAddressBookService.deleteByMacAddresses(Collections.singletonList(macAddress)); } @@ -362,17 +362,17 @@ public class DeviceServiceImpl extends BaseServiceImpl @Override public void deleteByAgentId(String agentId) { - // 先查询该智能体下的所有设备,获取mac地址用于删除通讯录记录 + // Query all devices under this Agent first to get MAC addresses for deleting contact records QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("agent_id", agentId); List devices = baseDao.selectList(queryWrapper); - // 删除设备 + // Delete device UpdateWrapper wrapper = new UpdateWrapper<>(); wrapper.eq("agent_id", agentId); baseDao.delete(wrapper); - // 批量删除这些设备相关的所有通讯录权限记录 + // Batch delete all contact permissions related to these devices if (!devices.isEmpty()) { List macAddresses = devices.stream() .map(DeviceEntity::getMacAddress) 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 b00a16865..e4f75637e 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 @@ -8,43 +8,43 @@ 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 = "Bind username") private String bindUserName; - @Schema(description = "设备型号") + @Schema(description = "Device Model") private String deviceType; - @Schema(description = "设备型号(board)") + @Schema(description = "Device model (board)") private String board; - @Schema(description = "设备唯一标识符") + @Schema(description = "Device unique identifier") private String id; - @Schema(description = "mac地址") + @Schema(description = "MAC Address") private String macAddress; - @Schema(description = "设备别名") + @Schema(description = "Device alias") private String alias; - @Schema(description = "自动更新开关(0关闭/1开启)") + @Schema(description = "Auto-update switch (0: off / 1: on)") private Integer autoUpdate; - @Schema(description = "最近对话时间") + @Schema(description = "Last conversation time") private String recentChatTime; - @Schema(description = "最后连接时间戳(毫秒)", type = "string", example = "1783689702000") + @Schema(description = "Last connection timestamp (ms)", type = "string", example = "1783689702000") private Long lastConnectedAtTimestamp; - @Schema(description = "绑定时间戳(毫秒)", type = "string", example = "1783689702000") + @Schema(description = "Bind timestamp (ms)", type = "string", example = "1783689702000") private Long createDateTimestamp; - @Schema(description = "绑定时间(兼容字段,请使用 createDateTimestamp)", deprecated = true) + @Schema(description = "Binding time (legacy field, use createDateTimestamp)", deprecated = true) @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "UTC") private Date createDate; 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 4aa64b0c7..997d1e700 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; /** - * 验证当前用户是否有权限操作指定知识库 + * Verify if current user has permission to operate specified knowledge base * - * @param datasetId 知识库ID + * @param datasetId Knowledge base ID */ private void validateKnowledgeBasePermission(String datasetId) { - // 获取当前登录用户ID + // Get current logged-in user ID Long currentUserId = SecurityUser.getUserId(); - // 获取知识库信息 + // Get knowledge base info KnowledgeBaseDTO knowledgeBase = knowledgeBaseService.getByDatasetId(datasetId); - // 检查权限:用户只能操作自己创建的知识库 + // Check permissions: users can only manage their own knowledge bases if (knowledgeBase.getCreator() == null || !knowledgeBase.getCreator().equals(currentUserId)) { throw new RenException(ErrorCode.NO_PERMISSION); } } @GetMapping("/documents") - @Operation(summary = "分页查询文档列表") + @Operation(summary = "Paginated query for document list") @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); - // 组装参数 + // Assembly 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 = "Query document list 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); - // 组装参数 + // Assembly 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 document to 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 = "Batch delete documents") @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 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,28 +141,28 @@ public class KnowledgeFilesController { } @PostMapping("/chunks") - @Operation(summary = "解析文档(切块)") + @Operation(summary = "Parse document (chunking)") @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("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, document may be processing"); } } @GetMapping("/documents/{document_id}/chunks") - @Operation(summary = "列出指定文档的切片") + @Operation(summary = "List slices of specified document") @RequiresPermissions("sys:role:normal") public Result listChunks( @PathVariable("dataset_id") String datasetId, @@ -172,10 +172,10 @@ public class KnowledgeFilesController { @RequestParam(required = false) String keywords, @RequestParam(required = false) String id) { - // 验证权限 (内部已包含知识库存在性校验与归属权校验) + // Verify permissions (includes internal knowledge base existence and ownership checks) validateKnowledgeBasePermission(datasetId); - // 构建请求对象 + // Build request object ChunkDTO.ListReq req = ChunkDTO.ListReq.builder() .page(page) .pageSize(pageSize) @@ -183,27 +183,27 @@ public class KnowledgeFilesController { .id(id) .build(); - // 调用服务层获取强类型切片列表 + // Call service layer to get strongly-typed slice list ChunkDTO.ListVO result = knowledgeFilesService.listChunks(datasetId, documentId, req); return new Result().ok(result); } @PostMapping("/retrieval-test") - @Operation(summary = "召回测试") + @Operation(summary = "Recall 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 + // Business logic fallback: If knowledge base ID is not specified, set it to the datasetId in the current path if (req.getDatasetIds() == null || req.getDatasetIds().isEmpty()) { req.setDatasetIds(java.util.Arrays.asList(datasetId)); } - // [Reinforce] 强管控分页参数,防止 RAGFlow 端出现 Negative Slicing 报错 + // [Reinforce] Enforce pagination parameters to prevent Negative Slicing errors on the RAGFlow side if (req.getPage() == null || req.getPage() < 1) { req.setPage(1); } @@ -211,13 +211,13 @@ public class KnowledgeFilesController { req.setPageSize(100); } - // 调用检索服务,返回强类型聚合对象 + // Call retrieval service and return strongly-typed aggregate object RetrievalDTO.ResultVO result = knowledgeFilesService.retrievalTest(req); return new Result().ok(result); } /** - * 解析JSON字符串为Map对象 + * Parse JSON string into Map object */ private Map parseJsonMap(String jsonString) { try { @@ -225,7 +225,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/dto/KnowledgeBaseDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeBaseDTO.java index 5b7722491..e8e5bfe54 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,66 +8,66 @@ import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @Data -@Schema(description = "知识库知识库") +@Schema(description = "Knowledge base") public class KnowledgeBaseDTO implements Serializable { @Serial private static final long serialVersionUID = 1L; - @Schema(description = "唯一标识") + @Schema(description = "Unique identifier") private String id; - @Schema(description = "知识库ID") + @Schema(description = "Knowledge base ID") private String datasetId; - @Schema(description = "RAG模型配置ID") + @Schema(description = "RAG model config ID") private String ragModelId; - @Schema(description = "知识库名称") + @Schema(description = "Knowledge base name") private String name; - @Schema(description = "知识库头像(Base64)") + @Schema(description = "Knowledge base avatar (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 settings: me/team") private String permission; - @Schema(description = "分块方法") + @Schema(description = "Chunking Method") private String chunkMethod; - @Schema(description = "解析器配置(JSON String)") + @Schema(description = "Parser config (JSON String)") private String parserConfig; - @Schema(description = "分块总数") + @Schema(description = "Total Chunks") private Long chunkCount; - @Schema(description = "总Token数") + @Schema(description = "Total tokens") private Long tokenNum; - @Schema(description = "状态(0:禁用 1:启用)") + @Schema(description = "Status (0: disabled, 1: enabled)") private Integer status; - @Schema(description = "创建者") + @Schema(description = "Creator") private Long creator; - @Schema(description = "创建时间") + @Schema(description = "Creation Time") private Date createdAt; - @Schema(description = "更新者") + @Schema(description = "Updated by") private Long updater; - @Schema(description = "更新时间") + @Schema(description = "Update time") private Date updatedAt; - @Schema(description = "文档数量") + @Schema(description = "Document count") private Integer documentCount; - @Schema(description = "异常提示") + @Schema(description = "Error message") private String errorMessage; } \ No newline at end of file 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 ae6f913a3..9de373eb1 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 has been upgraded to use {@link RAGFlowClient} for unified HTTP communication. + * Resolved issues in legacy code: missing Timeout and scattered Error Handling. *

*/ @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 Client with a default timeout of 30s, extendable via 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 timeout config, using default 30s"); } } this.client = new RAGFlowClient(baseUrl, apiKey, timeout); - log.info("RAGFlow适配器初始化完成,Client已就绪"); + log.info("RAGFlow adapter initialized, Client 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("You")) { throw new RenException(ErrorCode.RAG_API_ERROR_API_KEY_INVALID); } @@ -109,7 +109,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } /** - * 辅助方法:支持多种键名获取配置(兼容 camelCase 和 snake_case) + * Helper method: retrieve config using multiple key names (supports camelCase and snake_case) */ private String getConfigValue(Map config, String snakeKey, String camelKey) { if (config.containsKey(snakeKey)) { @@ -122,15 +122,15 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } /** - * 辅助方法:确保 Client 已初始化 + * Helper method: ensure Client is initialized */ private RAGFlowClient getClient() { if (this.client == null) { - // 尝试重新初始化 + // Attempt re-initialization 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 not initialized"); // should throw a RuntimeException } } 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] Fetching document list: datasetId={} ===", datasetId); - // 使用 Jackson 将 DTO 转为 Map 作为查询参数 + // Use Jackson to convert DTO to Map as query parameters Map params = objectMapper.convertValue(req, new TypeReference>() { }); @@ -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 get 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] Fetch document details: datasetId={}, documentId={} ===", datasetId, documentId); DocumentDTO.ListReq req = DocumentDTO.ListReq.builder() .id(documentId) .page(1) @@ -187,7 +187,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } return null; } catch (Exception e) { - log.error("获取文档详情失败: documentId={}", documentId, e); + log.error("Failed to get document details: documentId={}", documentId, e); throw convertToRenException(e); } } @@ -197,7 +197,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { String datasetId = req.getDatasetId(); MultipartFile file = req.getFile(); try { - log.info("=== [RAGFlow] 上传文档: datasetId={} ===", datasetId); + log.info("=== [RAGFlow] Upload document: datasetId={} ===", datasetId); MultiValueMap body = new LinkedMultiValueMap<>(); body.add("file", new MultipartFileResource(file)); @@ -209,7 +209,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { body.add("meta", objectMapper.writeValueAsString(req.getMetaFields())); } if (req.getChunkMethod() != null) { - // 将枚举值转为 RAGFlow 期待的字符串(如 NAIVE -> naive) + // Convert enum values to strings expected by RAGFlow (e.g., NAIVE -> naive). body.add("chunk_method", req.getChunkMethod().name().toLowerCase()); } if (req.getParserConfig() != null) { @@ -226,7 +226,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); } } @@ -268,11 +268,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] Batch delete 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("Failed to batch delete documents: datasetId={}", datasetId, e); throw convertToRenException(e); } } @@ -280,14 +280,14 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public boolean parseDocuments(String datasetId, List documentIds) { try { - log.info("=== [RAGFlow] 解析文档 ==="); + log.info("=== [RAGFlow] Parsing document ==="); 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("Failed to parse document", e); throw convertToRenException(e); } } @@ -295,7 +295,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public ChunkDTO.ListVO listChunks(String datasetId, String documentId, ChunkDTO.ListReq req) { try { - // [提灯重构] 使用 objectMapper 动态转换查询参数,消除硬编码 + // [Lantern Refactor] Use objectMapper to dynamically convert query parameters, eliminating hardcoding Map params = objectMapper.convertValue(req, new TypeReference>() { }); @@ -304,7 +304,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 response data is empty, docId={}", documentId); return ChunkDTO.ListVO.builder() .chunks(new ArrayList<>()) .total(0L) @@ -317,7 +317,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } return result; } catch (Exception e) { - log.error("获取切片失败: docId={}", documentId, e); + log.error("Failed to get slice: docId={}", documentId, e); throw convertToRenException(e); } } @@ -325,18 +325,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] Defensive parameter alignment: RAGFlow Python side is sensitive to 0 or negative pagination values + // Resolve ValueError('Search does not support negative slicing.') 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 10 items } if (req.getTopK() != null && req.getTopK() < 1) { - req.setTopK(1024); // RAGFlow 内部默认 TopK + req.setTopK(1024); // RAGFlow internal default TopK } - // 相似度阈值归一化 (0.0 ~ 1.0) + // Normalize similarity threshold (0.0 ~ 1.0) if (req.getSimilarityThreshold() != null) { if (req.getSimilarityThreshold() < 0f) req.setSimilarityThreshold(0.2f); @@ -344,12 +344,12 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { req.setSimilarityThreshold(1.0f); } - // [提灯重构] 直接透传强类型 DTO,由 getClient 处理序列化 + // [Lantern refactor] Pass through strongly-typed DTOs directly; 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 response data is empty"); return RetrievalDTO.ResultVO.builder() .chunks(new ArrayList<>()) .docAggs(new ArrayList<>()) @@ -363,7 +363,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } return result; } catch (Exception e) { - log.error("召回测试失败", e); + log.error("Recall test failed", e); throw convertToRenException(e); } } @@ -374,7 +374,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; } } @@ -383,7 +383,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; @@ -392,9 +392,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 (ms)"); return supportedConfig; } @@ -408,8 +408,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 value handling to prevent RAGFlow API errors (Code 101) due to empty strings or missing fields + // Resolve validation failures such as "Field: - Message: " if (StringUtils.isBlank(req.getPermission())) { req.setPermission("me"); } @@ -417,33 +417,33 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { req.setChunkMethod("naive"); } - // 🤖 自动补全嵌入模型:优先使用请求传参,其次使用配置中的默认模型 + // 🤖 Auto-complete embedding model: prioritize request parameters, then use the default model from config 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 default embedding model from config: {}", defaultModel); req.setEmbeddingModel(defaultModel); } - // 若配置中也无默认值,则留空由 RAGFlow 服务端自行兜底(或抛出业务异常) + // If no default value is configured, leave it empty to let the RAGFlow server handle it (or throw a business exception) } - // 🖼️ 自动补全头像:若为空则提供一个 1x1 透明像素,防止 RAGFlow 校验 MIME Prefix 失败 + // 🖼️ Auto-complete avatar: Provide a 1x1 transparent pixel if empty to prevent RAGFlow MIME Prefix validation failures. if (StringUtils.isBlank(req.getAvatar())) { req.setAvatar( "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="); } - // 直接将强类型请求对象传给 Client,Jackson 会处理 JsonProperty 映射 + // Pass the strongly-typed request object directly to the Client; Jackson handles JsonProperty mapping. Map response = getClient().post("/api/v1/datasets", req); - // 安全地获取 data 并通过 DatasetDTO.InfoVO 进行全量映射 + // Safely retrieve data and perform full mapping via 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("Failed to create dataset", e); throw convertToRenException(e); } } @@ -451,7 +451,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public DatasetDTO.InfoVO updateDataset(String datasetId, DatasetDTO.UpdateReq req) { try { - // RAGFlow API 更新建议路径带 ID + // RAGFlow API update suggestion path with ID Map response = getClient().put("/api/v1/datasets/" + datasetId, req); Object dataObj = response.get("data"); @@ -460,7 +460,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } return null; } catch (Exception e) { - log.error("更新数据集失败", e); + log.error("Failed to update dataset", e); throw convertToRenException(e); } } @@ -468,7 +468,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { @Override public DatasetDTO.BatchOperationVO deleteDataset(DatasetDTO.BatchIdReq req) { try { - // RAGFlow 批量删除接口使用 DELETE /api/v1/datasets + // RAGFlow batch delete API uses DELETE /api/v1/datasets Map response = getClient().delete("/api/v1/datasets", req); Object dataObj = response.get("data"); @@ -477,7 +477,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } return null; } catch (Exception e) { - log.error("批量删除数据集失败", e); + log.error("Failed to batch delete datasets", e); throw convertToRenException(e); } } @@ -508,10 +508,10 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { return objectMapper.convertValue(list.get(0), DatasetDTO.InfoVO.class); } } - // RAGFlow 端不存在该数据集 + // Dataset not found in RAGFlow return null; } catch (Exception e) { - log.warn("获取数据集信息失败: datasetId={}, error={}", datasetId, e.getMessage()); + log.warn("Failed to get dataset info: datasetId={}, error={}", datasetId, e.getMessage()); throw convertToRenException(e); } } @@ -521,7 +521,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); } } @@ -529,20 +529,20 @@ 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()。 + // Is SearchBot a wrapper for Dataset retrieval, or an undocumented API? + // Assume RAGFlow does not expose an explicit /searchbots endpoint for SDK calls, but rather Dataset Retrieval or Chat. + // But according to BotDTO, it is /api/v1/searchbots/ask (assumed) + // The config here may be for overriding, or we simply use the existing client from the adapter instance. + // But the Bot might use a different API Key? Typically, an Adapter instance is bound to one Key. + // If the Bot uses the system key, use getClient() directly. - // 暂时假设 endpoint /api/v1/searchbots/ask 存在(或者类似的) - // 如果是流式: + // Temporarily assume endpoint /api/v1/searchbots/ask exists (or similar) + // If streaming: 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); } } @@ -550,17 +550,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 existing helper parsing method for compatibility + // [Bug Fix] No longer swallow deserialization exceptions to prevent upper-layer misjudgment"document deleted" private PageData parseDocumentListResponse(Object dataObj, long curPage, long pageSize) { if (dataObj == null) { return new PageData<>(new ArrayList<>(), 0); @@ -569,18 +569,18 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { Map dataMap = Map.class.cast(dataObj); List documents = List.class.cast(dataMap.get("docs")); if (documents == null || documents.isEmpty()) { - // RAGFlow 明确返回了空文档列表,这是合法的"真空" + // RAGFlow explicitly returned an empty document list, this is a valid " empty" return new PageData<>(new ArrayList<>(), 0); } List list = new ArrayList<>(); for (Object docObj : documents) { try { - // 单文档转换容错:一个文档反序列化失败不影响其他文档 + // Single document conversion fault tolerance: deserialization failure of one document does not affect others 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 document: {}", e.getMessage()); } } @@ -595,7 +595,7 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { private KnowledgeFilesDTO parseUploadResponse(Object dataObj, String datasetId, MultipartFile file) { KnowledgeFilesDTO result = null; - // 尝试从响应数据中提取文档ID (documentId) + // Attempt to extract the document ID (documentId) from the response data if (dataObj != null) { try { DocumentDTO.InfoVO info = null; @@ -612,13 +612,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("Failed to extract documentId from RAGFlow response; content: {}", dataObj); + // Return a minimal DTO with basic info instead of null here to prevent upstream NPE result = new KnowledgeFilesDTO(); result.setDatasetId(datasetId); result.setName(file.getOriginalFilename()); @@ -630,8 +630,8 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { } /** - * 将 RAGFlow 的强类型 InfoVO 映射到内部使用的 KnowledgeFilesDTO - * 确保所有可用字段(名称、大小、状态、配置等)都得到全量同步 + * Map RAGFlow's strongly-typed InfoVO to the internal KnowledgeFilesDTO + * Ensure all available fields (name, size, status, config, etc.) are fully synchronized */ private KnowledgeFilesDTO mapToKnowledgeFilesDTO(DocumentDTO.InfoVO info, String datasetId) { KnowledgeFilesDTO dto = new KnowledgeFilesDTO(); @@ -644,7 +644,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()); } @@ -652,10 +652,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 } - // 时间同步 + // Time sync if (info.getCreateTime() != null) { dto.setCreatedAt(new Date(info.getCreateTime())); } @@ -663,16 +663,16 @@ public class RAGFlowAdapter extends KnowledgeBaseAdapter { dto.setUpdatedAt(new Date(info.getUpdateTime())); } - // 核心元数据补齐 (Issue 1) + // Complete core metadata (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()); // Map progress descriptions to error messages - // 扩展字段同步 + // Sync extended fields dto.setMetaFields(info.getMetaFields()); if (info.getChunkMethod() != null) { dto.setChunkMethod(info.getChunkMethod().name().toLowerCase()); 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 918148d12..39889e404 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 (Refactored) + * Integrate RAGFlow Adapter with Shadow DB mode */ @Service @AllArgsConstructor @@ -72,8 +72,8 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl { enrichDocumentCount(dto); - // syncDatasetFromRAG 检测到 RAGFlow 端已删除时,会将本地记录清理 - // 此时 datasetId 被置空作为标记,需要在列表中移除该条目 + // syncDatasetFromRAG cleans up local records when deletion is detected on the RAGFlow side. + // datasetId is set to empty as a marker; remove this entry from the list return dto.getDatasetId() == null; }); } @@ -85,8 +85,8 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl perform local cascade cleanup + log.info("Dataset {} does not exist on the RAGFlow side; performing local cleanup", dto.getDatasetId()); cleanupLocalDataset(dto.getDatasetId(), dto.getId()); - // 标记为已删除,让上层从列表中移除 + // Mark as deleted so the upper layer removes it from the list dto.setDatasetId(null); return; } - // 同步名称(去掉 username_ 前缀) + // Sync name (remove username_ prefix) String ragflowName = datasetInfo.getName(); if (StringUtils.isNotBlank(ragflowName)) { String localName = ragflowName.contains("_") ? ragflowName.substring(ragflowName.indexOf('_') + 1) : ragflowName; if (!localName.equals(dto.getName())) { - log.info("同步知识库名称: {} -> {}", dto.getName(), localName); + log.info("Sync knowledge base name: {} -> {}", dto.getName(), localName); KnowledgeBaseEntity entity = knowledgeBaseDao.selectById(dto.getId()); if (entity != null) { entity.setName(localName); @@ -125,12 +125,12 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl().eq("dataset_id", datasetId)); - // 2. 删除插件映射 + // 2. Delete plugin mappings knowledgeBaseDao.deletePluginMappingByKnowledgeBaseId(entityId); - // 3. 删除知识库记录 + // 3. Delete knowledge base record knowledgeBaseDao.deleteById(entityId); - // 4. 清理缓存 + // 4. Clear cache redisUtils.delete(RedisKeys.getKnowledgeBaseCacheKey(entityId)); - log.info("本地级联清理完成: datasetId={}, entityId={}", datasetId, entityId); + log.info("Local cascade cleanup completed: datasetId={}, entityId={}", datasetId, entityId); } catch (Exception e) { - log.error("本地级联清理失败: datasetId={}, entityId={}", datasetId, entityId, e); + log.error("Local cascade cleanup failed: datasetId={}, entityId={}", datasetId, entityId, e); } } @@ -186,7 +186,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl() .eq("dataset_id", datasetId) @@ -208,13 +208,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 default RAG model specified or available"); } } @@ -227,21 +227,21 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl() @@ -314,13 +314,13 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl().eq("dataset_id", datasetId)); - // 1. 恢复 404 校验:找不到记录抛异常 + // 1. Restore 404 validation: throw exception if record not found if (entity == null) { - log.warn("记录不存在,datasetId: {}", datasetId); + log.warn("Record not found, 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 删除失败则抛出异常,触发事务回滚,不允许已删除本地但保留远程的脏数据 + // Restore strict consistency: throw exception on RAG deletion failure to trigger transaction rollback; disallow dirty data where local is deleted but remote is retained boolean apiDeleteSuccess = false; if (StringUtils.isNotBlank(entity.getRagModelId()) && StringUtils.isNotBlank(entity.getDatasetId())) { try { @@ -400,26 +400,26 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl 0 ? "成功" : "失败"); + log.info("Local database deletion result: {}", deleteCount > 0 ? "Success" : "Failure"); redisUtils.delete(RedisKeys.getKnowledgeBaseCacheKey(entity.getId())); } } @@ -429,7 +429,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl queryWrapper = new QueryWrapper<>(); queryWrapper.in("dataset_id", datasetIdList).or().in("id", datasetIdList); List list = knowledgeBaseDao.selectList(queryWrapper); @@ -454,7 +454,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl getPageList(KnowledgeFilesDTO knowledgeFilesDTO, Integer page, Integer limit) { - log.info("=== 开始获取知识库文档列表 (Local-First 优化版) ==="); + log.info("=== Start fetching knowledge base document list (Local-First optimized) ==="); String datasetId = knowledgeFilesDTO.getDatasetId(); if (StringUtils.isBlank(datasetId)) { throw new RenException(ErrorCode.RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL); } - // 全量对账同步: 从RAGFlow拉取远端文档,实时同步确保立即感知远端变更 + // Full reconciliation sync: Pull remote documents from RAGFlow for real-time sync to immediately detect remote changes try { self.syncDocumentsFromRAG(datasetId); } catch (Exception e) { - log.warn("从RAGFlow全量同步文档失败(不影响本地查询): datasetId={}, error={}", datasetId, e.getMessage()); + log.warn("Failed to sync all documents from RAGFlow (does not affect local queries): datasetId={}, error={}", datasetId, e.getMessage()); } - // 1. 获取本地影子表数据 (MyBatis-Plus 分页) + // 1. Fetch local shadow table data (MyBatis-Plus pagination) Page pageParams = new Page<>(page, limit); QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("dataset_id", datasetId); @@ -100,30 +100,30 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl iPage = documentDao.selectPage(pageParams, queryWrapper); - // 3. 手动转换 DTO + // 3. Manually convert DTO 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. Dynamic state synchronization (with rate limiting and protection) + // [Bug Fix] P1: Expand sync whitelist to allow low-frequency sync for CANCEL/FAIL to support self-healing 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 (5s cooldown) boolean isActiveSync = "RUNNING".equals(runStatus) || "UNSTART".equals(runStatus); - // 低频自愈同步: CANCEL/FAIL (60秒冷却), 防止错误状态永久锁死 + // Low-frequency self-healing sync: CANCEL/FAIL (60s cooldown) to prevent permanent error state lock. boolean isRecoverySync = "CANCEL".equals(runStatus) || "FAIL".equals(runStatus); boolean needSync = isActiveSync || isRecoverySync; if (needSync) { - // 限流保护:活跃状态 5 秒冷却,自愈状态 60 秒冷却 + // Rate limiting protection: 5-second cooldown for active state, 60-second cooldown for self-healing state long cooldownMs = isActiveSync ? 5000 : 60000; DocumentEntity localEntity = documentDao.selectOne(new QueryWrapper() .eq("document_id", dto.getDocumentId())); @@ -134,52 +134,52 @@ 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 interrupt: failed to initialize adapter, {}", e.getMessage()); break; } } - // [关键修复] 记录同步前的 Token 数,用于计算增量 + // [Critical fix] Record token count before sync to calculate delta Long oldTokenCount = dto.getTokenCount() != null ? dto.getTokenCount() : 0L; syncDocumentStatusWithRAG(dto, adapter); - // 计算增量并更新知识库统计 (与定时任务保持一致) + // Calculate delta and update knowledge base stats (consistent with scheduled tasks) 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: correct knowledge base stats, docId={}, tokenDelta={}", dto.getDocumentId(), tokenDelta); } } } } - log.info("获取文档列表成功,总数: {}", pageData.getTotal()); + log.info("Successfully retrieved document list, total: {}", pageData.getTotal()); return pageData; } /** - * 将本地记录实体转换为DTO,手动对齐不一致字段 (size -> fileSize, type -> fileType) + * Convert local record entities to DTOs, manually aligning mismatched fields (size -> fileSize, type -> fileType) */ private KnowledgeFilesDTO convertEntityToDTO(DocumentEntity entity) { if (entity == null) { return null; } KnowledgeFilesDTO dto = new KnowledgeFilesDTO(); - // 1. 基础字段拷贝 + // 1. Copy basic fields BeanUtils.copyProperties(entity, dto); - // Issue 2: 修正 ID 语义。前端习惯使用 id 作为操作主键。 - // 在该模块中,应始终将远程 documentId 映射为 DTO 的 id,确保前端在详情/删除等操作时 ID 一致。 + // Issue 2: Correct ID semantics. Frontend convention uses id as the primary key for operations. + // In this module, always map the remote documentId to the DTO id to ensure ID consistency for frontend detail/delete operations. dto.setId(entity.getDocumentId()); - // 2. 将本地记录实体转换为DTO,手动对齐不一致字段 (size -> fileSize, type -> fileType) + // 2. Convert local record entities to DTOs, manually aligning inconsistent fields (size -> fileSize, type -> fileType) dto.setFileSize(entity.getSize()); dto.setFileType(entity.getType()); dto.setRun(entity.getRun()); @@ -187,25 +187,25 @@ 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. Parse config JSON deserialization 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 +213,12 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl updateWrapper = new UpdateWrapper() .set("status", remoteStatus) .set("run", remoteDto.getRun()) @@ -275,43 +275,43 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl() .set("run", "CANCEL") - .set("error", "文档在远程服务中已被删除") + .set("error", "Document has been deleted on 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 adapter call throws an exception, to avoid false positives due to network/deserialization issues + // Log only; retry on next sync cycle + log.warn("Adapter call failed during document status sync (do not mark CANCEL), documentId: {}, error: {}", documentId, e.getMessage()); } } @@ -322,38 +322,38 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); - // 提取适配器类型 + // Extract adapter type String adapterType = extractAdapterType(ragConfig); - // 使用适配器工厂获取适配器实例 + // Get adapter instance via adapter factory KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(adapterType, ragConfig); - // 使用适配器获取文档详情 + // Fetch document details using the adapter DocumentDTO.InfoVO info = adapter.getDocumentById(datasetId, documentId); if (info != null) { - log.info("获取文档详情成功,documentId: {}", documentId); + log.info("Successfully retrieved document details, 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 get 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("=== End of document operation based on documentId ==="); } } @@ -365,21 +365,21 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig); - // 构造强类型请求 DTO + // Construct strongly-typed request DTO DocumentDTO.UploadReq uploadReq = DocumentDTO.UploadReq.builder() .datasetId(datasetId) .file(file) @@ -387,40 +387,40 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl Enum) + // Convert chunking method (String -> 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: {}, using backend default config", chunkMethod); } } - // 转换解析配置 (Map -> DTO) + // Convert parse config (Map -> DTO) if (parserConfig != null && !parserConfig.isEmpty()) { uploadReq.setParserConfig(objectMapper.convertValue(parserConfig, DocumentDTO.InfoVO.ParserConfig.class)); } - // 执行远程上传 (耗时 IO,在事务之外) + // Execute remote upload (time-consuming IO, outside transaction) 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 returned no valid DocumentID"); } - // 2. 本地持久化 (通过 self 调用以激活 @Transactional 代理) - log.info("2. 同步保存本地影子记录: documentId={}", result.getDocumentId()); + // 2. Local persistence (call via self to activate @Transactional proxy) + log.info("2. Synchronously save local shadow record: documentId={}", result.getDocumentId()); self.saveDocumentShadow(datasetId, result, fileName, chunkMethod, parserConfig); - log.info("=== 文档上传与影子记录保存成功 ==="); + log.info("=== Document upload and shadow record saved successfully ==="); return result; } /** - * 原子化保存影子记录(Upsert 语义) - * 若 document_id 已存在则更新,不存在则插入,避免 UNIQUE 约束冲突 + * Atomically save shadow record (Upsert semantics) + * Update if document_id exists, insert otherwise, to avoid UNIQUE constraint conflicts * - * @return true=新插入, false=更新已有记录 + * @return true=New insertion, false=Update existing record */ @Transactional(rollbackFor = Exception.class) public boolean saveDocumentShadow(String datasetId, KnowledgeFilesDTO result, String originalName, String chunkMethod, @@ -437,7 +437,7 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl().eq("document_id", entity.getDocumentId())); if (existing != null) { entity.setId(existing.getId()); - entity.setCreatedAt(existing.getCreatedAt()); // 保留原始创建时间 + entity.setCreatedAt(existing.getCreatedAt()); // Preserve original creation time documentDao.updateById(entity); - log.info("影子记录已更新: documentId={}", entity.getDocumentId()); + log.info("Shadow record updated: documentId={}", entity.getDocumentId()); return false; } else { documentDao.insert(entity); - // 新增记录时递增数据集文档总数统计 + // Increment dataset document count when adding new record knowledgeBaseService.updateStatistics(datasetId, 1, 0L, 0L); - log.info("影子记录已插入: documentId={}, datasetId={}", entity.getDocumentId(), datasetId); + log.info("Shadow record inserted: documentId={}, datasetId={}", entity.getDocumentId(), datasetId); return true; } } @@ -492,16 +492,16 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl documentIds = req.getIds(); - log.info("=== 开始批量删除文档: datasetId={}, count={} ===", datasetId, documentIds.size()); + log.info("=== Starting batch document deletion: datasetId={}, count={} ===", datasetId, documentIds.size()); - // 1. 批量权限与状态预审 + // 1. Batch permission and status pre-check 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 have ownership issues: expected={}, actual={}", documentIds.size(), entities.size()); throw new RenException(ErrorCode.NO_PERMISSION); } @@ -509,69 +509,69 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig); - // 3. 执行远程删除 + // 3. Execute remote deletion try { adapter.deleteDocument(datasetId, req); - log.info("远程批量删除请求成功"); + log.info("Remote batch delete request succeeded"); } catch (Exception e) { - log.error("远程删除请求失败,中止本地清理以避免数据不一致: {}", e.getMessage()); + log.error("Remote deletion request failed; aborting local cleanup to prevent data inconsistency: {}", e.getMessage()); throw new RenException(e.getMessage()); } - // 4. 原子化清理本地影子记录并同步统计数据 + // 4. Atomically clean up local shadow records and sync statistics self.deleteDocumentShadows(documentIds, datasetId, totalChunkDelta, totalTokenDelta); - // 5. 清理缓存 + // 5. Clear cache 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 Redis cache: {}", e.getMessage()); } - log.info("=== 批量文档清理完成 ==="); + log.info("=== Batch document cleanup complete ==="); } /** - * 批量原子化删除影子记录并同步父表统计 + * Atomically delete shadow records in batch and sync parent table statistics */ @Transactional(rollbackFor = Exception.class) public void deleteDocumentShadows(List documentIds, String datasetId, Long chunkDelta, Long tokenDelta) { - // 1. 物理删除记录 + // 1. Physically delete records int deleted = documentDao.delete( new QueryWrapper() .eq("dataset_id", datasetId) .in("document_id", documentIds)); if (deleted > 0) { - // 2. 同步更新数据集统计信息 + // 2. Synchronously update dataset statistics knowledgeBaseService.updateStatistics(datasetId, -documentIds.size(), -chunkDelta, -tokenDelta); - log.info("已同步扣减数据集统计: datasetId={}, chunks={}, tokens={}", datasetId, chunkDelta, tokenDelta); + log.info("Synced dataset stats deduction: datasetId={}, chunks={}, tokens={}", datasetId, chunkDelta, tokenDelta); } } /** - * 获取文件类型 - 支持RAG四种文档格式类型 + * Get file type - supports four RAG document format types */ private String getFileType(String fileName) { if (StringUtils.isBlank(fileName)) { - log.warn("文件名为空,返回unknown类型"); + log.warn("Filename is empty, returning unknown type"); return "unknown"; } @@ -580,57 +580,57 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl 0 && lastDotIndex < fileName.length() - 1) { String extension = fileName.substring(lastDotIndex + 1).toLowerCase(); - // 文档格式类型 + // Document format type String[] documentTypes = { "pdf", "doc", "docx", "txt", "md", "mdx" }; String[] spreadsheetTypes = { "csv", "xls", "xlsx" }; String[] presentationTypes = { "ppt", "pptx" }; - // 检查文档类型 + // Check document type for (String type : documentTypes) { if (type.equals(extension)) { return "document"; } } - // 检查表格类型 + // Check table type for (String type : spreadsheetTypes) { if (type.equals(extension)) { return "spreadsheet"; } } - // 检查幻灯片类型 + // Check slide type for (String type : presentationTypes) { if (type.equals(extension)) { return "presentation"; } } - // 返回原始扩展名作为文件类型 + // Return original extension as file type return extension; } return "unknown"; } catch (Exception e) { - log.error("获取文件类型失败: ", e); + log.error("Failed to get file type: ", e); return "unknown"; } } /** - * 从RAG配置中提取适配器类型 + * Extract adapter type from RAG config */ private String extractAdapterType(Map config) { if (config == null) { throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND); } - // 从配置中提取type字段 + // Extract type field from config String adapterType = (String) config.get("type"); if (StringUtils.isBlank(adapterType)) { throw new RenException(ErrorCode.RAG_ADAPTER_TYPE_NOT_FOUND); } - // 验证适配器类型是否已注册 + // Verify if 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 not registered: " + adapterType); } return adapterType; @@ -642,27 +642,27 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); - // 提取适配器类型 + // Extract adapter type String adapterType = extractAdapterType(ragConfig); - // 获取知识库适配器 + // Get knowledge base adapter KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(adapterType, ragConfig); - log.debug("解析文档参数: documentIds: {}", documentIds); + log.debug("Parsing document parameters: documentIds: {}", documentIds); - // 调用适配器解析文档 + // Call adapter to parse document boolean result = adapter.parseDocuments(datasetId, documentIds); if (result) { - log.info("文档解析命令发送成功,准备同步本地影子库状态,datasetId: {}, documentIds: {}", datasetId, documentIds); - // 指令成功后立即更新本地影子状态为 RUNNING 和 解析中(1),确保 Local-First 列表能立即反馈 + log.info("Document parsing command sent successfully, preparing to sync local shadow DB state, datasetId: {}, documentIds: {}", datasetId, documentIds); + // Immediately update the local shadow state to RUNNING and Parsing(1) after command success to ensure the Local-First list reflects changes instantly. documentDao.update(null, new UpdateWrapper() .set("run", "RUNNING") .set("status", "1") @@ -670,23 +670,23 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); @@ -704,27 +704,27 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(req.getDatasetIds().get(0)); @@ -732,24 +732,24 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl list = documentDao .selectList(new QueryWrapper().eq("dataset_id", datasetId)); if (list == null || list.isEmpty()) @@ -757,20 +757,20 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl docIds = list.stream().map(DocumentEntity::getDocumentId).toList(); - // 封包调用现有删除逻辑 (含 RAG 物理删除) + // Package call to existing deletion logic (including RAG physical deletion) DocumentDTO.BatchIdReq req = DocumentDTO.BatchIdReq.builder().ids(docIds).build(); this.deleteDocuments(datasetId, req); } @Override public int syncDocumentsFromRAG(String datasetId) { - log.info("=== 开始从RAGFlow全量同步文档到本地影子表: datasetId={} ===", datasetId); + log.info("=== Starting full document sync from RAGFlow to local shadow table: datasetId={} ===", datasetId); - // 1. 获取适配器 + // 1. Get adapter Map ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); KnowledgeBaseAdapter adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig); - // 2. 分页拉取远端所有文档 + // 2. Fetch all remote documents via pagination List allRemoteDocs = new ArrayList<>(); int pageNum = 1; int pageSize = 100; @@ -790,20 +790,20 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl localDocs = documentDao.selectList( new QueryWrapper().eq("dataset_id", datasetId)); Set localDocIds = localDocs.stream() .map(DocumentEntity::getDocumentId) .collect(Collectors.toSet()); - // 4. 远端文档ID集合 + // 4. Remote document ID set Set remoteDocIds = allRemoteDocs.stream() .map(KnowledgeFilesDTO::getDocumentId) .filter(id -> id != null) .collect(Collectors.toSet()); - // 5. 补充: 插入远端存在但本地缺失的文档 + // 5. Supplement: insert documents present remotely but missing locally List newDocs = allRemoteDocs.stream() .filter(doc -> doc.getDocumentId() != null && !localDocIds.contains(doc.getDocumentId())) .collect(Collectors.toList()); @@ -813,7 +813,7 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl 0 || chunkCount > 0) { @@ -821,13 +821,13 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl deletedDocs = localDocs.stream() .filter(entity -> !remoteDocIds.contains(entity.getDocumentId())) .collect(Collectors.toList()); @@ -844,14 +844,14 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl remoteDocMap = allRemoteDocs.stream() .filter(doc -> doc.getDocumentId() != null) .collect(Collectors.toMap(KnowledgeFilesDTO::getDocumentId, doc -> doc, (a, b) -> b)); @@ -864,11 +864,11 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl updateWrapper = new UpdateWrapper() .set("run", remote.getRun()) .set("status", remote.getStatus() != null ? remote.getStatus() : local.getStatus()) @@ -893,13 +893,13 @@ public class KnowledgeFilesServiceImpl extends BaseServiceImpl runningDocs = documentDao.selectList( new QueryWrapper() .eq("run", "RUNNING") - .eq("status", "1") // 仅同步启用的文档 + .eq("status", "1") // Sync only enabled documents ); if (runningDocs == null || runningDocs.isEmpty()) { return; } - log.info("定时任务: 发现 {} 个文档正在解析中,开始同步...", runningDocs.size()); + log.info("Scheduled task: Found {} documents being parsed, starting sync...", runningDocs.size()); - // 2. 按 DatasetID 分组,复用 Adapter + // 2. Group by DatasetID, reuse Adapter Map> groupedDocs = runningDocs.stream() .collect(Collectors.groupingBy(DocumentEntity::getDatasetId)); groupedDocs.forEach((datasetId, docs) -> { KnowledgeBaseAdapter adapter = null; try { - // 初始化 Adapter (每个数据集只初始化一次) + // Initialize Adapter (initialize once per dataset) Map ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); adapter = KnowledgeBaseAdapterFactory.getAdapter(extractAdapterType(ragConfig), ragConfig); } catch (Exception e) { - log.warn("无法为数据集 {} 初始化适配器,跳过同步: {}", datasetId, e.getMessage()); + log.warn("Failed to initialize adapter for dataset {}, skipping sync: {}", datasetId, e.getMessage()); return; } for (DocumentEntity doc : docs) { try { - // 构造临时 DTO 传给同步方法 + // Construct a temporary DTO to pass to the sync method. KnowledgeFilesDTO dto = convertEntityToDTO(doc); - // 记录同步前的 Token 数 + // Record token count before sync Long oldTokenCount = dto.getTokenCount() != null ? dto.getTokenCount() : 0L; syncDocumentStatusWithRAG(dto, adapter); - // 3. [关键修复] 计算增量并更新知识库统计 + // 3. [Critical Fix] Calculate the delta and update knowledge base statistics Long newTokenCount = dto.getTokenCount() != null ? dto.getTokenCount() : 0L; Long tokenDelta = newTokenCount - oldTokenCount; - // 仅当状态变为 SUCCESS 且 Token 数有变化时更新统计 + // Update statistics only when status changes to SUCCESS and token count changes if (tokenDelta != 0) { knowledgeBaseService.updateStatistics(datasetId, 0, 0L, tokenDelta); - log.info("定时任务: 同步修正知识库统计, docId={}, tokenDelta={}", dto.getDocumentId(), tokenDelta); + log.info("Scheduled task: Sync and correct 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()); } } }); 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 b89ae982f..bf3d361ac 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 @@ -24,14 +24,14 @@ 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 API + * Supports models compatible with OpenAI API, such as Alibaba Cloud, DeepSeek, and ChatGLM */ @Slf4j @Service public class OpenAIStyleLLMServiceImpl implements LLMService { - // 需要禁用思考模式的平台域名及其对应参数 + // Platform domains requiring thinking mode disabled and their corresponding parameters private static final Map> THINKING_DISABLED_DOMAINS = new LinkedHashMap<>(); static { THINKING_DISABLED_DOMAINS.put("aliyuncs.com", Map.of("enable_thinking", false)); @@ -48,21 +48,21 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { private final RestTemplate restTemplate = new RestTemplate(); /** - * 根据域名自动禁用思考模式 + * Automatically disable thinking mode based on domain */ private void applyThinkingDisabled(String baseUrl, Map requestBody) { for (Map.Entry> entry : THINKING_DISABLED_DOMAINS.entrySet()) { if (baseUrl.contains(entry.getKey())) { requestBody.putAll(entry.getValue()); - log.info("为域名 {} 禁用思考模式,参数: {}", baseUrl, entry.getValue()); + log.info("Disable thinking mode for domain {}, params: {}", baseUrl, entry.getValue()); break; } } } - 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, skilled at summarizing conversation content. Follow these rules: \n 1. Summarize important user information to provide more personalized service in future conversations. 2. Do not repeat summaries or forget previous memories. Unless the original memory exceeds 1800 characters, do not forget or compress the user's historical memory. 3. Do not include content unrelated to the user, such as device volume control, music playback, weather, exit commands, or refusal to converse. 4. Do not include data unrelated to user events, such as today's date/time or today's weather, as storing this as memory affects subsequent conversations. 5. Do not include success or failure results of device control, nor include user filler words. 6. Do not summarize for the sake of summarizing. If the user's chat is meaningless, returning the original history is acceptable. 7. Return only the summary, strictly within 1800 characters. 8. Do not include code or XML. No explanations, comments, or descriptions. Extract information only from the conversation when saving memory; do not mix in example content. 9. If historical memory is provided, intelligently merge new conversation content with historical memory, preserving valuable historical information while adding new important information. Historical Memory: {history_memory} New Conversation Content: {conversation}"; - private static final String DEFAULT_TITLE_PROMPT = "请根据以下对话内容,生成一个简洁的会话标题(约15字以内),只返回标题,不要包含任何解释或标点符号:\n{conversation}"; + private static final String DEFAULT_TITLE_PROMPT = "Generate a concise session title (approx. 15 chars) based on the following conversation. Return only the title, with no explanations or punctuation: \n{conversation}"; @Override public String generateSummary(String conversation) { @@ -77,24 +77,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 unavailable, unable to generate summary"); + return "LLM service unavailable, unable to generate summary"; } try { - // 从智控台获取LLM模型配置 + // Fetch LLM model config from Console ModelConfigEntity llmConfig; if (modelId != null && !modelId.trim().isEmpty()) { - // 通过具体模型ID获取配置 + // Get config by specific model ID llmConfig = modelConfigService.getModelByIdFromCache(modelId); } else { - // 保持向后兼容,使用默认配置 + // Maintain backward compatibility using default config llmConfig = getDefaultLLMConfig(); } if (llmConfig == null || llmConfig.getConfigJson() == null) { - log.error("未找到可用的LLM模型配置,modelId: {}", modelId); - return "未找到可用的LLM模型配置"; + log.error("No available LLM model config found, modelId: {}", modelId); + return "No available LLM model config found"; } JSONObject configJson = llmConfig.getConfigJson(); @@ -105,15 +105,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 config incomplete: baseUrl or apiKey is empty"); + return "LLM config incomplete, unable to generate summary"; } - // 构建提示词 + // Build prompt String prompt = (promptTemplate != null ? promptTemplate : DEFAULT_SUMMARY_PROMPT).replace("{conversation}", conversation); - // 构建请求体 + // Build request body Map requestBody = new HashMap<>(); requestBody.put("model", model != null ? model : "gpt-3.5-turbo"); @@ -125,17 +125,17 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { requestBody.put("temperature", temperature != null ? temperature : 0.7); requestBody.put("max_tokens", maxTokens != null ? maxTokens : 2000); - // 禁用思考模式 + // Disable thinking mode applyThinkingDisabled(baseUrl, requestBody); - // 发送HTTP请求 + // Send 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 complete API URL String apiUrl = baseUrl; if (!apiUrl.endsWith("/chat/completions")) { if (!apiUrl.endsWith("/")) { @@ -156,13 +156,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 code: {}, response: {}", response.getStatusCode(), response.getBody()); } } catch (Exception e) { - log.error("调用LLM服务生成总结时发生异常,modelId: {}", modelId, e); + log.error("Exception occurred while calling LLM service to generate summary, modelId: {}", modelId, e); } - return "生成总结失败,请稍后重试"; + return "Failed to generate summary, please try again later"; } @Override @@ -174,12 +174,12 @@ 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 unavailable, unable to generate summary"); + return "LLM service unavailable, unable to generate summary"; } try { - // 从智控台获取LLM模型配置 + // Fetch LLM model config from Console ModelConfigEntity llmConfig; if (modelId != null && !modelId.trim().isEmpty()) { llmConfig = modelConfigService.getModelByIdFromCache(modelId); @@ -188,8 +188,8 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { } if (llmConfig == null || llmConfig.getConfigJson() == null) { - log.error("未找到可用的LLM模型配置,modelId: {}", modelId); - return "未找到可用的LLM模型配置"; + log.error("No available LLM model config found, modelId: {}", modelId); + return "No available LLM model config found"; } JSONObject configJson = llmConfig.getConfigJson(); @@ -198,16 +198,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 config incomplete: baseUrl or apiKey is empty"); + return "LLM config incomplete, unable to generate summary"; } - // 构建提示词,包含历史记忆 + // 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 history memory") .replace("{conversation}", conversation); - // 构建请求体 + // Build request body Map requestBody = new HashMap<>(); requestBody.put("model", model != null ? model : "gpt-3.5-turbo"); @@ -219,17 +219,17 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { requestBody.put("temperature", 0.2); requestBody.put("max_tokens", 2000); - // 禁用思考模式 + // Disable thinking mode applyThinkingDisabled(baseUrl, requestBody); - // 发送HTTP请求 + // Send 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 complete API URL String apiUrl = baseUrl; if (!apiUrl.endsWith("/chat/completions")) { if (!apiUrl.endsWith("/")) { @@ -250,13 +250,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 code: {}, response: {}", response.getStatusCode(), response.getBody()); } } catch (Exception e) { - log.error("调用LLM服务生成总结时发生异常,modelId: {}", modelId, e); + log.error("Exception occurred while calling LLM service to generate summary, modelId: {}", modelId, e); } - return "生成总结失败,请稍后重试"; + return "Failed to generate summary, please try again later"; } @Override @@ -274,7 +274,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("Exception occurred while checking LLM service availability:", e); return false; } } @@ -286,10 +286,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { return isAvailable(); } - // 通过具体模型ID获取配置 + // Get config by specific model ID ModelConfigEntity modelConfig = modelConfigService.getModelByIdFromCache(modelId); if (modelConfig == null || modelConfig.getConfigJson() == null) { - log.warn("未找到指定的LLM模型配置,modelId: {}", modelId); + log.warn("Specified LLM model config not found, modelId: {}", modelId); return false; } @@ -300,23 +300,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("Exception while checking LLM service availability, modelId: {}", modelId, e); return false; } } /** - * 从智控台获取默认的LLM模型配置 + * Get default LLM model config from Console */ private ModelConfigEntity getDefaultLLMConfig() { try { - // 获取所有启用的LLM模型配置 + // Get all enabled LLM model configs List llmConfigs = modelConfigService.getEnabledModelsByType("LLM"); if (llmConfigs == null || llmConfigs.isEmpty()) { return null; } - // 优先返回默认配置,如果没有默认配置则返回第一个启用的配置 + // Return default config first; if none exists, return the first enabled config for (ModelConfigEntity config : llmConfigs) { if (config.getIsDefault() != null && config.getIsDefault() == 1) { return config; @@ -325,7 +325,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { return llmConfigs.get(0); } catch (Exception e) { - log.error("获取LLM模型配置时发生异常:", e); + log.error("Exception occurred while retrieving LLM model config:", e); return null; } } @@ -333,7 +333,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { @Override public String generateTitle(String conversation, String modelId) { if (!isAvailable()) { - log.warn("LLM服务不可用,无法生成标题"); + log.warn("LLM service unavailable, unable to generate title"); return null; } @@ -346,7 +346,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { } if (llmConfig == null || llmConfig.getConfigJson() == null) { - log.error("未找到可用的LLM模型配置,modelId: {}", modelId); + log.error("No available LLM model config found, modelId: {}", modelId); return null; } @@ -356,7 +356,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { String apiKey = configJson.getStr("api_key"); if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) { - log.error("LLM配置不完整,baseUrl或apiKey为空"); + log.error("LLM config incomplete: baseUrl or apiKey is empty"); return null; } @@ -373,7 +373,7 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { requestBody.put("temperature", 0.3); requestBody.put("max_tokens", 50); - // 禁用思考模式 + // Disable thinking mode applyThinkingDisabled(baseUrl, requestBody); HttpHeaders headers = new HttpHeaders(); @@ -409,10 +409,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService { } } } else { - log.error("LLM API调用失败,状态码:{},响应:{}", response.getStatusCode(), response.getBody()); + log.error("LLM API call failed, status code: {}, response: {}", response.getStatusCode(), response.getBody()); } } catch (Exception e) { - log.error("调用LLM服务生成标题时发生异常,modelId: {}", modelId, e); + log.error("Exception occurred while calling LLM service to generate title, modelId: {}", modelId, e); } return null; 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 007e8abf9..5bcf9b60e 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 @@ -385,7 +385,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl { void initServerSecret(); /** - * 获取系统功能菜单配置 + * Get system function menu configuration * - * @param fromCache 是否从缓存获取 - * @return 系统功能菜单配置JSON字符串 + * @param fromCache Whether retrieved from cache + * @return System function menu config JSON string */ String getSystemWebMenu(boolean fromCache); /** - * 更新系统功能菜单配置(自动处理功能相关的插件清理) + * Update system feature menu config (automatically handles cleanup of feature-related plugins) * - * @param configJson 新的系统功能菜单配置JSON + * @param configJson New system feature menu config JSON */ void updateSystemWebMenu(String configJson); } 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 4c6423f85..7f1d10534 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 @@ -30,7 +30,7 @@ import xiaozhi.modules.sys.redis.SysParamsRedis; import xiaozhi.modules.sys.service.SysParamsService; /** - * 参数管理 + * Parameter management */ @AllArgsConstructor @Service @@ -96,7 +96,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)); } @@ -203,56 +203,56 @@ public class SysParamsServiceImpl extends BaseServiceImpl keyPair = SM2Utils.createKey(); String newPublicKey = keyPair.get(SM2Utils.KEY_PUBLIC_KEY); String newPrivateKey = keyPair.get(SM2Utils.KEY_PRIVATE_KEY); - // 更新数据库中的密钥对 + // Update key pair in database updateValueByCode(Constant.SM2_PUBLIC_KEY, newPublicKey); updateValueByCode(Constant.SM2_PRIVATE_KEY, newPrivateKey); } } /** - * 检测短信参数是否符合要求 + * Validate SMS parameters * - * @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 the parameter code enables mobile registration; if not, skip other SMS parameter checks and return true directly. if (!Constant.SysMSMParam.SERVER_ENABLE_MOBILE_REGISTER.getValue().equals(paramCode)) { return true; } - // 判断是否为关闭,如果是关闭短信注册,着不需要检测其他短信参数,直接返回true + // Check if it is a close SMS registration; if so, skip other SMS parameter checks and return true directly. if ("false".equalsIgnoreCase(paramValue)) { return true; } - // 检测短信关联参数是否为空 + // Check if SMS association parameters are empty ArrayList list = new ArrayList(); list.add(Constant.SysMSMParam.SERVER_SMS_MAX_SEND_COUNT.getValue()); list.add(Constant.SysMSMParam.TWILIO_SMS_ACCOUNT_SID.getValue()); @@ -266,7 +266,7 @@ public class SysParamsServiceImpl extends BaseServiceImpl currentMap = null; Map newMap = null; @@ -296,7 +296,7 @@ public class SysParamsServiceImpl extends BaseServiceImpl currentFeatures = Map.class.cast(currentMap.get("features")); Map newFeatures = Map.class.cast(newMap.get("features")); @@ -318,14 +318,14 @@ public class SysParamsServiceImpl extends BaseServiceImpl changedFields = (List) method.invoke(service, current, next); @@ -1160,7 +1160,7 @@ class AgentSnapshotServiceImplTest { template.setSummaryMemory(null); when(templateService.getDefaultTemplate()).thenReturn(template); - when(timbreService.getDefaultLanguageById("TTS_EdgeTTS0001")).thenReturn("普通话"); + when(timbreService.getDefaultLanguageById("TTS_EdgeTTS0001")).thenReturn("Mandarin"); when(agentDao.insert(any(AgentEntity.class))).thenReturn(1); AgentCreateDTO dto = new AgentCreateDTO(); @@ -1170,7 +1170,7 @@ class AgentSnapshotServiceImplTest { InOrder inOrder = inOrder(agentDao, pluginMappingService, snapshotService); inOrder.verify(agentDao).insert(argThat((AgentEntity agent) -> "test123".equals(agent.getAgentName()) - && "普通话".equals(agent.getTtsLanguage()) + && "Mandarin".equals(agent.getTtsLanguage()) && "".equals(agent.getSummaryMemory()) && Integer.valueOf(0).equals(agent.getChatHistoryConf()))); inOrder.verify(pluginMappingService).saveBatch(any(), eq(IRepository.DEFAULT_BATCH_SIZE)); @@ -1235,7 +1235,7 @@ class AgentSnapshotServiceImplTest { RenException error = assertThrows(RenException.class, () -> service.restoreSnapshot(agentId, targetId, "stale-token")); - assertTrue(error.getMessage().contains("重新打开恢复预览")); + assertTrue(error.getMessage().contains("reopen recovery preview")); verify(snapshotDao, never()).selectLatestSnapshot(agentId); verify(snapshotDao, never()).insertWithNextVersion(any()); verify(agentDao, never()).updateSnapshotFields(any()); @@ -1430,7 +1430,7 @@ class AgentSnapshotServiceImplTest { AgentEntity lockedAgent = new AgentEntity(); lockedAgent.setId(agentId); lockedAgent.setUserId(7L); - lockedAgent.setTtsLanguage("普通话"); + lockedAgent.setTtsLanguage("Mandarin"); lockedAgent.setTtsVolume(0); lockedAgent.setTtsRate(0); lockedAgent.setTtsPitch(0); @@ -1440,7 +1440,7 @@ class AgentSnapshotServiceImplTest { lockedAgent.setSystemPrompt("old prompt"); AgentInfoVO currentInfo = snapshotAgentInfo(agentId, 7L, "same-name", "same-summary"); - currentInfo.setTtsLanguage("普通话"); + currentInfo.setTtsLanguage("Mandarin"); currentInfo.setTtsVolume(0); currentInfo.setTtsRate(0); currentInfo.setTtsPitch(0); @@ -1451,7 +1451,7 @@ class AgentSnapshotServiceImplTest { AgentInfoVO restoredInfo = snapshotAgentInfo(agentId, 7L, "same-name", "same-summary"); AgentSnapshotDataDTO currentData = snapshotData("same-name", "same-summary"); - currentData.setTtsLanguage("普通话"); + currentData.setTtsLanguage("Mandarin"); currentData.setTtsVolume(0); currentData.setTtsRate(0); currentData.setTtsPitch(0); @@ -1834,7 +1834,7 @@ class AgentSnapshotServiceImplTest { () -> method.invoke(service, snapshotTag, new Date())); assertTrue(error.getCause() instanceof RenException); - assertEquals("快照引用的标签已被删除,无法恢复,请先重新创建或选择标签", error.getCause().getMessage()); + assertEquals("The tag referenced by the snapshot has been deleted and cannot be restored. Please recreate or select a tag first.", error.getCause().getMessage()); verify(tagDao, never()).updateById(any(AgentTagEntity.class)); verify(tagDao, never()).insert(any(AgentTagEntity.class)); } diff --git a/main/manager-api/src/test/java/xiaozhi/modules/device/controller/DeviceControllerTest.java b/main/manager-api/src/test/java/xiaozhi/modules/device/controller/DeviceControllerTest.java index a3fa0ad4f..de575f564 100644 --- a/main/manager-api/src/test/java/xiaozhi/modules/device/controller/DeviceControllerTest.java +++ b/main/manager-api/src/test/java/xiaozhi/modules/device/controller/DeviceControllerTest.java @@ -22,14 +22,14 @@ import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.security.user.SecurityUser; import xiaozhi.modules.sys.service.SysParamsService; -@DisplayName("设备更新接口回归测试") +@DisplayName("Device update API regression test") class DeviceControllerTest { private static final String DEVICE_ID = "device-id"; private static final long USER_ID = 1L; @Test - @DisplayName("数据库未更新时不误报自动升级状态修改成功") + @DisplayName("Do not falsely report auto-upgrade status change success when the database is not updated") void updateFailureIsReturnedToCaller() { DeviceService deviceService = mock(DeviceService.class); DeviceEntity entity = ownedDevice(); diff --git a/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceAutoUpdateTest.java b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceAutoUpdateTest.java index 67a29a6ce..2fae36d29 100644 --- a/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceAutoUpdateTest.java +++ b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceAutoUpdateTest.java @@ -19,7 +19,7 @@ import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.service.OtaService; import xiaozhi.modules.sys.service.SysParamsService; -@DisplayName("设备自动升级回归测试") +@DisplayName("Device auto-upgrade regression test") class DeviceAutoUpdateTest { private static final String MAC_ADDRESS = "00:11:22:33:44:55"; @@ -27,7 +27,7 @@ class DeviceAutoUpdateTest { private static final String CURRENT_VERSION = "1.0.0"; @Test - @DisplayName("#3299 自动升级关闭时 OTA 响应不包含固件") + @DisplayName("#3299 OTA response excludes firmware when auto-upgrade is disabled") void disabledAutoUpdateOmitsFirmware() { OtaService otaService = mock(OtaService.class); DeviceServiceImpl service = proxiedService(deviceWithAutoUpdate(0), otaService); @@ -40,7 +40,7 @@ class DeviceAutoUpdateTest { } @Test - @DisplayName("自动升级开启时继续执行固件查询") + @DisplayName("Continue firmware query when auto-upgrade is enabled.") void enabledAutoUpdateChecksFirmware() { OtaService otaService = mock(OtaService.class); when(otaService.getLatestOta(BOARD_TYPE)).thenReturn(null); diff --git a/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceTimeSerializationTest.java b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceTimeSerializationTest.java index bf2e14835..48f438663 100644 --- a/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceTimeSerializationTest.java +++ b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceTimeSerializationTest.java @@ -21,12 +21,12 @@ import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.vo.UserShowDeviceListVO; import xiaozhi.modules.security.config.WebMvcConfig; -@DisplayName("设备时间序列化回归测试") +@DisplayName("Device time serialization regression test") class DeviceTimeSerializationTest { - @ParameterizedTest(name = "浏览器时区 {0}") + @ParameterizedTest(name = "Browser timezone {0}") @ValueSource(strings = { "Asia/Shanghai", "America/Sao_Paulo" }) - @DisplayName("#3280 绑定时间和最后连接时间在任意浏览器时区都表示同一时刻") + @DisplayName("#3280 Bind time and last connection time represent the same moment in any browser timezone") void serializedDeviceTimesDescribeTheSameInstantAcrossBrowserTimeZones(String browserTimeZone) { Instant connectedAt = Instant.parse("2026-07-10T13:21:42Z"); DeviceEntity entity = new DeviceEntity(); @@ -46,22 +46,22 @@ class DeviceTimeSerializationTest { assertAll( () -> assertTrue(payload.path("createDateTimestamp").isTextual(), - "Long 时间戳必须遵循现有 JSON 契约序列化为字符串"), + "Long timestamps must be serialized as strings per existing JSON contract"), () -> assertTrue(payload.path("lastConnectedAtTimestamp").isTextual(), - "Long 时间戳必须遵循现有 JSON 契约序列化为字符串"), + "Long timestamps must be serialized as strings per existing JSON contract"), () -> assertEquals(connectedAt, createDate, - "createDateTimestamp 必须保留源时间点"), + "createDateTimestamp must preserve source timestamp"), () -> assertEquals(connectedAt, lastConnectedAt, - "lastConnectedAtTimestamp 必须保留源时间点"), + "lastConnectedAtTimestamp must preserve the original timestamp"), () -> assertEquals(lastConnectedAt.atZone(browserZone).toLocalDateTime(), createDate.atZone(browserZone).toLocalDateTime(), - "绑定时间和最后连接时间在同一浏览器中必须显示为相同的本地时间"), + "Bound time and last connection time must display as the same local time in the same browser"), () -> assertTrue(payload.path("createDate").isTextual(), - "兼容字段 createDate 必须继续保留")); + "Retain the legacy field createDate for compatibility")); } @Test - @DisplayName("时间为空时新旧字段均保持 null") + @DisplayName("When time is empty, both old and new fields remain null") void nullDeviceTimesRemainNull() { DeviceEntity entity = new DeviceEntity(); DeviceServiceImpl deviceService = serviceReturning(entity); @@ -76,9 +76,9 @@ class DeviceTimeSerializationTest { () -> assertTrue(payload.path("createDate").isNull())); } - @ParameterizedTest(name = "自动升级状态 {0}") + @ParameterizedTest(name = "Auto-upgrade status {0}") @ValueSource(ints = { 0, 1 }) - @DisplayName("#3299 设备列表按 autoUpdate 契约返回真实开关状态") + @DisplayName("#3299 Device list returns actual toggle states per autoUpdate contract") void serializedDeviceContainsAutoUpdateState(int autoUpdate) { DeviceEntity entity = new DeviceEntity(); entity.setAutoUpdate(autoUpdate); @@ -92,7 +92,7 @@ class DeviceTimeSerializationTest { () -> assertEquals(autoUpdate, device.getAutoUpdate()), () -> assertEquals(autoUpdate, payload.path("autoUpdate").asInt()), () -> assertTrue(payload.path("otaUpgrade").isMissingNode(), - "设备列表不应继续暴露未映射的旧字段 otaUpgrade")); + "Device list should not continue exposing unmapped legacy field otaUpgrade")); } private DeviceServiceImpl serviceReturning(DeviceEntity entity) { diff --git a/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/MqttGatewayAuthorizationTest.java b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/MqttGatewayAuthorizationTest.java index c3644b5f7..e15d097c4 100644 --- a/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/MqttGatewayAuthorizationTest.java +++ b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/MqttGatewayAuthorizationTest.java @@ -30,7 +30,7 @@ import com.sun.net.httpserver.HttpServer; import cn.hutool.crypto.digest.DigestUtil; -@DisplayName("MQTT Gateway 日期鉴权回归测试") +@DisplayName("MQTT Gateway date authentication regression test") class MqttGatewayAuthorizationTest { private static final String SIGNATURE_KEY = "test-signature-key"; @@ -46,7 +46,7 @@ class MqttGatewayAuthorizationTest { } @Test - @DisplayName("以 UTC 日期生成当天、前一天和后一天三个候选 token") + @DisplayName("Generate three candidate tokens for today, yesterday, and tomorrow based on UTC date") void generatesUtcDateCandidates() { List tokens = MqttGatewayAuthorization.generateDailyTokens(SIGNATURE_KEY, FIXED_INSTANT); @@ -56,9 +56,9 @@ class MqttGatewayAuthorizationTest { tokenFor("2026-07-15")), tokens); } - @ParameterizedTest(name = "Gateway 时区 {0}") + @ParameterizedTest(name = "Gateway timezone {0}") @MethodSource("gatewayTimeZones") - @DisplayName("候选 token 覆盖上海和圣保罗 Gateway 的本地日期") + @DisplayName("Candidate tokens cover local dates for Shanghai and São Paulo Gateways") void coversGatewayLocalDate(String gatewayTimeZone, Instant now, int expectedTokenIndex) { String gatewayDate = now.atZone(ZoneId.of(gatewayTimeZone)).toLocalDate().toString(); List tokens = MqttGatewayAuthorization.generateDailyTokens(SIGNATURE_KEY, now); @@ -67,7 +67,7 @@ class MqttGatewayAuthorizationTest { } @Test - @DisplayName("仅在 401 时按日期候选重试并保留请求体") + @DisplayName("Retry with date candidates and preserve request body only on 401") void retriesOnlyAuthenticationFailures() throws IOException { AtomicInteger requestCount = new AtomicInteger(); List authorizationHeaders = new ArrayList<>(); @@ -98,7 +98,7 @@ class MqttGatewayAuthorizationTest { @ParameterizedTest(name = "HTTP {0}") @ValueSource(ints = { 403, 500 }) - @DisplayName("非 401 错误不重试且向上抛出") + @DisplayName("Do not retry non-401 errors and propagate them") void doesNotRetryNonAuthenticationFailure(int statusCode) throws IOException { AtomicInteger requestCount = new AtomicInteger(); startServer(exchange -> { @@ -117,7 +117,7 @@ class MqttGatewayAuthorizationTest { } @Test - @DisplayName("所有日期候选被拒绝时不把错误响应当作设备离线数据") + @DisplayName("Do not treat error responses as device offline data when all date candidates are rejected") void propagatesAuthenticationFailureAfterAllCandidatesAreRejected() throws IOException { AtomicInteger requestCount = new AtomicInteger(); startServer(exchange -> { @@ -135,10 +135,10 @@ class MqttGatewayAuthorizationTest { assertEquals(3, requestCount.get()); } - @ParameterizedTest(name = "密钥值 [{0}]") + @ParameterizedTest(name = "Key value [{0}]") @NullAndEmptySource @ValueSource(strings = { " ", "null", " NULL " }) - @DisplayName("缺少或占位签名密钥时在发起 HTTP 请求前失败") + @DisplayName("Fail before HTTP request if signature key is missing or placeholder") void rejectsMissingSignatureKeyBeforeSendingRequest(String signatureKey) { MqttGatewayAuthorization.GatewayRequestException exception = assertThrows( MqttGatewayAuthorization.GatewayRequestException.class, diff --git a/main/manager-api/src/test/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImplTest.java b/main/manager-api/src/test/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImplTest.java index 985bc8866..e0356c20c 100644 --- a/main/manager-api/src/test/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImplTest.java +++ b/main/manager-api/src/test/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImplTest.java @@ -27,10 +27,10 @@ class TimbreServiceImplTest { VoiceCloneDao voiceCloneDao = mock(VoiceCloneDao.class); TimbreServiceImpl service = new TimbreServiceImpl(timbreDao, voiceCloneDao, mock(RedisUtils.class)); TimbreEntity timbre = new TimbreEntity(); - timbre.setLanguages(",, ; 普通话;粤语"); + timbre.setLanguages(",, ; Mandarin; Cantonese"); when(timbreDao.selectById("voice-id")).thenReturn(timbre); - assertEquals("普通话", service.getDefaultLanguageById("voice-id")); + assertEquals("Mandarin", service.getDefaultLanguageById("voice-id")); verify(voiceCloneDao, never()).selectById("voice-id"); } @@ -41,7 +41,7 @@ class TimbreServiceImplTest { VoiceCloneDao voiceCloneDao = mock(VoiceCloneDao.class); TimbreServiceImpl service = new TimbreServiceImpl(timbreDao, voiceCloneDao, mock(RedisUtils.class)); VoiceCloneEntity voiceClone = new VoiceCloneEntity(); - voiceClone.setLanguages("、, English,中文"); + voiceClone.setLanguages(",, English, Chinese"); when(voiceCloneDao.selectById("clone-id")).thenReturn(voiceClone); assertEquals("English", service.getDefaultLanguageById("clone-id")); @@ -53,7 +53,7 @@ class TimbreServiceImplTest { VoiceCloneDao voiceCloneDao = mock(VoiceCloneDao.class); TimbreServiceImpl service = new TimbreServiceImpl(timbreDao, voiceCloneDao, mock(RedisUtils.class)); TimbreEntity timbre = new TimbreEntity(); - timbre.setLanguages(",,、;;;,,"); + timbre.setLanguages(",,,;;;,,"); when(timbreDao.selectById("voice-id")).thenReturn(timbre); assertNull(service.getDefaultLanguageById("voice-id")); @@ -100,7 +100,7 @@ class TimbreServiceImplTest { service.save(validTimbreData()); verify(timbreDao).insert(argThat((TimbreEntity entity) -> - "测试音色".equals(entity.getName()) && entity.getSort() == 0L)); + "Test voice".equals(entity.getName()) && entity.getSort() == 0L)); } @Test @@ -122,8 +122,8 @@ class TimbreServiceImplTest { private TimbreDataDTO validTimbreData() { TimbreDataDTO dto = new TimbreDataDTO(); - dto.setLanguages("中文"); - dto.setName("测试音色"); + dto.setLanguages("Chinese"); + dto.setName("Test voice"); dto.setTtsModelId("TTS_Test"); dto.setTtsVoice("test-voice"); return dto; diff --git a/main/manager-mobile/.editorconfig b/main/manager-mobile/.editorconfig index 7f0986477..9756adb2c 100644 --- a/main/manager-mobile/.editorconfig +++ b/main/manager-mobile/.editorconfig @@ -1,13 +1,13 @@ root = true -[*] # 表示所有文件适用 -charset = utf-8 # 设置文件字符集为 utf-8 -indent_style = space # 缩进风格(tab | space) -indent_size = 2 # 缩进大小 -end_of_line = lf # 控制换行类型(lf | cr | crlf) -trim_trailing_whitespace = true # 去除行首的任意空白字符 -insert_final_newline = true # 始终在文件末尾插入一个新行 +[*] # Indicates all files apply +charset = utf-8 # Set file character encoding to utf-8 +indent_style = space # Indentation style (tab | space) +indent_size = 2 # Indent size +end_of_line = lf # Control newline type (lf | cr | crlf) +trim_trailing_whitespace = true # Strip leading whitespace +insert_final_newline = true # Always insert a new line at the end of the file -[*.md] # 表示仅 md 文件适用以下规则 -max_line_length = off # 关闭最大行长度限制 -trim_trailing_whitespace = false # 关闭末尾空格修剪 +[*.md] # Indicates the following rules apply only to md files +max_line_length = off # Disable max line length limit +trim_trailing_whitespace = false # Disable trailing whitespace trimming diff --git a/main/manager-mobile/.gitignore b/main/manager-mobile/.gitignore index 34ddbdf3d..2b686e9b7 100644 --- a/main/manager-mobile/.gitignore +++ b/main/manager-mobile/.gitignore @@ -29,16 +29,16 @@ docs/.vitepress/cache src/types -# lock 文件还是不要了,我主要的版本写死就好了 +# Remove lock file; hardcode the main version instead # pnpm-lock.yaml # package-lock.json -# TIPS:如果某些文件已经加入了版本管理,现在重新加入 .gitignore 是不生效的,需要执行下面的操作 -# `git rm -r --cached .` 然后提交 commit 即可。 +# TIPS: If files are already tracked by version control, adding them to .gitignore now has no effect; perform the following steps instead +# `git rm -r --cached .` then commit the changes. -# git rm -r --cached file1 file2 ## 针对某些文件 -# git rm -r --cached dir1 dir2 ## 针对某些文件夹 -# git rm -r --cached . ## 针对所有文件 +# git rm -r --cached file1 file2 ## For specific files +# git rm -r --cached dir1 dir2 ## For specific folders +# git rm -r --cached . ## For all files -# 更新 uni-app 官方版本 +# Update to the official uni-app version. # npx @dcloudio/uvm@latest diff --git a/main/manager-mobile/src/api/agent/agent.ts b/main/manager-mobile/src/api/agent/agent.ts index bfaca352a..51b9a829e 100644 --- a/main/manager-mobile/src/api/agent/agent.ts +++ b/main/manager-mobile/src/api/agent/agent.ts @@ -12,7 +12,7 @@ import type { } from './types' import { http } from '@/http/request/alova' -// 获取智能体详情 +// Get agent details export function getAgentDetail(id: string) { return http.Get(`/agent/${id}`, { meta: { @@ -25,7 +25,7 @@ export function getAgentDetail(id: string) { }) } -// 获取角色模板列表 +// Get role template list export function getRoleTemplates() { return http.Get('/agent/template', { meta: { @@ -38,7 +38,7 @@ export function getRoleTemplates() { }) } -// 获取模型选项 +// Get model options export function getModelOptions(modelType: string, modelName: string = '') { return http.Get('/models/names', { params: { @@ -55,7 +55,7 @@ export function getModelOptions(modelType: string, modelName: string = '') { }) } -// 获取智能体列表 +// Get Agent list export function getAgentList() { return http.Get('/agent/list', { meta: { @@ -68,7 +68,7 @@ export function getAgentList() { }) } -// 创建智能体 +// Create Agent export function createAgent(data: AgentCreateData) { return http.Post('/agent', data, { meta: { @@ -78,7 +78,7 @@ export function createAgent(data: AgentCreateData) { }) } -// 删除智能体 +// Delete Agent export function deleteAgent(id: string) { return http.Delete(`/agent/${id}`, { meta: { @@ -88,7 +88,7 @@ export function deleteAgent(id: string) { }) } -// 获取TTS音色列表 +// Get TTS voice list export function getTTSVoices(ttsModelId: string, voiceName: string = '') { return http.Get(`/models/${ttsModelId}/voices`, { params: { @@ -104,7 +104,7 @@ export function getTTSVoices(ttsModelId: string, voiceName: string = '') { }) } -// 更新智能体 +// Update agent export function updateAgent(id: string, data: Partial & { tagNames?: string[] }) { return http.Put(`/agent/${id}`, data, { meta: { @@ -117,7 +117,7 @@ export function updateAgent(id: string, data: Partial & { tagNames? }) } -// 获取插件列表 +// Get plugin list export function getPluginFunctions() { return http.Get(`/models/provider/plugin/names`, { meta: { @@ -130,7 +130,7 @@ export function getPluginFunctions() { }) } -// 获取mcp接入点 +// Get MCP endpoint export function getMcpAddress(agentId: string) { return http.Get(`/agent/mcp/address/${agentId}`, { meta: { @@ -141,7 +141,7 @@ export function getMcpAddress(agentId: string) { }) } -// 获取mcp工具 +// Get MCP tools export function getMcpTools(agentId: string) { return http.Get(`/agent/mcp/tools/${agentId}`, { meta: { @@ -154,7 +154,7 @@ export function getMcpTools(agentId: string) { }) } -// 获取声纹列表 +// Get voiceprint list export function getVoicePrintList(agentId: string) { return http.Get(`/agent/voice-print/list/${agentId}`, { meta: { @@ -167,7 +167,7 @@ export function getVoicePrintList(agentId: string) { }) } -// 获取语音对话记录 +// Get voice conversation records export function getChatHistoryUser(agentId: string) { return http.Get(`/agent/${agentId}/chat-history/user`, { meta: { @@ -180,7 +180,7 @@ export function getChatHistoryUser(agentId: string) { }) } -// 新增声纹说话人 +// Add voiceprint speaker export function createVoicePrint(data: { agentId: string, audioId: string, sourceName: string, introduce: string }) { return http.Post('/agent/voice-print', data, { meta: { @@ -190,7 +190,7 @@ export function createVoicePrint(data: { agentId: string, audioId: string, sourc }) } -// 获取智能体标签 +// Get agent tags export function getAgentTags(agentId: string) { return http.Get(`/agent/${agentId}/tags`, { meta: { @@ -203,7 +203,7 @@ export function getAgentTags(agentId: string) { }) } -// 更新智能体标签 +// Update agent tag export function updateAgentTags(agentId: string, data) { return http.Put(`/agent/${agentId}/tags`, data, { meta: { @@ -213,7 +213,7 @@ export function updateAgentTags(agentId: string, data) { }) } -// 获取所有语言 +// Get all languages export function getAllLanguage(modelId: string) { return http.Get(`/models/${modelId}/voices`, { meta: { @@ -227,8 +227,8 @@ export function getAllLanguage(modelId: string) { } /** - * 获取克隆音色的临时播放ID - * @param cloneId 克隆音色记录ID + * Get temporary playback ID for cloned voice + * @param cloneId Cloned voice record ID */ export function getVoiceCloneAudioId(cloneId: string) { return http.Post(`/voiceClone/audio/${cloneId}`, {}, { @@ -239,7 +239,7 @@ export function getVoiceCloneAudioId(cloneId: string) { }) } -// 获取智能体历史版本列表 +// Get agent history version list export function getAgentSnapshots(agentId: string, params: AgentSnapshotPageParams) { return http.Get>(`/agent/${agentId}/snapshots`, { params, @@ -253,7 +253,7 @@ export function getAgentSnapshots(agentId: string, params: AgentSnapshotPagePara }) } -// 获取智能体历史版本详情 +// Get agent history version details export function getAgentSnapshot(agentId: string, snapshotId: string) { return http.Get(`/agent/${agentId}/snapshots/${snapshotId}`, { meta: { @@ -266,7 +266,7 @@ export function getAgentSnapshot(agentId: string, snapshotId: string) { }) } -// 恢复智能体历史版本 +// Restore agent historical version export function restoreAgentSnapshot(agentId: string, snapshotId: string, currentStateToken: string) { return http.Post(`/agent/${agentId}/snapshots/${snapshotId}/restore`, { currentStateToken }, { meta: { @@ -276,7 +276,7 @@ export function restoreAgentSnapshot(agentId: string, snapshotId: string, curren }) } -// 删除智能体历史版本 +// Delete agent history version export function deleteAgentSnapshot(agentId: string, snapshotId: string) { return http.Delete(`/agent/${agentId}/snapshots/${snapshotId}`, { meta: { @@ -286,7 +286,7 @@ export function deleteAgentSnapshot(agentId: string, snapshotId: string) { }) } -// 获取所有替换词文件 +// Get all replacement word files export function getCorrectWordFiles() { return http.Get('/correct-word/file/select', { meta: { diff --git a/main/manager-mobile/src/api/agent/types.ts b/main/manager-mobile/src/api/agent/types.ts index 440f50708..f4ed5b57e 100644 --- a/main/manager-mobile/src/api/agent/types.ts +++ b/main/manager-mobile/src/api/agent/types.ts @@ -1,4 +1,4 @@ -// 智能体列表数据类型 +// Agent list data type export interface Agent { id: string agentName: string @@ -14,12 +14,12 @@ export interface Agent { tags: Record[] } -// 智能体创建数据类型 +// Agent creation data type export interface AgentCreateData { agentName: string } -// 智能体详情数据类型 +// Agent details data type export interface AgentDetail { id: string userId: string @@ -122,7 +122,7 @@ export interface TtsVoice { isClone?: boolean | null } -// 角色模板数据类型 +// Role template data type export interface RoleTemplate { id: string agentCode: string @@ -148,7 +148,7 @@ export interface RoleTemplate { updatedAt: string } -// 模型选项数据类型 +// Model option data type export interface ModelOption { id: string modelName: string @@ -168,7 +168,7 @@ export interface PluginDefinition { modelType: string providerCode: string name: string - fields: PluginField[] // 注意:原始是字符串,需要先 JSON.parse + fields: PluginField[] // Note: Original is a string; JSON.parse is required first sort: number updater: string updateDate: string diff --git a/main/manager-mobile/src/pages.json b/main/manager-mobile/src/pages.json index 06999ccca..7576c6f72 100644 --- a/main/manager-mobile/src/pages.json +++ b/main/manager-mobile/src/pages.json @@ -97,7 +97,7 @@ "type": "page", "layout": "default", "style": { - "navigationBarTitleText": "编辑源", + "navigationBarTitleText": "Edit source", "navigationStyle": "custom" } }, @@ -106,7 +106,7 @@ "type": "page", "layout": "default", "style": { - "navigationBarTitleText": "语音设置", + "navigationBarTitleText": "Voice Settings", "navigationStyle": "custom" } }, @@ -194,7 +194,7 @@ "type": "page", "layout": "default", "style": { - "navigationBarTitleText": "设置", + "navigationBarTitleText": "Settings", "navigationStyle": "custom" } }, diff --git a/main/manager-mobile/src/pages/agent/components/agentSnapshotUtils.test.mjs b/main/manager-mobile/src/pages/agent/components/agentSnapshotUtils.test.mjs index a75e25dc2..803febf13 100644 --- a/main/manager-mobile/src/pages/agent/components/agentSnapshotUtils.test.mjs +++ b/main/manager-mobile/src/pages/agent/components/agentSnapshotUtils.test.mjs @@ -19,7 +19,7 @@ test('rejects empty TTS metadata while keeping language-less voices selectable w assert.equal(hasUsableTtsVoiceMetadata([]), false) assert.equal(hasUsableTtsVoiceMetadata(voices), true) assert.deepEqual(filterTtsVoicesByLanguage(voices, ''), voices) - assert.deepEqual(filterTtsVoicesByLanguage(voices, 'zh-CN'), []) + assert.deepEqual(filterTtsVoicesByLanguage(voices, 'en-US'), []) }) test('keeps inherited TTS values distinct from explicit zero', () => { diff --git a/main/manager-mobile/src/pages/agent/edit.vue b/main/manager-mobile/src/pages/agent/edit.vue index ce2f90e4c..50fd625cb 100644 --- a/main/manager-mobile/src/pages/agent/edit.vue +++ b/main/manager-mobile/src/pages/agent/edit.vue @@ -18,14 +18,14 @@ const props = withDefaults(defineProps(), { agentId: '', }) -// 组件参数 +// Component parameters interface Props { agentId?: string } const agentId = computed(() => props.agentId) -// 表单数据 +// Form data const formData = ref>({ agentName: '', systemPrompt: '', @@ -45,9 +45,9 @@ const formData = ref>({ ttsPitch: 0, }) -// 显示名称数据 +// Display name data const displayNames = ref({ -// 显示名称数据 +// Display name data vad: t('agent.pleaseSelect'), asr: t('agent.pleaseSelect'), llm: t('agent.pleaseSelect'), @@ -61,11 +61,11 @@ const displayNames = ref({ language: t('agent.pleaseSelect'), }) -// 角色模板数据 +// Role template data const roleTemplates = ref([]) const selectedTemplateId = ref('') -// 加载状态 +// Loading status const loading = ref(false) const saving = ref(false) const showSnapshotPanel = ref(false) @@ -73,7 +73,7 @@ const currentVersionNo = ref(null) const snapshotReloadBlocked = ref(false) const snapshotReloadFailed = ref(false) -// 模型选项数据 +// Model option data const modelOptions = ref<{ [key: string]: ModelOption[] }>({ @@ -96,18 +96,18 @@ interface VoiceOption { train_status?: number } -// 音色选项数据 +// Voice option data const voiceOptions = ref([]) -// 保存完整的音色信息 +// Save complete voice info const voiceDetails = ref>({}) -// 上报模式选项数据 +// Report mode option data const reportOptions = [ { name: t('agent.reportText'), value: 1 }, { name: t('agent.reportTextVoice'), value: 2 }, ] -// 选择器显示状态 +// Selector display state const pickerShow = ref<{ [key: string]: boolean }>({ @@ -148,12 +148,12 @@ interface SnapshotRestoreContext { actionSequence: number } -// 音频播放相关 +// Audio playback related const audioRef = ref(null) const playingVoiceId = ref('') const voicePreviewRequestGate = createVoicePreviewRequestGate() -// 使用插件store +// Use plugin store const pluginStore = usePluginStore() const speedPitchStore = useSpeedPitch() const providerStore = useProvider() @@ -286,7 +286,7 @@ function handleInputConfirm() { inputVisible.value = false } -// 是否禁用历史记忆输入框 +// Is history memory input disabled const isMemoryDisabled = computed(() => formData.value.memModelId !== 'Memory_mem_local_short') function normalizeFunctionParams(paramInfo: any) { @@ -311,7 +311,7 @@ function normalizeAgentFunctions(functions: any[] = []) { })) } -// 打开上下文源编辑弹窗 +// Open context source edit dialog function openContextProviderDialog() { uni.navigateTo({ url: '/pages/agent/provider', @@ -324,7 +324,7 @@ function handleRegulate() { }) } -// 加载智能体详情 +// Load agent details async function loadAgentDetail(targetAgentId = agentId.value) { if (!targetAgentId) return false @@ -343,7 +343,7 @@ async function loadAgentDetail(targetAgentId = agentId.value) { } catch (error) { if (isActiveAgentDetailRequest(targetAgentId, requestId)) { - console.error('加载智能体详情失败:', error) + console.error('Failed to load Agent details:', error) toast.error(t('agent.loadFail')) } return false @@ -416,28 +416,28 @@ function invalidateTtsMetadataRequest() { ttsOptionsModelId.value = '' } -// 获取音色显示名称 +// Get voice display name function getVoiceDisplayName(ttsVoiceId: string) { if (!ttsVoiceId) return t('agent.pleaseSelect') - console.log('=== 音色映射调试 ===') - console.log('当前音色ID:', ttsVoiceId) - console.log('当前TTS模型:', formData.value.ttsModelId) - console.log('可用音色选项:', voiceOptions.value) + console.log('=== Voice mapping debug ===') + console.log('Current voice ID:', ttsVoiceId) + console.log('Current TTS model:', formData.value.ttsModelId) + console.log('Available voice options:', voiceOptions.value) - // 首先尝试直接从音色选项中匹配ID + // First try to match ID directly from voice options const voice = voiceOptions.value.find(v => v.id === ttsVoiceId) if (voice) { - console.log('直接匹配成功:', voice) + console.log('Direct match succeeded:', voice) return voice.name } - // 如果没找到,尝试兼容性映射 + // If not found, try compatibility mapping if (voiceOptions.value.length > 0) { - console.log('直接匹配失败,尝试兼容性映射') + console.log('Direct match failed, trying compatibility mapping') - // 创建索引映射:voice1 → 第1个音色,voice2 → 第2个音色 + // Create index mapping: voice1 -> 1st voice, voice2 -> 2nd voice const indexMap = { voice1: 0, voice2: 1, @@ -449,16 +449,16 @@ function getVoiceDisplayName(ttsVoiceId: string) { const index = indexMap[ttsVoiceId] if (index !== undefined && voiceOptions.value[index]) { const mappedVoice = voiceOptions.value[index] - console.log(`索引映射: ${ttsVoiceId} → index ${index} → ${mappedVoice.name}`) + console.log(`Index mapping: ${ttsVoiceId} → index ${index} → ${mappedVoice.name}`) return mappedVoice.name } } - console.log('所有映射方式都失败,返回原始ID:', ttsVoiceId) + console.log('All mapping methods failed, returning original ID:', ttsVoiceId) return ttsVoiceId } -// 更新显示名称 +// Update display name function updateDisplayNames() { if (!formData.value) return @@ -472,46 +472,46 @@ function updateDisplayNames() { displayNames.value.memory = getModelDisplayName('Memory', formData.value.memModelId) displayNames.value.tts = getModelDisplayName('TTS', formData.value.ttsModelId) - // 角色音色特殊处理 + // Special handling for role voice displayNames.value.report = reportOptions.find(item => item.value === formData.value.chatHistoryConf)?.name isVisibleReport.value = formData.value.memModelId !== 'Memory_nomem' - console.log('最终音色显示名称:', displayNames.value.voiceprint) + console.log('Final voice display name:', displayNames.value.voiceprint) } -// 加载角色模板 +// Load role templates async function loadRoleTemplates() { try { const templates = await getRoleTemplates() roleTemplates.value = templates } catch (error) { - console.error('加载角色模板失败:', error) + console.error('Failed to load role templates:', error) } } -// 加载模型选项 +// Load model options async function loadModelOptions() { const modelTypes = ['VAD', 'ASR', 'LLM', 'VLLM', 'Intent', 'Memory', 'TTS'] try { await Promise.all( modelTypes?.map(async (type) => { - console.log(`加载模型类型: ${type}`) + console.log(`Loading model type: ${type}`) const options = await getModelOptions(type) modelOptions.value[type] = options - console.log(`${type} 选项:`, options) + console.log(`${type} options:`, options) }) || [], ) - console.log('所有模型选项加载完成:', modelOptions.value) + console.log('All model options loaded:', modelOptions.value) } catch (error) { - console.error('加载模型选项失败:', error) + console.error('Failed to load model options:', error) } } -// 根据语言筛选音色 +// Filter voices by language interface VoiceSelectionOptions { autoSelectVoice?: boolean preferredLanguage?: string | null @@ -580,7 +580,7 @@ function filterVoicesByLanguage(options: VoiceSelectionOptions = {}) { const allVoices = Object.values(voiceDetails.value) - // 根据选中的语言筛选音色 + // Filter voices by selected language const filteredVoices = filterTtsVoicesByLanguage(allVoices, selectedTtsLanguage.value) voiceOptions.value = filteredVoices.map(voice => ({ @@ -592,7 +592,7 @@ function filterVoicesByLanguage(options: VoiceSelectionOptions = {}) { train_status: voice.trainStatus, })) - // 检查当前选中的音色是否支持当前语言,如果不支持则选择第一个 + // Check if the currently selected voice supports the current language; if not, select the first one const currentVoiceSupportsLanguage = formData.value.ttsVoiceId && filteredVoices.some(voice => voice.id === formData.value.ttsVoiceId) @@ -618,7 +618,7 @@ function getVoiceDefaultLanguage(ttsVoiceId: string) { return languages[0] || '' } -// 根据语音合成模型加载语言 +// Load language based on text-to-speech model async function fetchAllLanguag(ttsModelId: string, options: VoiceSelectionOptions = {}): Promise<'loaded' | 'failed' | 'stale'> { const requestId = ++ttsOptionsRequestSequence ttsOptionsLoading.value = true @@ -636,12 +636,12 @@ async function fetchAllLanguag(ttsModelId: string, options: VoiceSelectionOption if (!hasUsableTtsVoiceMetadata(res)) { throw new Error('No TTS voice metadata is available') } - // 保存完整的音色信息 + // Save complete voice info voiceDetails.value = res.reduce>((acc, voice) => { acc[voice.id] = voice return acc }, {}) - // 提取所有语言选项并去重 + // Extract and deduplicate all language options const allLanguages = new Set() res.forEach((voice) => { if (voice.languages) { @@ -662,7 +662,7 @@ async function fetchAllLanguag(ttsModelId: string, options: VoiceSelectionOption // exposes no language dimension. selectedTtsLanguage.value = '' displayNames.value.language = '' - // 优先使用调用方指定的语言或音色默认语言,再回退到智能体当前配置 + // Prefer the language specified by the caller or the voice's default language, then fall back to the Agent's current config if (requestedLanguage && languageOptions.value.some(option => option.value === requestedLanguage)) { selectedTtsLanguage.value = requestedLanguage displayNames.value.language = requestedLanguage @@ -684,7 +684,7 @@ async function fetchAllLanguag(ttsModelId: string, options: VoiceSelectionOption displayNames.value.language = languageOptions.value[0].value } - // 根据选中的语言筛选音色 + // Filter voices by selected language filterVoicesByLanguage(options) ttsOptionsModelId.value = ttsModelId return 'loaded' @@ -703,24 +703,24 @@ async function fetchAllLanguag(ttsModelId: string, options: VoiceSelectionOption } } -// 加载TTS音色选项 +// Load TTS voice options // async function loadVoiceOptions(ttsModelId?: string) { // if (!ttsModelId) // return // try { -// console.log(`加载音色选项: ${ttsModelId}`) +// console.log(`Loading voice options: ${ttsModelId}`) // const voices = await getTTSVoices(ttsModelId) // voiceOptions.value = voices -// console.log('音色选项:', voices) +// console.log('Voice options:', voices) // } // catch (error) { -// console.error('加载音色选项失败:', error) +// console.error('Failed to load voice options:', error) // voiceOptions.value = [] // } // } -// 选择角色模板 +// Select role template async function selectRoleTemplate(templateId: string) { if (ttsOptionsLoading.value) { return @@ -777,7 +777,7 @@ async function selectRoleTemplate(templateId: string) { } } -// 打开选择器 +// Open selector function openPicker(type: string) { if (ttsOptionsLoading.value && (type === 'tts' || type === 'language' || type === 'voiceprint')) { return @@ -785,12 +785,12 @@ function openPicker(type: string) { pickerShow.value[type] = true } -// 选择器确认 +// Selector confirmed async function onPickerConfirm(type: string, value: any, name: string) { - console.log('选择器确认:', type, value, name) + console.log('Selector confirmed:', type, value, name) const previousTtsState = type === 'tts' ? captureTtsSelectionState() : null - // 保存显示名称 + // Save display name displayNames.value[type] = name switch (type) { @@ -811,12 +811,12 @@ async function onPickerConfirm(type: string, value: any, name: string) { break case 'intent': formData.value.intentModelId = value - displayNames.value.intent = name // 确保显示名称正确更新 + displayNames.value.intent = name // Ensure display name updates correctly break case 'memory': formData.value.memModelId = value formData.value.chatHistoryConf = value === 'Memory_nomem' ? 0 : 2 - displayNames.value.memory = name // 确保显示名称正确更新 + displayNames.value.memory = name // Ensure display name updates correctly displayNames.value.report = reportOptions[1].name isVisibleReport.value = value !== 'Memory_nomem' if (value === 'Memory_nomem' || value === 'Memory_mem_report_only') { @@ -856,7 +856,7 @@ async function onPickerConfirm(type: string, value: any, name: string) { formData.value.ttsLanguage = selectedTtsLanguage.value ttsLanguageTouched.value = true } - displayNames.value.voiceprint = name // 确保显示名称正确更新 + displayNames.value.voiceprint = name // Ensure display name updates correctly break case 'report': formData.value.chatHistoryConf = value @@ -866,30 +866,30 @@ async function onPickerConfirm(type: string, value: any, name: string) { pickerShow.value[type] = false } -// 选择器取消 +// Selector canceled function onPickerCancel(type: string) { pickerShow.value[type] = false - // 关闭时停止播放 + // Stop playback on close if (type === 'voiceprint') { stopAudio() } } -// 播放音频 +// Play audio async function playAudio(voice: VoiceOption, event: Event) { - event.stopPropagation() // 阻止事件冒泡,防止关闭下拉框 + event.stopPropagation() // Prevent event bubbling to avoid closing the dropdown if (!hasVoicePreview(voice)) { return } - // 如果正在播放同一个音频,则停止 + // If playing the same audio, stop playback if (playingVoiceId.value === voice.value) { stopAudio() return } - // 停止之前的音频 + // Stop previous audio stopAudio() const requestId = voicePreviewRequestGate.begin() playingVoiceId.value = voice.value @@ -901,7 +901,7 @@ async function playAudio(voice: VoiceOption, event: Event) { voiceDemo: voice.voiceDemo || voice.voice_demo, }, getVoiceCloneAudioId, getEnvBaseUrl()) - // 用户可能在等待克隆音色临时地址时取消或切换了音色。 + // User may have cancelled or switched voices while waiting for the cloned voice temporary URL. if (!voicePreviewRequestGate.isCurrent(requestId) || playingVoiceId.value !== voice.value) { return } @@ -911,12 +911,12 @@ async function playAudio(voice: VoiceOption, event: Event) { return } - // 创建新的音频实例 + // Create new audio instance const audio = uni.createInnerAudioContext() audioRef.value = audio audio.src = audioUrl - // 监听播放结束 + // Listen for playback end audio.onEnded(() => { if ( voicePreviewRequestGate.isCurrent(requestId) @@ -927,7 +927,7 @@ async function playAudio(voice: VoiceOption, event: Event) { } }) - // 监听播放错误 + // Listen for playback error audio.onError(() => { if ( voicePreviewRequestGate.isCurrent(requestId) @@ -939,29 +939,29 @@ async function playAudio(voice: VoiceOption, event: Event) { } }) - // 播放音频 + // Play audio audio.play() } catch (error) { if (!voicePreviewRequestGate.isCurrent(requestId) || playingVoiceId.value !== voice.value) { return } - console.error('获取克隆音色试听地址失败:', error) + console.error('Failed to get cloned voice preview URL:', error) toast.error(t('voiceprint.getAudioFailed')) playingVoiceId.value = '' }) - // 监听播放错误 + // Listen for playback error audioRef.value.onError(() => { toast.error(t('chatHistory.audioPlayFailed')) playingVoiceId.value = '' }) - // 播放音频 + // Play audio audioRef.value.play() } -// 停止音频 +// Stop audio function stopAudio() { voicePreviewRequestGate.invalidate() if (audioRef.value) { @@ -972,12 +972,12 @@ function stopAudio() { playingVoiceId.value = '' } -// 获取模型显示名称 +// Get model display name function getModelDisplayName(modelType: string, modelId: string) { if (!modelId) return t('agent.pleaseSelect') - // 直接从API配置数据中查找匹配的ID + // Look up matching ID directly from API config data const options = modelOptions.value[modelType] if (!options || options.length === 0) { @@ -991,7 +991,7 @@ function getModelDisplayName(modelType: string, modelId: string) { return modelId } -// 保存智能体 +// Save Agent async function saveAgent() { if (saving.value) { return @@ -1029,7 +1029,7 @@ async function saveAgent() { saving.value = true const tagNames = dynamicTags.value.map(tag => tag.tagName) const tagsChanged = !isSameStringList(tagNames, originalTagNames.value) - // 构建保存数据,包含上下文配置和语音设置 + // Build save data including context config and voice settings const saveData: Record = { ...formData.value, contextProviders: providerStore.providers, @@ -1069,7 +1069,7 @@ async function saveAgent() { toast.success(t('agent.saveSuccess')) } catch (error) { - console.error('保存失败:', error) + console.error('Save failed:', error) toast.error(t('agent.saveFail')) } finally { @@ -1089,15 +1089,15 @@ function loadPluginFunctions() { }) || [] allFunctions.value = processedFunctions - // 同时更新到store + // Also update to store pluginStore.setAllFunctions(processedFunctions) }) } function handleTools() { - console.log('当前插件配置:', formData.value.functions) + console.log('Current plugin config:', formData.value.functions) - // 确保store中有最新数据 + // Ensure store contains latest data pluginStore.setCurrentAgentId(agentId.value) pluginStore.setCurrentFunctions(normalizeAgentFunctions(formData.value.functions || [])) pluginStore.setAllFunctions(allFunctions.value) @@ -1107,7 +1107,7 @@ function handleTools() { }) } -// 获取智能体标签 +// Get agent tags async function loadAgentTags(targetAgentId = agentId.value) { if (!targetAgentId) { return false @@ -1124,7 +1124,7 @@ async function loadAgentTags(targetAgentId = agentId.value) { } catch (error) { if (isActiveAgentTagRequest(targetAgentId, requestId)) { - console.error('加载智能体标签失败:', error) + console.error('Failed to load Agent tags:', error) } return false } @@ -1180,7 +1180,7 @@ async function reloadAgentAfterSnapshotRestore(targetAgentId = agentId.value) { } catch (error) { if (isActiveSnapshotReload(targetAgentId, reloadId, detailRequestId, tagRequestId)) { - console.error('恢复后重新加载智能体失败:', error) + console.error('Failed to reload Agent after recovery:', error) snapshotReloadFailed.value = true toast.error(t('agentSnapshot.reloadAfterRestoreFailed')) } @@ -1227,7 +1227,7 @@ function isSameStringList(left: string[], right: string[]) { return left.every((value, index) => value === right[index]) } -// 监听store中的插件配置变化 +// Listen for plugin config changes in the store. watch(() => pluginStore.currentFunctions, (newFunctions) => { formData.value.functions = normalizeAgentFunctions(newFunctions || []) }, { deep: true }) @@ -1253,14 +1253,14 @@ watch(agentId, (currentAgentId, previousAgentId) => { onMounted(async () => { loadAgentTags() - // 先加载模型选项和角色模板 + // Load model options and character templates first await Promise.all([ loadRoleTemplates(), loadModelOptions(), loadPluginFunctions(), ]) - // 然后加载智能体详情,这样可以正确映射显示名称 + // Then load agent details to ensure correct display name mapping if (agentId.value && !snapshotReloadBlocked.value) { await loadAgentDetail() } @@ -1289,14 +1289,14 @@ onMounted(async () => { - - + @@ -1386,14 +1386,14 @@ onMounted(async () => { - + {{ t('agent.modelConfig') }} - + @@ -1478,14 +1478,14 @@ onMounted(async () => { - + {{ t('agent.voiceSettings') }} - + @@ -1538,14 +1538,14 @@ onMounted(async () => { - + {{ t('agent.historyMemory') }} - +