From eb4b6bfecc88fac2dafc6cd1e32c73449fcee888 Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Thu, 21 Aug 2025 18:32:00 +0530 Subject: [PATCH] server connecting with db properly --- main/manager-api/README.md | 14 +- .../database-interactive-schema.html | 917 + .../manager-api/database-network-diagram.html | 1512 ++ .../database-relationship-matrix.md | 201 + .../database-schema-documentation.md | 422 + main/manager-api/database-visual-schema.md | 366 + main/manager-api/pom.xml | 18 +- main/manager-api/railway-setup.md | 78 + .../xiaozhi/common/constant/Constant.java | 12 +- .../java/xiaozhi/common/utils/JsonRpcTwo.java | 21 + .../java/xiaozhi/common/utils/JsonUtils.java | 1 + .../agent/Enums/AgentChatHistoryType.java | 21 + .../agent/Enums/XiaoZhiMcpJsonRpcJson.java | 44 + .../agent/controller/AgentController.java | 28 + .../controller/AgentVoicePrintController.java | 86 + .../modules/agent/dao/AgentVoicePrintDao.java | 20 + .../agent/dto/AgentVoicePrintSaveDTO.java | 28 + .../agent/dto/AgentVoicePrintUpdateDTO.java | 28 + .../agent/dto/IdentifyVoicePrintResponse.java | 21 + .../modules/agent/dto/McpJsonRpcRequest.java | 32 - .../agent/entity/AgentVoicePrintEntity.java | 64 + .../service/AgentChatHistoryService.java | 27 + .../agent/service/AgentVoicePrintService.java | 50 + .../impl/AgentChatHistoryServiceImpl.java | 78 + .../impl/AgentMcpAccessPointServiceImpl.java | 113 +- .../agent/service/impl/AgentServiceImpl.java | 27 + .../impl/AgentVoicePrintServiceImpl.java | 410 + .../agent/vo/AgentChatHistoryUserVO.java | 16 + .../modules/agent/vo/AgentVoicePrintVO.java | 33 + .../service/impl/ConfigServiceImpl.java | 101 +- .../device/controller/OTAController.java | 13 +- .../device/dto/DeviceReportRespDTO.java | 20 - .../service/impl/DeviceServiceImpl.java | 18 - .../device/service/impl/OtaServiceImpl.java | 2 +- .../model/controller/ModelController.java | 14 +- .../model/dto/LlmModelBasicInfoDTO.java | 13 + .../model/service/ModelConfigService.java | 3 + .../service/impl/ModelConfigServiceImpl.java | 38 + .../sys/controller/SysParamsController.java | 39 +- .../sys/service/impl/SysUserServiceImpl.java | 2 +- .../sys/utils/WebSocketClientManager.java | 56 +- .../src/main/resources/application-dev.yml | 30 +- .../main/resources/application-railway.yml | 61 + .../src/main/resources/application.properties | 3 - .../src/main/resources/application.yml | 10 +- .../resources/db/changelog/202507031602.sql | 4 + .../resources/db/changelog/202507041018.sql | 12 + .../resources/db/changelog/202507051233.sql | 5 - .../resources/db/changelog/202507071130.sql | 26 + .../resources/db/changelog/202507071530.sql | 56 + .../resources/db/changelog/202507081646.sql | 3 + .../resources/db/changelog/202507101203.sql | 38 + .../resources/db/changelog/202508081701.sql | 32 + .../resources/db/changelog/202508111734.sql | 16 + .../resources/db/changelog/202508131557.sql | 26 + .../resources/db/changelog/202508141200.sql | 7 - .../changelog/add_english_sherpa_models.sql | 19 - .../db/changelog/db.changelog-master.yaml | 64 +- .../mapper/security/SysUserTokenDao.xml | 4 +- .../resources/mapper/sys/SysParamsDao.xml | 2 +- main/manager-mobile/.commitlintrc.cjs | 3 + main/manager-mobile/.editorconfig | 13 + main/manager-mobile/.gitignore | 44 + main/manager-mobile/.npmrc | 8 + main/manager-mobile/LICENSE | 21 + main/manager-mobile/README.md | 170 + main/manager-mobile/eslint.config.mjs | 43 + main/manager-mobile/favicon.ico | Bin 0 -> 14575 bytes main/manager-mobile/index.html | 26 + main/manager-mobile/manifest.config.ts | 155 + main/manager-mobile/pages.config.ts | 23 + .../patches/@dcloudio__uni-h5.patch | 13 + main/manager-mobile/pnpm-lock.yaml | 14866 ++++++++++++++++ main/manager-mobile/pnpm-workspace.yaml | 6 + main/manager-mobile/scripts/postupgrade.js | 35 + main/manager-mobile/src/App.vue | 39 + main/manager-mobile/src/api/agent/agent.ts | 185 + main/manager-mobile/src/api/agent/types.ts | 107 + main/manager-mobile/src/api/auth.ts | 127 + .../src/api/chat-history/chat-history.ts | 60 + .../src/api/chat-history/index.ts | 2 + .../src/api/chat-history/types.ts | 38 + main/manager-mobile/src/api/device/device.ts | 55 + main/manager-mobile/src/api/device/index.ts | 2 + main/manager-mobile/src/api/device/types.ts | 21 + .../src/api/voiceprint/index.ts | 2 + .../src/api/voiceprint/types.ts | 29 + .../src/api/voiceprint/voiceprint.ts | 62 + main/manager-mobile/src/components/.gitkeep | 0 .../src/components/custom-tabs/index.vue | 131 + main/manager-mobile/src/env.d.ts | 34 + main/manager-mobile/src/hooks/.gitkeep | 0 main/manager-mobile/src/hooks/usePageAuth.ts | 50 + main/manager-mobile/src/hooks/useRequest.ts | 51 + main/manager-mobile/src/hooks/useUpload.ts | 160 + main/manager-mobile/src/http/README.md | 36 + main/manager-mobile/src/http/request/alova.ts | 120 + main/manager-mobile/src/http/request/enum.ts | 66 + main/manager-mobile/src/http/request/types.ts | 22 + main/manager-mobile/src/layouts/default.vue | 17 + .../src/layouts/fg-tabbar/fg-tabbar.vue | 68 + .../src/layouts/fg-tabbar/tabbar.md | 17 + .../src/layouts/fg-tabbar/tabbar.ts | 11 + .../src/layouts/fg-tabbar/tabbarList.ts | 76 + main/manager-mobile/src/layouts/tabbar.vue | 19 + main/manager-mobile/src/main.ts | 19 + .../src/pages-sub/demo/index.vue | 27 + main/manager-mobile/src/pages/agent/edit.vue | 701 + main/manager-mobile/src/pages/agent/index.vue | 214 + main/manager-mobile/src/pages/agent/tools.vue | 584 + .../src/pages/chat-history/detail.vue | 331 + .../src/pages/chat-history/index.vue | 399 + .../components/ultrasonic-config.vue | 684 + .../device-config/components/wifi-config.vue | 230 + .../components/wifi-selector.vue | 556 + .../src/pages/device-config/index.vue | 146 + .../manager-mobile/src/pages/device/index.vue | 333 + main/manager-mobile/src/pages/index/index.vue | 578 + main/manager-mobile/src/pages/login/index.vue | 824 + .../src/pages/register/index.vue | 878 + .../src/pages/settings/index.vue | 380 + .../src/pages/voiceprint/index.vue | 512 + main/manager-mobile/src/router/interceptor.ts | 66 + .../src/static/app/icons/1024x1024.png | Bin 0 -> 458242 bytes .../src/static/app/icons/120x120.png | Bin 0 -> 17805 bytes .../src/static/app/icons/144x144.png | Bin 0 -> 24176 bytes .../src/static/app/icons/152x152.png | Bin 0 -> 26428 bytes .../src/static/app/icons/167x167.png | Bin 0 -> 30883 bytes .../src/static/app/icons/180x180.png | Bin 0 -> 35063 bytes .../src/static/app/icons/192x192.png | Bin 0 -> 38903 bytes .../src/static/app/icons/20x20.png | Bin 0 -> 1330 bytes .../src/static/app/icons/29x29.png | Bin 0 -> 1471 bytes .../src/static/app/icons/40x40.png | Bin 0 -> 1709 bytes .../src/static/app/icons/58x58.png | Bin 0 -> 2210 bytes .../src/static/app/icons/60x60.png | Bin 0 -> 2275 bytes .../src/static/app/icons/72x72.png | Bin 0 -> 2708 bytes .../src/static/app/icons/76x76.png | Bin 0 -> 2833 bytes .../src/static/app/icons/80x80.png | Bin 0 -> 2962 bytes .../src/static/app/icons/87x87.png | Bin 0 -> 3266 bytes .../src/static/app/icons/96x96.png | Bin 0 -> 3680 bytes .../manager-mobile/src/static/images/.gitkeep | 0 .../src/static/images/default-avatar.png | Bin 0 -> 560 bytes .../src/static/images/home/main-top-bg.png | Bin 0 -> 978384 bytes main/manager-mobile/src/static/logo.png | Bin 0 -> 13372 bytes main/manager-mobile/src/static/logo.svg | 33 + .../manager-mobile/src/static/tabbar/chat.png | Bin 0 -> 2153 bytes .../src/static/tabbar/chat_activate.png | Bin 0 -> 2155 bytes .../src/static/tabbar/device.png | Bin 0 -> 4058 bytes .../src/static/tabbar/device_activate.png | Bin 0 -> 4040 bytes .../src/static/tabbar/example.png | Bin 0 -> 1371 bytes .../src/static/tabbar/exampleHL.png | Bin 0 -> 1398 bytes .../manager-mobile/src/static/tabbar/home.png | Bin 0 -> 1346 bytes .../src/static/tabbar/homeHL.png | Bin 0 -> 1415 bytes .../src/static/tabbar/microphone.png | Bin 0 -> 3189 bytes .../src/static/tabbar/microphone_activate.png | Bin 0 -> 3273 bytes .../src/static/tabbar/network.png | Bin 0 -> 6593 bytes .../src/static/tabbar/network_activate.png | Bin 0 -> 6289 bytes .../src/static/tabbar/personal.png | Bin 0 -> 2457 bytes .../src/static/tabbar/personalHL.png | Bin 0 -> 2534 bytes .../src/static/tabbar/robot.png | Bin 0 -> 3471 bytes .../src/static/tabbar/robot_activate.png | Bin 0 -> 3508 bytes .../src/static/tabbar/system.png | Bin 0 -> 3391 bytes .../src/static/tabbar/system_activate.png | Bin 0 -> 3566 bytes main/manager-mobile/src/store/config.ts | 65 + main/manager-mobile/src/store/index.ts | 19 + main/manager-mobile/src/store/plugin.ts | 58 + main/manager-mobile/src/store/user.ts | 83 + main/manager-mobile/src/style/iconfont.css | 28 + main/manager-mobile/src/style/index.scss | 19 + main/manager-mobile/src/typings.d.ts | 28 + main/manager-mobile/src/typings.ts | 15 + main/manager-mobile/src/uni.scss | 77 + main/manager-mobile/src/utils/index.ts | 198 + main/manager-mobile/src/utils/platform.ts | 24 + main/manager-mobile/src/utils/toast.ts | 65 + main/manager-mobile/src/utils/uploadFile.ts | 327 + main/manager-mobile/uno.config.ts | 65 + .../unpackage/res/icons/1024x1024.png | Bin 0 -> 458242 bytes .../unpackage/res/icons/120x120.png | Bin 0 -> 17805 bytes .../unpackage/res/icons/144x144.png | Bin 0 -> 24176 bytes .../unpackage/res/icons/152x152.png | Bin 0 -> 26428 bytes .../unpackage/res/icons/167x167.png | Bin 0 -> 30883 bytes .../unpackage/res/icons/180x180.png | Bin 0 -> 35063 bytes .../unpackage/res/icons/192x192.png | Bin 0 -> 38903 bytes .../unpackage/res/icons/20x20.png | Bin 0 -> 1330 bytes .../unpackage/res/icons/29x29.png | Bin 0 -> 1471 bytes .../unpackage/res/icons/40x40.png | Bin 0 -> 1709 bytes .../unpackage/res/icons/58x58.png | Bin 0 -> 2210 bytes .../unpackage/res/icons/60x60.png | Bin 0 -> 2275 bytes .../unpackage/res/icons/72x72.png | Bin 0 -> 2708 bytes .../unpackage/res/icons/76x76.png | Bin 0 -> 2833 bytes .../unpackage/res/icons/80x80.png | Bin 0 -> 2962 bytes .../unpackage/res/icons/87x87.png | Bin 0 -> 3266 bytes .../unpackage/res/icons/96x96.png | Bin 0 -> 3680 bytes main/manager-mobile/vite.config.ts | 182 + main/manager-web/public/offline.html | 14 +- main/manager-web/src/App.vue | 70 +- main/manager-web/src/apis/api.js | 12 +- main/manager-web/src/apis/httpRequest.js | 22 +- main/manager-web/src/apis/module/admin.js | 34 +- main/manager-web/src/apis/module/agent.js | 120 +- main/manager-web/src/apis/module/device.js | 20 +- main/manager-web/src/apis/module/dict.js | 62 +- main/manager-web/src/apis/module/model.js | 100 +- main/manager-web/src/apis/module/ota.js | 28 +- main/manager-web/src/apis/module/timbre.js | 16 +- main/manager-web/src/apis/module/user.js | 30 +- .../src/components/AddDeviceDialog.vue | 16 +- .../src/components/AddModelDialog.vue | 44 +- .../src/components/AddWisdomBodyDialog.vue | 14 +- .../src/components/CacheViewer.vue | 60 +- .../src/components/ChangePasswordDialog.vue | 34 +- .../src/components/ChatHistoryDialog.vue | 70 +- .../manager-web/src/components/DeviceItem.vue | 30 +- .../src/components/DictDataDialog.vue | 20 +- .../src/components/DictTypeDialog.vue | 18 +- .../src/components/EditVoiceDialog.vue | 32 +- .../src/components/FirmwareDialog.vue | 50 +- .../src/components/FunctionDialog.vue | 58 +- main/manager-web/src/components/HeaderBar.vue | 80 +- .../src/components/ManualAddDeviceDialog.vue | 36 +- .../src/components/ModelEditDialog.vue | 44 +- .../src/components/ParamDialog.vue | 38 +- .../src/components/ProviderDialog.vue | 106 +- main/manager-web/src/components/TtsModel.vue | 26 +- .../src/components/VersionFooter.vue | 2 +- .../src/components/ViewPasswordDialog.vue | 10 +- .../src/components/VoicePrintDialog.vue | 420 + main/manager-web/src/router/index.js | 33 +- main/manager-web/src/utils/cacheViewer.js | 48 +- main/manager-web/src/utils/constant.js | 6 +- .../src/views/DeviceManagement.vue | 115 +- main/manager-web/src/views/DictManagement.vue | 120 +- main/manager-web/src/views/ModelConfig.vue | 158 +- main/manager-web/src/views/OtaManagement.vue | 102 +- .../src/views/ParamsManagement.vue | 80 +- .../src/views/ProviderManagement.vue | 110 +- .../src/views/ServerSideManager.vue | 40 +- main/manager-web/src/views/UserManagement.vue | 112 +- main/manager-web/src/views/VoicePrint.vue | 563 + main/manager-web/src/views/home.vue | 66 +- main/manager-web/src/views/login.vue | 46 +- main/manager-web/src/views/register.vue | 82 +- .../src/views/retrievePassword.vue | 52 +- main/manager-web/src/views/roleConfig.vue | 178 +- .../asr_logs/asr_log_20250821.csv | 1 + .../asr_logs/asr_log_20250821.txt | 8 + 247 files changed, 33418 insertions(+), 1444 deletions(-) create mode 100644 main/manager-api/database-interactive-schema.html create mode 100644 main/manager-api/database-network-diagram.html create mode 100644 main/manager-api/database-relationship-matrix.md create mode 100644 main/manager-api/database-schema-documentation.md create mode 100644 main/manager-api/database-visual-schema.md create mode 100644 main/manager-api/railway-setup.md create mode 100644 main/manager-api/src/main/java/xiaozhi/common/utils/JsonRpcTwo.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/AgentChatHistoryType.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/XiaoZhiMcpJsonRpcJson.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentVoicePrintController.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentVoicePrintDao.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintSaveDTO.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintUpdateDTO.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/dto/IdentifyVoicePrintResponse.java delete mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/dto/McpJsonRpcRequest.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentVoicePrintEntity.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentVoicePrintService.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentVoicePrintServiceImpl.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentChatHistoryUserVO.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentVoicePrintVO.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/model/dto/LlmModelBasicInfoDTO.java create mode 100644 main/manager-api/src/main/resources/application-railway.yml delete mode 100644 main/manager-api/src/main/resources/application.properties create mode 100644 main/manager-api/src/main/resources/db/changelog/202507031602.sql create mode 100644 main/manager-api/src/main/resources/db/changelog/202507041018.sql delete mode 100644 main/manager-api/src/main/resources/db/changelog/202507051233.sql create mode 100644 main/manager-api/src/main/resources/db/changelog/202507071130.sql create mode 100644 main/manager-api/src/main/resources/db/changelog/202507071530.sql create mode 100644 main/manager-api/src/main/resources/db/changelog/202507081646.sql create mode 100644 main/manager-api/src/main/resources/db/changelog/202507101203.sql create mode 100644 main/manager-api/src/main/resources/db/changelog/202508081701.sql create mode 100644 main/manager-api/src/main/resources/db/changelog/202508111734.sql create mode 100644 main/manager-api/src/main/resources/db/changelog/202508131557.sql delete mode 100644 main/manager-api/src/main/resources/db/changelog/202508141200.sql delete mode 100644 main/manager-api/src/main/resources/db/changelog/add_english_sherpa_models.sql create mode 100644 main/manager-mobile/.commitlintrc.cjs create mode 100644 main/manager-mobile/.editorconfig create mode 100644 main/manager-mobile/.gitignore create mode 100644 main/manager-mobile/.npmrc create mode 100644 main/manager-mobile/LICENSE create mode 100644 main/manager-mobile/README.md create mode 100644 main/manager-mobile/eslint.config.mjs create mode 100644 main/manager-mobile/favicon.ico create mode 100644 main/manager-mobile/index.html create mode 100644 main/manager-mobile/manifest.config.ts create mode 100644 main/manager-mobile/pages.config.ts create mode 100644 main/manager-mobile/patches/@dcloudio__uni-h5.patch create mode 100644 main/manager-mobile/pnpm-lock.yaml create mode 100644 main/manager-mobile/pnpm-workspace.yaml create mode 100644 main/manager-mobile/scripts/postupgrade.js create mode 100644 main/manager-mobile/src/App.vue create mode 100644 main/manager-mobile/src/api/agent/agent.ts create mode 100644 main/manager-mobile/src/api/agent/types.ts create mode 100644 main/manager-mobile/src/api/auth.ts create mode 100644 main/manager-mobile/src/api/chat-history/chat-history.ts create mode 100644 main/manager-mobile/src/api/chat-history/index.ts create mode 100644 main/manager-mobile/src/api/chat-history/types.ts create mode 100644 main/manager-mobile/src/api/device/device.ts create mode 100644 main/manager-mobile/src/api/device/index.ts create mode 100644 main/manager-mobile/src/api/device/types.ts create mode 100644 main/manager-mobile/src/api/voiceprint/index.ts create mode 100644 main/manager-mobile/src/api/voiceprint/types.ts create mode 100644 main/manager-mobile/src/api/voiceprint/voiceprint.ts create mode 100644 main/manager-mobile/src/components/.gitkeep create mode 100644 main/manager-mobile/src/components/custom-tabs/index.vue create mode 100644 main/manager-mobile/src/env.d.ts create mode 100644 main/manager-mobile/src/hooks/.gitkeep create mode 100644 main/manager-mobile/src/hooks/usePageAuth.ts create mode 100644 main/manager-mobile/src/hooks/useRequest.ts create mode 100644 main/manager-mobile/src/hooks/useUpload.ts create mode 100644 main/manager-mobile/src/http/README.md create mode 100644 main/manager-mobile/src/http/request/alova.ts create mode 100644 main/manager-mobile/src/http/request/enum.ts create mode 100644 main/manager-mobile/src/http/request/types.ts create mode 100644 main/manager-mobile/src/layouts/default.vue create mode 100644 main/manager-mobile/src/layouts/fg-tabbar/fg-tabbar.vue create mode 100644 main/manager-mobile/src/layouts/fg-tabbar/tabbar.md create mode 100644 main/manager-mobile/src/layouts/fg-tabbar/tabbar.ts create mode 100644 main/manager-mobile/src/layouts/fg-tabbar/tabbarList.ts create mode 100644 main/manager-mobile/src/layouts/tabbar.vue create mode 100644 main/manager-mobile/src/main.ts create mode 100644 main/manager-mobile/src/pages-sub/demo/index.vue create mode 100644 main/manager-mobile/src/pages/agent/edit.vue create mode 100644 main/manager-mobile/src/pages/agent/index.vue create mode 100644 main/manager-mobile/src/pages/agent/tools.vue create mode 100644 main/manager-mobile/src/pages/chat-history/detail.vue create mode 100644 main/manager-mobile/src/pages/chat-history/index.vue create mode 100644 main/manager-mobile/src/pages/device-config/components/ultrasonic-config.vue create mode 100644 main/manager-mobile/src/pages/device-config/components/wifi-config.vue create mode 100644 main/manager-mobile/src/pages/device-config/components/wifi-selector.vue create mode 100644 main/manager-mobile/src/pages/device-config/index.vue create mode 100644 main/manager-mobile/src/pages/device/index.vue create mode 100644 main/manager-mobile/src/pages/index/index.vue create mode 100644 main/manager-mobile/src/pages/login/index.vue create mode 100644 main/manager-mobile/src/pages/register/index.vue create mode 100644 main/manager-mobile/src/pages/settings/index.vue create mode 100644 main/manager-mobile/src/pages/voiceprint/index.vue create mode 100644 main/manager-mobile/src/router/interceptor.ts create mode 100644 main/manager-mobile/src/static/app/icons/1024x1024.png create mode 100644 main/manager-mobile/src/static/app/icons/120x120.png create mode 100644 main/manager-mobile/src/static/app/icons/144x144.png create mode 100644 main/manager-mobile/src/static/app/icons/152x152.png create mode 100644 main/manager-mobile/src/static/app/icons/167x167.png create mode 100644 main/manager-mobile/src/static/app/icons/180x180.png create mode 100644 main/manager-mobile/src/static/app/icons/192x192.png create mode 100644 main/manager-mobile/src/static/app/icons/20x20.png create mode 100644 main/manager-mobile/src/static/app/icons/29x29.png create mode 100644 main/manager-mobile/src/static/app/icons/40x40.png create mode 100644 main/manager-mobile/src/static/app/icons/58x58.png create mode 100644 main/manager-mobile/src/static/app/icons/60x60.png create mode 100644 main/manager-mobile/src/static/app/icons/72x72.png create mode 100644 main/manager-mobile/src/static/app/icons/76x76.png create mode 100644 main/manager-mobile/src/static/app/icons/80x80.png create mode 100644 main/manager-mobile/src/static/app/icons/87x87.png create mode 100644 main/manager-mobile/src/static/app/icons/96x96.png create mode 100644 main/manager-mobile/src/static/images/.gitkeep create mode 100644 main/manager-mobile/src/static/images/default-avatar.png create mode 100644 main/manager-mobile/src/static/images/home/main-top-bg.png create mode 100644 main/manager-mobile/src/static/logo.png create mode 100644 main/manager-mobile/src/static/logo.svg create mode 100644 main/manager-mobile/src/static/tabbar/chat.png create mode 100644 main/manager-mobile/src/static/tabbar/chat_activate.png create mode 100644 main/manager-mobile/src/static/tabbar/device.png create mode 100644 main/manager-mobile/src/static/tabbar/device_activate.png create mode 100644 main/manager-mobile/src/static/tabbar/example.png create mode 100644 main/manager-mobile/src/static/tabbar/exampleHL.png create mode 100644 main/manager-mobile/src/static/tabbar/home.png create mode 100644 main/manager-mobile/src/static/tabbar/homeHL.png create mode 100644 main/manager-mobile/src/static/tabbar/microphone.png create mode 100644 main/manager-mobile/src/static/tabbar/microphone_activate.png create mode 100644 main/manager-mobile/src/static/tabbar/network.png create mode 100644 main/manager-mobile/src/static/tabbar/network_activate.png create mode 100644 main/manager-mobile/src/static/tabbar/personal.png create mode 100644 main/manager-mobile/src/static/tabbar/personalHL.png create mode 100644 main/manager-mobile/src/static/tabbar/robot.png create mode 100644 main/manager-mobile/src/static/tabbar/robot_activate.png create mode 100644 main/manager-mobile/src/static/tabbar/system.png create mode 100644 main/manager-mobile/src/static/tabbar/system_activate.png create mode 100644 main/manager-mobile/src/store/config.ts create mode 100644 main/manager-mobile/src/store/index.ts create mode 100644 main/manager-mobile/src/store/plugin.ts create mode 100644 main/manager-mobile/src/store/user.ts create mode 100644 main/manager-mobile/src/style/iconfont.css create mode 100644 main/manager-mobile/src/style/index.scss create mode 100644 main/manager-mobile/src/typings.d.ts create mode 100644 main/manager-mobile/src/typings.ts create mode 100644 main/manager-mobile/src/uni.scss create mode 100644 main/manager-mobile/src/utils/index.ts create mode 100644 main/manager-mobile/src/utils/platform.ts create mode 100644 main/manager-mobile/src/utils/toast.ts create mode 100644 main/manager-mobile/src/utils/uploadFile.ts create mode 100644 main/manager-mobile/uno.config.ts create mode 100644 main/manager-mobile/unpackage/res/icons/1024x1024.png create mode 100644 main/manager-mobile/unpackage/res/icons/120x120.png create mode 100644 main/manager-mobile/unpackage/res/icons/144x144.png create mode 100644 main/manager-mobile/unpackage/res/icons/152x152.png create mode 100644 main/manager-mobile/unpackage/res/icons/167x167.png create mode 100644 main/manager-mobile/unpackage/res/icons/180x180.png create mode 100644 main/manager-mobile/unpackage/res/icons/192x192.png create mode 100644 main/manager-mobile/unpackage/res/icons/20x20.png create mode 100644 main/manager-mobile/unpackage/res/icons/29x29.png create mode 100644 main/manager-mobile/unpackage/res/icons/40x40.png create mode 100644 main/manager-mobile/unpackage/res/icons/58x58.png create mode 100644 main/manager-mobile/unpackage/res/icons/60x60.png create mode 100644 main/manager-mobile/unpackage/res/icons/72x72.png create mode 100644 main/manager-mobile/unpackage/res/icons/76x76.png create mode 100644 main/manager-mobile/unpackage/res/icons/80x80.png create mode 100644 main/manager-mobile/unpackage/res/icons/87x87.png create mode 100644 main/manager-mobile/unpackage/res/icons/96x96.png create mode 100644 main/manager-mobile/vite.config.ts create mode 100644 main/manager-web/src/components/VoicePrintDialog.vue create mode 100644 main/manager-web/src/views/VoicePrint.vue diff --git a/main/manager-api/README.md b/main/manager-api/README.md index 484c28dc0..5d5305066 100644 --- a/main/manager-api/README.md +++ b/main/manager-api/README.md @@ -1,18 +1,18 @@ -本文档是开发类文档,如需部署小智服务端,[点击这里查看部署教程](../../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3) +This is a development document. If you need to deploy the Xiaozhi server, [click here to view the deployment tutorial](../../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3) -# 项目介绍 +# Project Introduction -manager-api 该项目基于SpringBoot框架开发。 +manager-api: This project is developed based on the SpringBoot framework. -开发使用代码编辑器,导入项目时,选择`manager-api`文件夹作为项目目录 +When developing, use a code editor and select the `manager-api` folder as the project directory when importing the project. -# 开发环境 +# Development Environment JDK 21 Maven 3.8+ MySQL 8.0+ Redis 5.0+ Vue 3.x -# 接口文档 -启动后打开:http://localhost:8002/xiaozhi/doc.html +# API Documentation +After starting, open: http://localhost:8002/xiaozhi/doc.html diff --git a/main/manager-api/database-interactive-schema.html b/main/manager-api/database-interactive-schema.html new file mode 100644 index 000000000..05f737ab8 --- /dev/null +++ b/main/manager-api/database-interactive-schema.html @@ -0,0 +1,917 @@ + + + + + + Xiaozhi ESP32 Server - Interactive Database Schema + + + +
+
+

🗄️ Xiaozhi ESP32 Server Database Schema

+

Interactive visualization of 16 tables across 6 functional categories

+
+ +
+
+ + +
+ +
+ + +
+ + + + +
+ +
+ +
+ + + +
+
+
16
+
Total Tables
+
+
+
6
+
Categories
+
+
+
25
+
Relationships
+
+
+
7
+
Model Types
+
+
+
+ + + + diff --git a/main/manager-api/database-network-diagram.html b/main/manager-api/database-network-diagram.html new file mode 100644 index 000000000..4a347625d --- /dev/null +++ b/main/manager-api/database-network-diagram.html @@ -0,0 +1,1512 @@ + + + + + + Xiaozhi ESP32 Server - Interactive Database Network Diagram + + + +
+
+
+

🗄️ Xiaozhi ESP32 Database Network

+
+
+
16
+
Tables
+
+
+
25
+
Relations
+
+
+
6
+
Categories
+
+
+
+
+ +
+
+ + +
+ +
+ + +
+ +
+ + +
+ + + + +
+ +
+
+ + + +
+
+ +
+ + + +
+ +
+

Relationship Types

+
+
+ One-to-One (1:1) +
+
+
+ One-to-Many (1:M) +
+
+
+ Many-to-Many (M:M) +
+
+
+ Template Based +
+
+ + +
+ + + + diff --git a/main/manager-api/database-relationship-matrix.md b/main/manager-api/database-relationship-matrix.md new file mode 100644 index 000000000..a6c95e12a --- /dev/null +++ b/main/manager-api/database-relationship-matrix.md @@ -0,0 +1,201 @@ +# Xiaozhi ESP32 Server - Database Relationship Matrix + +## 📊 Table Relationship Matrix + +This document provides a structured text-based view of all database relationships in the Xiaozhi ESP32 Server system. + +### 🔗 Relationship Matrix Table + +``` +┌─────────────────────────┬─────────────────────────┬──────────┬─────────────────────────────────────┐ +│ FROM TABLE │ TO TABLE │ TYPE │ DESCRIPTION │ +├─────────────────────────┼─────────────────────────┼──────────┼─────────────────────────────────────┤ +│ sys_user │ sys_user_token │ 1:1 │ User authentication tokens │ +│ sys_user │ ai_agent │ 1:M │ User owns multiple AI agents │ +│ sys_user │ ai_device │ 1:M │ User owns multiple ESP32 devices │ +│ sys_user │ ai_voiceprint │ 1:M │ User has multiple voiceprints │ +│ sys_user │ ai_chat_history │ 1:M │ User participates in multiple chats │ +│ sys_user │ ai_chat_message │ 1:M │ User sends multiple messages │ +├─────────────────────────┼─────────────────────────┼──────────┼─────────────────────────────────────┤ +│ sys_dict_type │ sys_dict_data │ 1:M │ Dictionary type contains entries │ +├─────────────────────────┼─────────────────────────┼──────────┼─────────────────────────────────────┤ +│ ai_model_config │ ai_tts_voice │ 1:M │ TTS model provides multiple voices │ +│ ai_model_config │ ai_agent (asr_model) │ 1:M │ ASR model used by multiple agents │ +│ ai_model_config │ ai_agent (vad_model) │ 1:M │ VAD model used by multiple agents │ +│ ai_model_config │ ai_agent (llm_model) │ 1:M │ LLM model used by multiple agents │ +│ ai_model_config │ ai_agent (vllm_model) │ 1:M │ VLLM model used by multiple agents │ +│ ai_model_config │ ai_agent (tts_model) │ 1:M │ TTS model used by multiple agents │ +│ ai_model_config │ ai_agent (mem_model) │ 1:M │ Memory model used by multiple agents│ +│ ai_model_config │ ai_agent (intent_model) │ 1:M │ Intent model used by multiple agents│ +├─────────────────────────┼─────────────────────────┼──────────┼─────────────────────────────────────┤ +│ ai_tts_voice │ ai_agent │ 1:M │ Voice used by multiple agents │ +│ ai_tts_voice │ ai_agent_template │ 1:M │ Voice used by multiple templates │ +├─────────────────────────┼─────────────────────────┼──────────┼─────────────────────────────────────┤ +│ ai_agent_template │ ai_agent │ Template │ Template basis for agent creation │ +├─────────────────────────┼─────────────────────────┼──────────┼─────────────────────────────────────┤ +│ ai_agent │ ai_device │ 1:M │ Agent assigned to multiple devices │ +│ ai_agent │ ai_voiceprint │ 1:M │ Agent recognizes multiple voices │ +│ ai_agent │ ai_chat_history │ 1:M │ Agent in multiple chat sessions │ +│ ai_agent │ ai_agent_chat_history │ 1:M │ Agent in multiple device chats │ +├─────────────────────────┼─────────────────────────┼──────────┼─────────────────────────────────────┤ +│ ai_device │ ai_chat_history │ 1:M │ Device used in multiple chats │ +│ ai_device │ ai_agent_chat_history │ 1:M │ Device connects via MAC address │ +├─────────────────────────┼─────────────────────────┼──────────┼─────────────────────────────────────┤ +│ ai_chat_history │ ai_chat_message │ 1:M │ Chat session contains messages │ +├─────────────────────────┼─────────────────────────┼──────────┼─────────────────────────────────────┤ +│ ai_agent_chat_history │ ai_agent_chat_audio │ 1:1 │ Chat entry may have audio data │ +└─────────────────────────┴─────────────────────────┴──────────┴─────────────────────────────────────┘ +``` + +## 🎯 Foreign Key Reference Table + +### Primary Foreign Key Relationships + +``` +┌─────────────────────────┬─────────────────────────┬─────────────────────────┬─────────────────┐ +│ TABLE │ FOREIGN KEY COLUMN │ REFERENCES │ CONSTRAINT TYPE │ +├─────────────────────────┼─────────────────────────┼─────────────────────────┼─────────────────┤ +│ sys_user_token │ user_id │ sys_user.id │ UNIQUE │ +│ sys_dict_data │ dict_type_id │ sys_dict_type.id │ NOT NULL │ +│ ai_tts_voice │ tts_model_id │ ai_model_config.id │ NULL ALLOWED │ +│ ai_agent │ user_id │ sys_user.id │ NULL ALLOWED │ +│ ai_agent │ asr_model_id │ ai_model_config.id │ NULL ALLOWED │ +│ ai_agent │ vad_model_id │ ai_model_config.id │ NULL ALLOWED │ +│ ai_agent │ llm_model_id │ ai_model_config.id │ NULL ALLOWED │ +│ ai_agent │ vllm_model_id │ ai_model_config.id │ NULL ALLOWED │ +│ ai_agent │ tts_model_id │ ai_model_config.id │ NULL ALLOWED │ +│ ai_agent │ tts_voice_id │ ai_tts_voice.id │ NULL ALLOWED │ +│ ai_agent │ mem_model_id │ ai_model_config.id │ NULL ALLOWED │ +│ ai_agent │ intent_model_id │ ai_model_config.id │ NULL ALLOWED │ +│ ai_device │ user_id │ sys_user.id │ NULL ALLOWED │ +│ ai_device │ agent_id │ ai_agent.id │ NULL ALLOWED │ +│ ai_voiceprint │ user_id │ sys_user.id │ NULL ALLOWED │ +│ ai_voiceprint │ agent_id │ ai_agent.id │ NULL ALLOWED │ +│ ai_chat_history │ user_id │ sys_user.id │ NULL ALLOWED │ +│ ai_chat_history │ agent_id │ ai_agent.id │ NULL ALLOWED │ +│ ai_chat_history │ device_id │ ai_device.id │ NULL ALLOWED │ +│ ai_chat_message │ user_id │ sys_user.id │ NULL ALLOWED │ +│ ai_chat_message │ chat_id │ ai_chat_history.id │ NULL ALLOWED │ +│ ai_agent_chat_history │ agent_id │ ai_agent.id │ NULL ALLOWED │ +│ ai_agent_chat_history │ audio_id │ ai_agent_chat_audio.id │ NULL ALLOWED │ +└─────────────────────────┴─────────────────────────┴─────────────────────────┴─────────────────┘ +``` + +## 📋 Table Dependency Hierarchy + +### Level 0 (Independent Tables) +``` +sys_user ← Root entity (users) +sys_dict_type ← System dictionaries +sys_params ← System parameters +ai_model_provider ← AI model providers +ai_model_config ← AI model configurations +ai_agent_chat_audio ← Audio data storage +``` + +### Level 1 (Depends on Level 0) +``` +sys_user_token ← Depends on: sys_user +sys_dict_data ← Depends on: sys_dict_type +ai_tts_voice ← Depends on: ai_model_config +ai_agent_template ← Independent template definitions +``` + +### Level 2 (Depends on Level 0-1) +``` +ai_agent ← Depends on: sys_user, ai_model_config, ai_tts_voice +``` + +### Level 3 (Depends on Level 0-2) +``` +ai_device ← Depends on: sys_user, ai_agent +ai_voiceprint ← Depends on: sys_user, ai_agent +ai_chat_history ← Depends on: sys_user, ai_agent, ai_device +ai_agent_chat_history ← Depends on: ai_agent, ai_agent_chat_audio +``` + +### Level 4 (Depends on Level 0-3) +``` +ai_chat_message ← Depends on: sys_user, ai_chat_history +``` + +## 🔄 Data Flow Patterns + +### User-Centric Flow +``` +sys_user +├── Creates → ai_agent (using ai_agent_template) +├── Owns → ai_device +├── Trains → ai_voiceprint +├── Participates → ai_chat_history +└── Sends → ai_chat_message +``` + +### AI Agent Configuration Flow +``` +ai_model_config +├── ASR Model → ai_agent.asr_model_id +├── VAD Model → ai_agent.vad_model_id +├── LLM Model → ai_agent.llm_model_id +├── VLLM Model → ai_agent.vllm_model_id +├── TTS Model → ai_agent.tts_model_id +├── Memory Model → ai_agent.mem_model_id +└── Intent Model → ai_agent.intent_model_id + +ai_tts_voice → ai_agent.tts_voice_id +``` + +### Communication Flow +``` +Web Interface: +sys_user → ai_chat_history → ai_chat_message + +Device Interface: +ai_device (via MAC) → ai_agent_chat_history → ai_agent_chat_audio +``` + +### Device Management Flow +``` +sys_user → ai_device → ai_agent (assignment) +ai_device → ai_agent_chat_history (via MAC address) +``` + +## 📊 Relationship Statistics + +### Relationship Type Distribution +``` +One-to-One: 2 relationships (8.0%) +One-to-Many: 20 relationships (80.0%) +Many-to-Many: 3 relationships (12.0%) [via foreign keys] +Template: 1 relationship (4.0%) +``` + +### Table Connection Density +``` +Most Connected Tables: +1. sys_user (6 outgoing relationships) +2. ai_agent (4 outgoing relationships) +3. ai_model_config (7 outgoing relationships) +4. ai_device (2 outgoing relationships) + +Least Connected Tables: +1. sys_params (0 relationships) +2. ai_model_provider (0 relationships) +3. ai_agent_chat_audio (1 incoming relationship) +``` + +### Critical Path Analysis +``` +Core User Journey: +sys_user → ai_agent → ai_device → ai_agent_chat_history + +Essential Configuration: +ai_model_config → ai_agent → ai_device + +Communication Channels: +1. Web: sys_user → ai_chat_history → ai_chat_message +2. Device: ai_device → ai_agent_chat_history → ai_agent_chat_audio +``` + +--- +*Generated: 2025-08-20 | Version: 1.0 | Format: Structured Text Matrix* diff --git a/main/manager-api/database-schema-documentation.md b/main/manager-api/database-schema-documentation.md new file mode 100644 index 000000000..909b71659 --- /dev/null +++ b/main/manager-api/database-schema-documentation.md @@ -0,0 +1,422 @@ +# Xiaozhi ESP32 Server - Database Schema Documentation + +## 📋 Overview + +This document provides a comprehensive overview of the database schema for the Xiaozhi ESP32 Server system. The system is designed to manage AI-powered voice assistants that run on ESP32 devices, with a web-based management interface. + +## 🗄️ Database Structure + +The database consists of **16 main tables** organized into **6 functional categories**: + +### 1. 🔐 System Management Tables (5 tables) + +#### `sys_user` - System Users +**Purpose**: Manages user accounts and authentication +```sql +CREATE TABLE sys_user ( + id bigint NOT NULL COMMENT 'User ID', + username varchar(50) NOT NULL COMMENT 'Username', + password varchar(100) COMMENT 'Password', + super_admin tinyint unsigned COMMENT 'Super Admin (0:No 1:Yes)', + status tinyint COMMENT 'Status (0:Disabled 1:Active)', + create_date datetime COMMENT 'Creation Time', + updater bigint COMMENT 'Updater', + creator bigint COMMENT 'Creator', + update_date datetime COMMENT 'Update Time', + PRIMARY KEY (id), + UNIQUE KEY uk_username (username) +); +``` + +#### `sys_user_token` - User Authentication Tokens +**Purpose**: Manages user session tokens for API authentication +```sql +CREATE TABLE sys_user_token ( + id bigint NOT NULL COMMENT 'Token ID', + user_id bigint NOT NULL COMMENT 'User ID', + token varchar(100) NOT NULL COMMENT 'User Token', + expire_date datetime COMMENT 'Expiration Date', + update_date datetime COMMENT 'Update Time', + create_date datetime COMMENT 'Creation Time', + PRIMARY KEY (id), + UNIQUE KEY user_id (user_id), + UNIQUE KEY token (token) +); +``` + +#### `sys_params` - System Parameters +**Purpose**: Stores system configuration parameters +```sql +CREATE TABLE sys_params ( + id bigint NOT NULL COMMENT 'Parameter ID', + param_code varchar(32) COMMENT 'Parameter Code', + param_value varchar(2000) COMMENT 'Parameter Value', + param_type tinyint unsigned default 1 COMMENT 'Type (0:System 1:Non-System)', + remark varchar(200) COMMENT 'Remark', + creator bigint COMMENT 'Creator', + create_date datetime COMMENT 'Creation Time', + updater bigint COMMENT 'Updater', + update_date datetime COMMENT 'Update Time', + PRIMARY KEY (id), + UNIQUE KEY uk_param_code (param_code) +); +``` + +#### `sys_dict_type` - Dictionary Types +**Purpose**: Defines dictionary categories for system data +```sql +CREATE TABLE sys_dict_type ( + id bigint NOT NULL COMMENT 'Dictionary Type ID', + dict_type varchar(100) NOT NULL COMMENT 'Dictionary Type', + dict_name varchar(255) NOT NULL COMMENT 'Dictionary Name', + remark varchar(255) COMMENT 'Remark', + sort int unsigned COMMENT 'Sort Order', + creator bigint COMMENT 'Creator', + create_date datetime COMMENT 'Creation Time', + updater bigint COMMENT 'Updater', + update_date datetime COMMENT 'Update Time', + PRIMARY KEY (id), + UNIQUE KEY(dict_type) +); +``` + +#### `sys_dict_data` - Dictionary Data +**Purpose**: Stores dictionary data entries +```sql +CREATE TABLE sys_dict_data ( + id bigint NOT NULL COMMENT 'Dictionary Data ID', + dict_type_id bigint NOT NULL COMMENT 'Dictionary Type ID', + dict_label varchar(255) NOT NULL COMMENT 'Dictionary Label', + dict_value varchar(255) COMMENT 'Dictionary Value', + remark varchar(255) COMMENT 'Remark', + sort int unsigned COMMENT 'Sort Order', + creator bigint COMMENT 'Creator', + create_date datetime COMMENT 'Creation Time', + updater bigint COMMENT 'Updater', + update_date datetime COMMENT 'Update Time', + PRIMARY KEY (id), + UNIQUE KEY uk_dict_type_value (dict_type_id, dict_value), + KEY idx_sort (sort) +); +``` + +### 2. 🤖 AI Model Configuration Tables (3 tables) + +#### `ai_model_provider` - Model Providers +**Purpose**: Manages AI model providers (OpenAI, Alibaba, etc.) +```sql +CREATE TABLE ai_model_provider ( + id VARCHAR(32) NOT NULL COMMENT 'Provider ID', + model_type VARCHAR(20) COMMENT 'Model Type (Memory/ASR/VAD/LLM/TTS)', + provider_code VARCHAR(50) COMMENT 'Provider Code', + name VARCHAR(50) COMMENT 'Provider Name', + fields JSON COMMENT 'Provider Fields (JSON format)', + sort INT UNSIGNED DEFAULT 0 COMMENT 'Sort Order', + creator BIGINT COMMENT 'Creator', + create_date DATETIME COMMENT 'Creation Time', + updater BIGINT COMMENT 'Updater', + update_date DATETIME COMMENT 'Update Time', + PRIMARY KEY (id), + INDEX idx_ai_model_provider_model_type (model_type) +); +``` + +#### `ai_model_config` - Model Configurations +**Purpose**: Stores specific AI model configurations +```sql +CREATE TABLE ai_model_config ( + id VARCHAR(32) NOT NULL COMMENT 'Model Config ID', + model_type VARCHAR(20) COMMENT 'Model Type (Memory/ASR/VAD/LLM/TTS)', + model_code VARCHAR(50) COMMENT 'Model Code', + model_name VARCHAR(50) COMMENT 'Model Name', + is_default TINYINT(1) DEFAULT 0 COMMENT 'Is Default (0:No 1:Yes)', + is_enabled TINYINT(1) DEFAULT 0 COMMENT 'Is Enabled', + config_json JSON COMMENT 'Model Configuration (JSON)', + doc_link VARCHAR(200) COMMENT 'Documentation Link', + remark VARCHAR(255) COMMENT 'Remark', + sort INT UNSIGNED DEFAULT 0 COMMENT 'Sort Order', + creator BIGINT COMMENT 'Creator', + create_date DATETIME COMMENT 'Creation Time', + updater BIGINT COMMENT 'Updater', + update_date DATETIME COMMENT 'Update Time', + PRIMARY KEY (id), + INDEX idx_ai_model_config_model_type (model_type) +); +``` + +#### `ai_tts_voice` - TTS Voice Configurations +**Purpose**: Manages Text-to-Speech voice options +```sql +CREATE TABLE ai_tts_voice ( + id VARCHAR(32) NOT NULL COMMENT 'Voice ID', + tts_model_id VARCHAR(32) COMMENT 'TTS Model ID', + name VARCHAR(20) COMMENT 'Voice Name', + tts_voice VARCHAR(50) COMMENT 'Voice Code', + languages VARCHAR(50) COMMENT 'Supported Languages', + voice_demo VARCHAR(500) DEFAULT NULL COMMENT 'Voice Demo URL', + remark VARCHAR(255) COMMENT 'Remark', + sort INT UNSIGNED DEFAULT 0 COMMENT 'Sort Order', + creator BIGINT COMMENT 'Creator', + create_date DATETIME COMMENT 'Creation Time', + updater BIGINT COMMENT 'Updater', + update_date DATETIME COMMENT 'Update Time', + PRIMARY KEY (id), + INDEX idx_ai_tts_voice_tts_model_id (tts_model_id) +); +``` + +### 3. 🧠 AI Agent Management Tables (2 tables) + +#### `ai_agent_template` - Agent Templates +**Purpose**: Predefined AI agent configurations that users can use as starting points +```sql +CREATE TABLE ai_agent_template ( + id VARCHAR(32) NOT NULL COMMENT 'Agent Template ID', + agent_code VARCHAR(36) COMMENT 'Agent Code', + agent_name VARCHAR(64) COMMENT 'Agent Name', + asr_model_id VARCHAR(32) COMMENT 'ASR Model ID', + vad_model_id VARCHAR(64) COMMENT 'VAD Model ID', + llm_model_id VARCHAR(32) COMMENT 'LLM Model ID', + vllm_model_id VARCHAR(32) COMMENT 'VLLM Model ID', + tts_model_id VARCHAR(32) COMMENT 'TTS Model ID', + tts_voice_id VARCHAR(32) COMMENT 'TTS Voice ID', + mem_model_id VARCHAR(32) COMMENT 'Memory Model ID', + intent_model_id VARCHAR(32) COMMENT 'Intent Model ID', + system_prompt TEXT COMMENT 'System Prompt', + lang_code VARCHAR(10) COMMENT 'Language Code', + language VARCHAR(10) COMMENT 'Interaction Language', + sort INT UNSIGNED DEFAULT 0 COMMENT 'Sort Weight', + creator BIGINT COMMENT 'Creator ID', + created_at DATETIME COMMENT 'Creation Time', + updater BIGINT COMMENT 'Updater ID', + updated_at DATETIME COMMENT 'Update Time', + PRIMARY KEY (id) +); +``` + +#### `ai_agent` - User AI Agents +**Purpose**: User-created AI agents with custom configurations +```sql +CREATE TABLE ai_agent ( + id VARCHAR(32) NOT NULL COMMENT 'Agent ID', + user_id BIGINT COMMENT 'Owner User ID', + agent_code VARCHAR(36) COMMENT 'Agent Code', + agent_name VARCHAR(64) COMMENT 'Agent Name', + asr_model_id VARCHAR(32) COMMENT 'ASR Model ID', + vad_model_id VARCHAR(64) COMMENT 'VAD Model ID', + llm_model_id VARCHAR(32) COMMENT 'LLM Model ID', + vllm_model_id VARCHAR(32) COMMENT 'VLLM Model ID', + tts_model_id VARCHAR(32) COMMENT 'TTS Model ID', + tts_voice_id VARCHAR(32) COMMENT 'TTS Voice ID', + mem_model_id VARCHAR(32) COMMENT 'Memory Model ID', + intent_model_id VARCHAR(32) COMMENT 'Intent Model ID', + system_prompt TEXT COMMENT 'System Prompt', + lang_code VARCHAR(10) COMMENT 'Language Code', + language VARCHAR(10) COMMENT 'Interaction Language', + sort INT UNSIGNED DEFAULT 0 COMMENT 'Sort Weight', + creator BIGINT COMMENT 'Creator ID', + created_at DATETIME COMMENT 'Creation Time', + updater BIGINT COMMENT 'Updater ID', + updated_at DATETIME COMMENT 'Update Time', + PRIMARY KEY (id), + INDEX idx_ai_agent_user_id (user_id) +); +``` + +### 4. 📱 Device Management Tables (1 table) + +#### `ai_device` - ESP32 Device Information +**Purpose**: Manages ESP32 devices and their configurations +```sql +CREATE TABLE ai_device ( + id VARCHAR(32) NOT NULL COMMENT 'Device ID', + user_id BIGINT COMMENT 'Associated User ID', + mac_address VARCHAR(50) COMMENT 'MAC Address', + last_connected_at DATETIME COMMENT 'Last Connection Time', + auto_update TINYINT UNSIGNED DEFAULT 0 COMMENT 'Auto Update (0:Off 1:On)', + board VARCHAR(50) COMMENT 'Hardware Model', + alias VARCHAR(64) DEFAULT NULL COMMENT 'Device Alias', + agent_id VARCHAR(32) COMMENT 'Assigned Agent ID', + app_version VARCHAR(20) COMMENT 'Firmware Version', + sort INT UNSIGNED DEFAULT 0 COMMENT 'Sort Order', + creator BIGINT COMMENT 'Creator', + create_date DATETIME COMMENT 'Creation Time', + updater BIGINT COMMENT 'Updater', + update_date DATETIME COMMENT 'Update Time', + PRIMARY KEY (id), + INDEX idx_ai_device_created_at (mac_address) +); +``` + +### 5. 🔊 Voice Recognition Tables (1 table) + +#### `ai_voiceprint` - Voice Print Recognition +**Purpose**: Stores voice print data for user identification +```sql +CREATE TABLE ai_voiceprint ( + id VARCHAR(32) NOT NULL COMMENT 'Voiceprint ID', + name VARCHAR(64) COMMENT 'Voiceprint Name', + user_id BIGINT COMMENT 'User ID', + agent_id VARCHAR(32) COMMENT 'Associated Agent ID', + agent_code VARCHAR(36) COMMENT 'Associated Agent Code', + agent_name VARCHAR(36) COMMENT 'Associated Agent Name', + description VARCHAR(255) COMMENT 'Voiceprint Description', + embedding LONGTEXT COMMENT 'Voice Feature Vector (JSON)', + memory TEXT COMMENT 'Associated Memory Data', + sort INT UNSIGNED DEFAULT 0 COMMENT 'Sort Weight', + creator BIGINT COMMENT 'Creator ID', + created_at DATETIME COMMENT 'Creation Time', + updater BIGINT COMMENT 'Updater ID', + updated_at DATETIME COMMENT 'Update Time', + PRIMARY KEY (id) +); +``` + +### 6. 💬 Chat & Communication Tables (4 tables) + +#### `ai_chat_history` - Web Chat Sessions +**Purpose**: Manages web-based chat sessions +```sql +CREATE TABLE ai_chat_history ( + id VARCHAR(32) NOT NULL COMMENT 'Chat Session ID', + user_id BIGINT COMMENT 'User ID', + agent_id VARCHAR(32) DEFAULT NULL COMMENT 'Chat Agent', + device_id VARCHAR(32) DEFAULT NULL COMMENT 'Device ID', + message_count INT COMMENT 'Message Count', + creator BIGINT COMMENT 'Creator', + create_date DATETIME COMMENT 'Creation Time', + updater BIGINT COMMENT 'Updater', + update_date DATETIME COMMENT 'Update Time', + PRIMARY KEY (id) +); +``` + +#### `ai_chat_message` - Web Chat Messages +**Purpose**: Stores individual chat messages from web interface +```sql +CREATE TABLE ai_chat_message ( + id VARCHAR(32) NOT NULL COMMENT 'Message ID', + user_id BIGINT COMMENT 'User ID', + chat_id VARCHAR(64) COMMENT 'Chat History ID', + role ENUM('user', 'assistant') COMMENT 'Role (user/assistant)', + content TEXT COMMENT 'Message Content', + prompt_tokens INT UNSIGNED DEFAULT 0 COMMENT 'Prompt Tokens', + total_tokens INT UNSIGNED DEFAULT 0 COMMENT 'Total Tokens', + completion_tokens INT UNSIGNED DEFAULT 0 COMMENT 'Completion Tokens', + prompt_ms INT UNSIGNED DEFAULT 0 COMMENT 'Prompt Time (ms)', + total_ms INT UNSIGNED DEFAULT 0 COMMENT 'Total Time (ms)', + completion_ms INT UNSIGNED DEFAULT 0 COMMENT 'Completion Time (ms)', + creator BIGINT COMMENT 'Creator', + create_date DATETIME COMMENT 'Creation Time', + updater BIGINT COMMENT 'Updater', + update_date DATETIME COMMENT 'Update Time', + PRIMARY KEY (id), + INDEX idx_ai_chat_message_user_id_chat_id_role (user_id, chat_id), + INDEX idx_ai_chat_message_created_at (create_date) +); +``` + +#### `ai_agent_chat_history` - Device Chat History +**Purpose**: Stores chat interactions from ESP32 devices +```sql +CREATE TABLE ai_agent_chat_history ( + id BIGINT AUTO_INCREMENT COMMENT 'Primary Key ID' PRIMARY KEY, + mac_address VARCHAR(50) COMMENT 'MAC Address', + agent_id VARCHAR(32) COMMENT 'Agent ID', + session_id VARCHAR(50) COMMENT 'Session ID', + chat_type TINYINT(3) COMMENT 'Message Type (1:User, 2:Agent)', + content VARCHAR(1024) COMMENT 'Chat Content', + audio_id VARCHAR(32) COMMENT 'Audio ID', + created_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3) NOT NULL COMMENT 'Creation Time', + updated_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3) NOT NULL ON UPDATE CURRENT_TIMESTAMP(3) COMMENT 'Update Time', + INDEX idx_ai_agent_chat_history_mac (mac_address), + INDEX idx_ai_agent_chat_history_session_id (session_id), + INDEX idx_ai_agent_chat_history_agent_id (agent_id), + INDEX idx_ai_agent_chat_history_agent_session_created (agent_id, session_id, created_at) +); +``` + +#### `ai_agent_chat_audio` - Device Chat Audio Data +**Purpose**: Stores audio data from device interactions +```sql +CREATE TABLE ai_agent_chat_audio ( + id VARCHAR(32) COMMENT 'Audio ID' PRIMARY KEY, + audio LONGBLOB COMMENT 'Audio OPUS Data' +); +``` + +## 🔗 Key Relationships + +### Primary Relationships: +1. **`sys_user`** → **`ai_agent`** (One-to-Many): Users can create multiple AI agents +2. **`sys_user`** → **`ai_device`** (One-to-Many): Users can own multiple ESP32 devices +3. **`ai_agent`** → **`ai_device`** (One-to-Many): An agent can be assigned to multiple devices +4. **`ai_model_config`** → **`ai_agent`** (Many-to-Many): Agents use multiple model configurations +5. **`ai_tts_voice`** → **`ai_agent`** (Many-to-One): Agents use specific TTS voices + +### Secondary Relationships: +1. **`sys_dict_type`** → **`sys_dict_data`** (One-to-Many) +2. **`sys_user`** → **`sys_user_token`** (One-to-One) +3. **`ai_agent_template`** → **`ai_agent`** (Template-based creation) +4. **`ai_device`** → **`ai_agent_chat_history`** (via MAC address) +5. **`ai_agent_chat_history`** → **`ai_agent_chat_audio`** (One-to-One) + +## 🎯 System Architecture Insights + +### AI Model Pipeline: +The system supports a modular AI pipeline with separate configurations for: +- **ASR** (Automatic Speech Recognition) +- **VAD** (Voice Activity Detection) +- **LLM** (Large Language Model) +- **VLLM** (Vision Large Language Model) +- **TTS** (Text-to-Speech) +- **Memory** (Conversation Memory) +- **Intent** (Intent Recognition) + +### Multi-Channel Communication: +1. **Web Interface**: `ai_chat_history` + `ai_chat_message` +2. **Device Interface**: `ai_agent_chat_history` + `ai_agent_chat_audio` + +### User Management: +- Role-based access with super admin capabilities +- Token-based authentication for API access +- User ownership of agents, devices, and voiceprints + +### Device Management: +- MAC address-based device identification +- Firmware version tracking +- Auto-update capabilities +- Agent assignment per device + +## 📊 Database Statistics + +- **Total Tables**: 16 +- **System Tables**: 5 +- **AI Configuration Tables**: 3 +- **Agent Management Tables**: 2 +- **Device Management Tables**: 1 +- **Voice Recognition Tables**: 1 +- **Communication Tables**: 4 + +## 🔧 Technical Notes + +### Indexing Strategy: +- Primary keys on all tables +- Foreign key indexes for performance +- Composite indexes for complex queries +- Time-based indexes for chat history + +### Data Types: +- **VARCHAR(32)** for UUIDs and IDs +- **JSON** for flexible configuration storage +- **LONGTEXT/LONGBLOB** for large data (embeddings, audio) +- **DATETIME(3)** for millisecond precision timestamps + +### Character Set: +- **utf8mb4** for full Unicode support including emojis + +--- + +*Generated on: 2025-08-20* +*Database Version: Latest* +*Documentation Version: 1.0* diff --git a/main/manager-api/database-visual-schema.md b/main/manager-api/database-visual-schema.md new file mode 100644 index 000000000..9ba16b390 --- /dev/null +++ b/main/manager-api/database-visual-schema.md @@ -0,0 +1,366 @@ +# Xiaozhi ESP32 Server - Database Visual Schema + +## 🎨 ASCII Art Database Relationship Diagram + +``` +┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ XIAOZHI ESP32 SERVER DATABASE SCHEMA │ +│ 16 Tables - 6 Categories │ +└─────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + +┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ 🔐 SYSTEM MANAGEMENT LAYER │ +└─────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + + ┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐ + │ sys_user │◄────────┤ sys_user_token │ │ sys_params │ + │ ─────────────────── │ 1:1 │ ─────────────────── │ │ ─────────────────── │ + │ 🔑 id (PK) │ │ 🔑 id (PK) │ │ 🔑 id (PK) │ + │ 🔒 username (UK) │ │ 🔗 user_id (FK) │ │ 🔒 param_code (UK) │ + │ password │ │ 🔒 token (UK) │ │ param_value │ + │ super_admin │ │ expire_date │ │ param_type │ + │ status │ │ create_date │ │ remark │ + │ create_date │ │ update_date │ │ creator │ + │ creator │ └─────────────────────┘ │ create_date │ + │ updater │ │ updater │ + │ update_date │ │ update_date │ + └─────────────────────┘ └─────────────────────┘ + │ + │ 1:M + ▼ + ┌─────────────────────┐ ┌─────────────────────┐ + │ sys_dict_type │◄────────┤ sys_dict_data │ + │ ─────────────────── │ 1:M │ ─────────────────── │ + │ 🔑 id (PK) │ │ 🔑 id (PK) │ + │ 🔒 dict_type (UK) │ │ 🔗 dict_type_id(FK) │ + │ dict_name │ │ dict_label │ + │ remark │ │ dict_value │ + │ sort │ │ remark │ + │ creator │ │ sort │ + │ create_date │ │ creator │ + │ updater │ │ create_date │ + │ update_date │ │ updater │ + └─────────────────────┘ │ update_date │ + └─────────────────────┘ + +┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ 🤖 AI MODEL CONFIGURATION LAYER │ +└─────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + + ┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐ + │ ai_model_provider │ │ ai_model_config │◄────────┤ ai_tts_voice │ + │ ─────────────────── │ │ ─────────────────── │ 1:M │ ─────────────────── │ + │ 🔑 id (PK) │ │ 🔑 id (PK) │ │ 🔑 id (PK) │ + │ model_type │ │ model_type │ │ 🔗 tts_model_id(FK) │ + │ provider_code │ │ model_code │ │ name │ + │ name │ │ model_name │ │ tts_voice │ + │ fields (JSON) │ │ is_default │ │ languages │ + │ sort │ │ is_enabled │ │ voice_demo │ + │ creator │ │ config_json │ │ remark │ + │ create_date │ │ doc_link │ │ sort │ + │ updater │ │ remark │ │ creator │ + │ update_date │ │ sort │ │ create_date │ + └─────────────────────┘ │ creator │ │ updater │ + │ create_date │ │ update_date │ + │ updater │ └─────────────────────┘ + │ update_date │ + └─────────────────────┘ + │ + │ M:M (via agent configs) + ▼ + +┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ 🧠 AI AGENT MANAGEMENT LAYER │ +└─────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + + ┌─────────────────────┐ ┌─────────────────────┐ + │ ai_agent_template │────────►│ ai_agent │◄─────────┐ + │ ─────────────────── │ template│ ─────────────────── │ │ + │ 🔑 id (PK) │ base │ 🔑 id (PK) │ │ + │ agent_code │ │ 🔗 user_id (FK) │ │ 1:M + │ agent_name │ │ agent_code │ │ + │ asr_model_id │ │ agent_name │ │ + │ vad_model_id │ │ asr_model_id │ │ + │ llm_model_id │ │ vad_model_id │ │ + │ vllm_model_id │ │ llm_model_id │ │ + │ tts_model_id │ │ vllm_model_id │ │ + │ tts_voice_id │ │ tts_model_id │ │ + │ mem_model_id │ │ tts_voice_id │ │ + │ intent_model_id │ │ mem_model_id │ │ + │ system_prompt │ │ intent_model_id │ │ + │ lang_code │ │ system_prompt │ │ + │ language │ │ lang_code │ │ + │ sort │ │ language │ │ + │ creator │ │ sort │ │ + │ created_at │ │ creator │ │ + │ updater │ │ created_at │ │ + │ updated_at │ │ updater │ │ + └─────────────────────┘ │ updated_at │ │ + └─────────────────────┘ │ + │ │ + │ 1:M │ + ▼ │ + │ + ┌─────────────────────┐ │ + │ sys_user │──────────┘ + │ ─────────────────── │ + │ 🔑 id (PK) │ + │ 🔒 username (UK) │ + │ password │ + │ super_admin │ + │ status │ + │ create_date │ + │ creator │ + │ updater │ + │ update_date │ + └─────────────────────┘ + +┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ 📱 DEVICE MANAGEMENT LAYER │ +└─────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + + ┌─────────────────────┐ ┌─────────────────────┐ + │ ai_device │◄────────┤ ai_agent │ + │ ─────────────────── │ M:1 │ ─────────────────── │ + │ 🔑 id (PK) │ │ 🔑 id (PK) │ + │ 🔗 user_id (FK) │ │ 🔗 user_id (FK) │ + │ mac_address │ │ agent_code │ + │ last_connected │ │ agent_name │ + │ auto_update │ │ asr_model_id │ + │ board │ │ vad_model_id │ + │ alias │ │ llm_model_id │ + │ 🔗 agent_id (FK) │ │ vllm_model_id │ + │ app_version │ │ tts_model_id │ + │ sort │ │ tts_voice_id │ + │ creator │ │ mem_model_id │ + │ create_date │ │ intent_model_id │ + │ updater │ │ system_prompt │ + │ update_date │ │ lang_code │ + └─────────────────────┘ │ language │ + │ │ sort │ + │ 1:M │ creator │ + ▼ │ created_at │ + │ updater │ + │ updated_at │ + └─────────────────────┘ + +┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ 🔊 VOICE RECOGNITION LAYER │ +└─────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + + ┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐ + │ ai_voiceprint │◄────────┤ sys_user │────────►│ ai_agent │ + │ ─────────────────── │ M:1 │ ─────────────────── │ 1:M │ ─────────────────── │ + │ 🔑 id (PK) │ │ 🔑 id (PK) │ │ 🔑 id (PK) │ + │ name │ │ 🔒 username (UK) │ │ 🔗 user_id (FK) │ + │ 🔗 user_id (FK) │ │ password │ │ agent_code │ + │ 🔗 agent_id (FK) │ │ super_admin │ │ agent_name │ + │ agent_code │ │ status │ │ asr_model_id │ + │ agent_name │ │ create_date │ │ vad_model_id │ + │ description │ │ creator │ │ llm_model_id │ + │ embedding │ │ updater │ │ vllm_model_id │ + │ memory │ │ update_date │ │ tts_model_id │ + │ sort │ └─────────────────────┘ │ tts_voice_id │ + │ creator │ │ mem_model_id │ + │ created_at │ │ intent_model_id │ + │ updater │ │ system_prompt │ + │ updated_at │ │ lang_code │ + └─────────────────────┘ │ language │ + │ sort │ + │ creator │ + │ created_at │ + │ updater │ + │ updated_at │ + └─────────────────────┘ + +┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ 💬 CHAT & COMMUNICATION LAYER │ +└─────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + + ┌─────────────────────┐ + │ sys_user │ + │ ─────────────────── │ + │ 🔑 id (PK) │ + │ 🔒 username (UK) │ + │ password │ + │ super_admin │ + │ status │ + │ create_date │ + │ creator │ + │ updater │ + │ update_date │ + └─────────────────────┘ + │ + │ 1:M + ▼ + ┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐ + │ ai_chat_history │◄────────┤ ai_agent │────────►│ ai_device │ + │ ─────────────────── │ M:1 │ ─────────────────── │ 1:M │ ─────────────────── │ + │ 🔑 id (PK) │ │ 🔑 id (PK) │ │ 🔑 id (PK) │ + │ 🔗 user_id (FK) │ │ 🔗 user_id (FK) │ │ 🔗 user_id (FK) │ + │ 🔗 agent_id (FK) │ │ agent_code │ │ mac_address │ + │ 🔗 device_id (FK) │ │ agent_name │ │ last_connected │ + │ message_count │ │ asr_model_id │ │ auto_update │ + │ creator │ │ vad_model_id │ │ board │ + │ create_date │ │ llm_model_id │ │ alias │ + │ updater │ │ vllm_model_id │ │ 🔗 agent_id (FK) │ + │ update_date │ │ tts_model_id │ │ app_version │ + └─────────────────────┘ │ tts_voice_id │ │ sort │ + │ │ mem_model_id │ │ creator │ + │ 1:M │ intent_model_id │ │ create_date │ + ▼ │ system_prompt │ │ updater │ + ┌─────────────────────┐ │ lang_code │ │ update_date │ + │ ai_chat_message │ │ language │ └─────────────────────┘ + │ ─────────────────── │ │ sort │ │ + │ 🔑 id (PK) │ │ creator │ │ via mac_address + │ 🔗 user_id (FK) │ │ created_at │ │ + │ 🔗 chat_id (FK) │ │ updater │ ▼ + │ role (ENUM) │ │ updated_at │ ┌─────────────────────┐ + │ content │ └─────────────────────┘ │ai_agent_chat_history│ + │ prompt_tokens │ │ │ ─────────────────── │ + │ total_tokens │ │ 1:M │ 🔑 id (PK) │ + │ completion_tokens│ ▼ │ mac_address │ + │ prompt_ms │ │ 🔗 agent_id (FK) │ + │ total_ms │ │ session_id │ + │ completion_ms │ │ chat_type │ + │ creator │ │ content │ + │ create_date │ │ 🔗 audio_id (FK) │ + │ updater │ │ created_at │ + │ update_date │ │ updated_at │ + └─────────────────────┘ └─────────────────────┘ + │ + │ 1:1 + ▼ + ┌─────────────────────┐ + │ai_agent_chat_audio │ + │ ─────────────────── │ + │ 🔑 id (PK) │ + │ audio (LONGBLOB) │ + └─────────────────────┘ + +┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ 📊 RELATIONSHIP SUMMARY │ +└─────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + +🔗 PRIMARY RELATIONSHIPS: +├── sys_user (1) ──────────── (M) ai_agent │ Users own multiple AI agents +├── sys_user (1) ──────────── (M) ai_device │ Users own multiple ESP32 devices +├── sys_user (1) ──────────── (M) ai_voiceprint │ Users have multiple voiceprints +├── sys_user (1) ──────────── (M) ai_chat_history │ Users participate in multiple chats +├── sys_user (1) ──────────── (1) sys_user_token │ Each user has one active token +├── ai_agent (1) ─────────── (M) ai_device │ Agent can be assigned to multiple devices +├── ai_agent (1) ─────────── (M) ai_chat_history │ Agent participates in multiple chats +├── ai_agent (1) ─────────── (M) ai_agent_chat_history │ Agent has multiple device interactions +├── ai_model_config (1) ──── (M) ai_tts_voice │ TTS models have multiple voices +└── ai_chat_history (1) ──── (M) ai_chat_message │ Chat sessions contain multiple messages + +🔗 SECONDARY RELATIONSHIPS: +├── sys_dict_type (1) ──────── (M) sys_dict_data │ Dictionary types contain multiple entries +├── ai_agent_template ────────── ai_agent │ Templates used to create agents +├── ai_device ───────────────── ai_agent_chat_history │ Devices connect via MAC address +└── ai_agent_chat_history (1) ── (1) ai_agent_chat_audio │ Chat entries may have audio data + +🔗 MODEL CONFIGURATION RELATIONSHIPS: +├── ai_agent.asr_model_id ────── ai_model_config.id │ Speech Recognition Model +├── ai_agent.vad_model_id ────── ai_model_config.id │ Voice Activity Detection Model +├── ai_agent.llm_model_id ────── ai_model_config.id │ Large Language Model +├── ai_agent.vllm_model_id ───── ai_model_config.id │ Vision Language Model +├── ai_agent.tts_model_id ────── ai_model_config.id │ Text-to-Speech Model +├── ai_agent.mem_model_id ────── ai_model_config.id │ Memory Model +├── ai_agent.intent_model_id ─── ai_model_config.id │ Intent Recognition Model +└── ai_agent.tts_voice_id ────── ai_tts_voice.id │ TTS Voice Configuration + +┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ 🔑 LEGEND │ +└─────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + +SYMBOLS: +🔑 PK = Primary Key +🔗 FK = Foreign Key +🔒 UK = Unique Key +(1) = One (in relationship) +(M) = Many (in relationship) +◄────────┤ = One-to-Many relationship (arrow points to "One" side) +────────► = Many-to-One relationship (arrow points to "One" side) +│ = Connection line +▼ = Relationship flow direction + +TABLE CATEGORIES: +🔐 System Management = User authentication, system configuration +🤖 AI Model Config = AI model providers, configurations, voices +🧠 AI Agent Management = Agent templates and user-created agents +📱 Device Management = ESP32 device information and assignments +🔊 Voice Recognition = Voiceprint storage and recognition +💬 Chat & Communication = Web and device-based chat systems + +DATA TYPES: +VARCHAR(n) = Variable character string +BIGINT = 64-bit integer +TINYINT = 8-bit integer +DATETIME = Date and time +JSON = JSON object +TEXT = Large text field +LONGTEXT = Very large text field +LONGBLOB = Large binary object +ENUM = Enumerated values + +┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ 🎯 SYSTEM FLOW │ +└─────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + +1. USER REGISTRATION & LOGIN + sys_user → sys_user_token (Authentication) + +2. AI AGENT CREATION + sys_user → ai_agent_template → ai_agent (Agent setup) + ai_model_config → ai_agent (Model assignment) + ai_tts_voice → ai_agent (Voice assignment) + +3. DEVICE MANAGEMENT + sys_user → ai_device (Device ownership) + ai_agent → ai_device (Agent assignment) + +4. VOICE RECOGNITION + sys_user → ai_voiceprint → ai_agent (Voice training) + +5. COMMUNICATION CHANNELS + A) Web Interface: + sys_user → ai_chat_history → ai_chat_message + + B) Device Interface: + ai_device → ai_agent_chat_history → ai_agent_chat_audio + +6. SYSTEM CONFIGURATION + sys_params (System settings) + sys_dict_type → sys_dict_data (System dictionaries) + +┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ 📈 DATABASE STATISTICS │ +└─────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + +TOTAL TABLES: 16 +├── System Management: 5 tables (31.25%) +├── AI Model Config: 3 tables (18.75%) +├── AI Agent Management: 2 tables (12.50%) +├── Device Management: 1 table (6.25%) +├── Voice Recognition: 1 table (6.25%) +└── Chat & Communication: 4 tables (25.00%) + +RELATIONSHIP TYPES: +├── One-to-One: 2 relationships +├── One-to-Many: 12 relationships +├── Many-to-Many: 7 relationships (via foreign keys) +└── Template-based: 1 relationship + +KEY FEATURES: +✅ Multi-user support with role-based access +✅ Modular AI pipeline (7 different model types) +✅ Dual communication channels (Web + Device) +✅ Voice recognition and personalization +✅ Device management with firmware tracking +✅ Comprehensive chat history and analytics +✅ Flexible system configuration +✅ Template-based agent creation + +--- +Generated: 2025-08-20 | Version: 1.0 | Format: ASCII Art Visualization diff --git a/main/manager-api/pom.xml b/main/manager-api/pom.xml index 8f7a92d6b..874a743a0 100644 --- a/main/manager-api/pom.xml +++ b/main/manager-api/pom.xml @@ -17,13 +17,15 @@ UTF-8 UTF-8 - 17 + 21 5.10.1 1.2.20 3.5.5 5.8.24 1.19.1 4.6.0 + 2.8.8 + 3.18.0 2.0.2 1.6.2 33.0.0-jre @@ -75,6 +77,7 @@ ${captcha.version} + org.springframework.boot spring-boot-starter-websocket @@ -190,11 +193,24 @@ jsoup ${jsoup.version} + com.github.xingfudeshi knife4j-openapi3-jakarta-spring-boot-starter ${knife4j.version} + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + ${springdoc.version} + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + org.projectlombok lombok diff --git a/main/manager-api/railway-setup.md b/main/manager-api/railway-setup.md new file mode 100644 index 000000000..94b13de97 --- /dev/null +++ b/main/manager-api/railway-setup.md @@ -0,0 +1,78 @@ +# Railway Database Setup Guide + +## Step 1: Create Railway MySQL Database + +1. Go to [Railway.app](https://railway.app) and create an account +2. Create a new project +3. Click "Add Service" → "Database" → "MySQL" +4. Wait for the database to be provisioned + +## Step 2: Get Database Connection Details + +In your Railway dashboard, click on your MySQL service and go to the "Variables" tab. You'll find: + +- `MYSQL_HOST` (e.g., `containers-us-west-xxx.railway.app`) +- `MYSQL_PORT` (usually `3306`) +- `MYSQL_DATABASE` (usually `railway`) +- `MYSQL_USER` (usually `root`) +- `MYSQL_PASSWORD` (auto-generated) + +## Step 3: Configure Your Application + +### Option A: Update application-dev.yml directly + +Replace the placeholders in `main/manager-api/src/main/resources/application-dev.yml`: + +```yaml +url: jdbc:mysql://YOUR_RAILWAY_HOST:YOUR_RAILWAY_PORT/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true +username: YOUR_RAILWAY_USERNAME +password: YOUR_RAILWAY_PASSWORD +``` + +### Option B: Use Railway profile (Recommended) + +1. Update `application.yml` to use the railway profile: + ```yaml + spring: + profiles: + active: railway + ``` + +2. Set environment variables when running your application: + ```bash + export RAILWAY_DATABASE_URL="jdbc:mysql://YOUR_HOST:3306/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true" + export RAILWAY_DATABASE_USERNAME="root" + export RAILWAY_DATABASE_PASSWORD="your_password" + ``` + +### Option C: Use Railway's DATABASE_URL (Most convenient) + +Railway provides a `DATABASE_URL` environment variable. You can modify your configuration to use it directly: + +```yaml +spring: + datasource: + url: ${DATABASE_URL} +``` + +## Step 4: Initialize Database Schema + +The application uses Liquibase to automatically create the database schema when it starts. Make sure your Railway database is accessible and the application will create all necessary tables. + +## Step 5: Test Connection + +Run your manager-api application and check the logs. You should see successful database connection messages instead of the previous error. + +## Troubleshooting + +1. **SSL Connection Issues**: Make sure `useSSL=true` and `allowPublicKeyRetrieval=true` are in your connection URL +2. **Timeout Issues**: Railway databases may have connection limits. Consider adding connection timeout parameters +3. **Firewall Issues**: Railway databases are accessible from anywhere by default, so no firewall configuration needed + +## Example Railway Connection String + +``` +jdbc:mysql://containers-us-west-123.railway.app:3306/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true&connectTimeout=30000&socketTimeout=30000 +``` + +Replace `containers-us-west-123.railway.app` with your actual Railway host. 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 518ebc70c..bf7476004 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 @@ -91,11 +91,6 @@ public interface Constant { */ String SERVER_WEBSOCKET = "server.websocket"; - /** - * mqtt gateway 配置 - */ - String SERVER_MQTT_GATEWAY = "server.mqtt_gateway"; - /** * ota地址 */ @@ -121,6 +116,11 @@ public interface Constant { */ String SERVER_MCP_ENDPOINT = "server.mcp_endpoint"; + /** + * mcp接入点路径 + */ + String SERVER_VOICE_PRINT = "server.voice_print"; + /** * 无记忆 */ @@ -237,7 +237,7 @@ public interface Constant { /** * 版本号 */ - public static final String VERSION = "0.6.2"; + public static final String VERSION = "0.7.5"; /** * 无效固件URL diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonRpcTwo.java b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonRpcTwo.java new file mode 100644 index 000000000..c522a61dc --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonRpcTwo.java @@ -0,0 +1,21 @@ +package xiaozhi.common.utils; + +import lombok.Data; +/** + * JSON-RPC2.0 格式规范对象 + */ +@Data +public class JsonRpcTwo { + private String jsonrpc = "2.0"; + private String method; + private Object params; + private Integer id; + + public JsonRpcTwo(String method, Object params, Integer id) { + this.method = method; + this.params = params; + this.id = id; + } + + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java index 6d628d381..288dae9ab 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java @@ -66,4 +66,5 @@ public class JsonUtils { throw new RuntimeException(e); } } + } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/AgentChatHistoryType.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/AgentChatHistoryType.java new file mode 100644 index 000000000..49ed2dce7 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/AgentChatHistoryType.java @@ -0,0 +1,21 @@ +package xiaozhi.modules.agent.Enums; + + +import lombok.Getter; + +/** + * 智能体聊天记录类型 + */ +@Getter +public enum AgentChatHistoryType { + + USER((byte) 1), + AGENT((byte) 2); + + private final byte value; + + AgentChatHistoryType(byte i) { + this.value = i; + } + +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/XiaoZhiMcpJsonRpcJson.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/XiaoZhiMcpJsonRpcJson.java new file mode 100644 index 000000000..114b1ab95 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/Enums/XiaoZhiMcpJsonRpcJson.java @@ -0,0 +1,44 @@ +package xiaozhi.modules.agent.Enums; + +import xiaozhi.common.utils.JsonUtils; +import xiaozhi.common.utils.JsonRpcTwo; + +import java.util.Map; + + +/** + * 小智MCP JSON-RPC 请求json + */ +public class XiaoZhiMcpJsonRpcJson { + //小智初始化mcp请求json + private static final String INITIALIZE_JSON; + //小智mcp初始化成功,返回通知请求json + private static final String NOTIFICATIONS_INITIALIZED_JSON; + //小智mcp获取mcp工具集合请求json + private static final String TOOLS_LIST_REQUEST; + // 延迟加载 + static { + INITIALIZE_JSON = JsonUtils.toJsonString(new JsonRpcTwo("initialize", + Map.of( + "protocolVersion", "2024-11-05", + "capabilities", Map.of( + "roots", Map.of("listChanged", false), + "sampling", Map.of()), + "clientInfo", Map.of( + "name", "xz-mcp-broker", + "version", "0.0.1")), + 1)); + NOTIFICATIONS_INITIALIZED_JSON = "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}"; + TOOLS_LIST_REQUEST = JsonUtils.toJsonString(new JsonRpcTwo("tools/list", null, 2)); + } + public static String getInitializeJson(){ + return INITIALIZE_JSON; + } + public static String getNotificationsInitializedJson(){ + return NOTIFICATIONS_INITIALIZED_JSON; + } + public static String getToolsListJson(){ + return TOOLS_LIST_REQUEST; + } + +} 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 bfd82e414..a4ad08632 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 @@ -47,6 +47,7 @@ import xiaozhi.modules.agent.service.AgentChatHistoryService; import xiaozhi.modules.agent.service.AgentPluginMappingService; import xiaozhi.modules.agent.service.AgentService; import xiaozhi.modules.agent.service.AgentTemplateService; +import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO; import xiaozhi.modules.agent.vo.AgentInfoVO; import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.service.DeviceService; @@ -181,6 +182,33 @@ public class AgentController { List result = agentChatHistoryService.getChatHistoryBySessionId(id, sessionId); return new Result>().ok(result); } + @GetMapping("/{id}/chat-history/user") + @Operation(summary = "获取智能体聊天记录(用户)") + @RequiresPermissions("sys:role:normal") + public Result> getRecentlyFiftyByAgentId( + @PathVariable("id") String id) { + // 获取当前用户 + UserDetail user = SecurityUser.getUser(); + + // 检查权限 + if (!agentService.checkAgentPermission(id, user.getId())) { + return new Result>().error("没有权限查看该智能体的聊天记录"); + } + + // 查询聊天记录 + List data = agentChatHistoryService.getRecentlyFiftyByAgentId(id); + return new Result>().ok(data); + } + + @GetMapping("/{id}/chat-history/audio") + @Operation(summary = "获取音频内容") + @RequiresPermissions("sys:role:normal") + public Result getContentByAudioId( + @PathVariable("id") String id) { + // 查询聊天记录 + String data = agentChatHistoryService.getContentByAudioId(id); + return new Result().ok(data); + } @PostMapping("/audio/{audioId}") @Operation(summary = "获取音频下载ID") diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentVoicePrintController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentVoicePrintController.java new file mode 100644 index 000000000..1615cee5f --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentVoicePrintController.java @@ -0,0 +1,86 @@ +package xiaozhi.modules.agent.controller; + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.AllArgsConstructor; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.utils.Result; +import xiaozhi.modules.agent.dto.AgentVoicePrintSaveDTO; +import xiaozhi.modules.agent.dto.AgentVoicePrintUpdateDTO; +import xiaozhi.modules.agent.service.AgentVoicePrintService; +import xiaozhi.modules.agent.vo.AgentVoicePrintVO; +import xiaozhi.modules.security.user.SecurityUser; +import xiaozhi.modules.sys.service.SysParamsService; + +@Tag(name = "智能体声纹管理") +@AllArgsConstructor +@RestController +@RequestMapping("/agent/voice-print") +public class AgentVoicePrintController { + private final AgentVoicePrintService agentVoicePrintService; + private final SysParamsService sysParamsService; + + @PostMapping + @Operation(summary = "创建智能体的声纹") + @RequiresPermissions("sys:role:normal") + public Result save(@RequestBody @Valid AgentVoicePrintSaveDTO dto) { + boolean b = agentVoicePrintService.insert(dto); + if (b) { + return new Result<>(); + } + return new Result().error("智能体的声纹创建失败"); + } + + @PutMapping + @Operation(summary = "更新智能体的对应声纹") + @RequiresPermissions("sys:role:normal") + public Result update(@RequestBody @Valid AgentVoicePrintUpdateDTO dto) { + Long userId = SecurityUser.getUserId(); + boolean b = agentVoicePrintService.update(userId, dto); + if (b) { + return new Result<>(); + } + return new Result().error("智能体的对应声纹更新失败"); + } + + @DeleteMapping("/{id}") + @Operation(summary = "删除智能体对应声纹") + @RequiresPermissions("sys:role:normal") + public Result delete(@PathVariable String id) { + Long userId = SecurityUser.getUserId(); + // 先删除关联的设备 + boolean delete = agentVoicePrintService.delete(userId, id); + if (delete) { + return new Result<>(); + } + return new Result().error("智能体的对应声纹删除失败"); + } + + @GetMapping("/list/{id}") + @Operation(summary = "获取用户指定智能体声纹列表") + @RequiresPermissions("sys:role:normal") + public Result> list(@PathVariable String id) { + String voiceprintUrl = sysParamsService.getValue("server.voice_print", true); + if (StringUtils.isBlank(voiceprintUrl) || "null".equals(voiceprintUrl)) { + throw new RenException("声纹接口未配置,请先在参数配置中配置声纹接口地址(server.voice_print)"); + } + Long userId = SecurityUser.getUserId(); + List list = agentVoicePrintService.list(userId, id); + return new Result>().ok(list); + } + +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentVoicePrintDao.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentVoicePrintDao.java new file mode 100644 index 000000000..1a5ee3649 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentVoicePrintDao.java @@ -0,0 +1,20 @@ +package xiaozhi.modules.agent.dao; + +import org.apache.ibatis.annotations.Mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import xiaozhi.modules.agent.entity.AgentChatHistoryEntity; +import xiaozhi.modules.agent.entity.AgentVoicePrintEntity; + +/** + * {@link AgentChatHistoryEntity} 智能体聊天历史记录Dao对象 + * + * @author Goody + * @version 1.0, 2025/4/30 + * @since 1.0.0 + */ +@Mapper +public interface AgentVoicePrintDao extends BaseMapper { + +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintSaveDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintSaveDTO.java new file mode 100644 index 000000000..0ff3b0cad --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintSaveDTO.java @@ -0,0 +1,28 @@ +package xiaozhi.modules.agent.dto; + +import lombok.Data; + +/** + * 保存智能体声纹的dto + * + * @author zjy + */ +@Data +public class AgentVoicePrintSaveDTO { + /** + * 关联的智能体id + */ + private String agentId; + /** + * 音频文件id + */ + private String audioId; + /** + * 声纹来源的人姓名 + */ + private String sourceName; + /** + * 描述声纹来源的人 + */ + private String introduce; +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintUpdateDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintUpdateDTO.java new file mode 100644 index 000000000..60643e294 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentVoicePrintUpdateDTO.java @@ -0,0 +1,28 @@ +package xiaozhi.modules.agent.dto; + +import lombok.Data; + +/** + * 修改智能体声纹的dto + * + * @author zjy + */ +@Data +public class AgentVoicePrintUpdateDTO { + /** + * 智能体声纹id + */ + private String id; + /** + * 音频文件id + */ + private String audioId; + /** + * 声纹来源的人姓名 + */ + private String sourceName; + /** + * 描述声纹来源的人 + */ + private String introduce; +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/IdentifyVoicePrintResponse.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/IdentifyVoicePrintResponse.java new file mode 100644 index 000000000..14ce57c2b --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/IdentifyVoicePrintResponse.java @@ -0,0 +1,21 @@ +package xiaozhi.modules.agent.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.Data; + +/** + * 声纹识别接口返回的对象 + */ +@Data +public class IdentifyVoicePrintResponse { + /** + * 最匹配的声纹id + */ + @JsonProperty("speaker_id") + private String speakerId; + /** + * 声纹的分数 + */ + private Double score; +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/McpJsonRpcRequest.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/McpJsonRpcRequest.java deleted file mode 100644 index e4fac0027..000000000 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/McpJsonRpcRequest.java +++ /dev/null @@ -1,32 +0,0 @@ -package xiaozhi.modules.agent.dto; - -import lombok.Data; - -/** - * MCP JSON-RPC 请求 DTO - */ -@Data -public class McpJsonRpcRequest { - private String jsonrpc = "2.0"; - private String method; - private Object params; - private Integer id; - - public McpJsonRpcRequest() { - } - - public McpJsonRpcRequest(String method) { - this.method = method; - } - - public McpJsonRpcRequest(String method, Object params, Integer id) { - this.method = method; - this.params = params; - this.id = id; - } - - public McpJsonRpcRequest(String method, Object params) { - this.method = method; - this.params = params; - } -} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentVoicePrintEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentVoicePrintEntity.java new file mode 100644 index 000000000..4998b2888 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentVoicePrintEntity.java @@ -0,0 +1,64 @@ +package xiaozhi.modules.agent.entity; + +import java.util.Date; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; + +import lombok.Data; + +/** + * 智能体声纹表 + * + * @author zjy + */ +@TableName(value = "ai_agent_voice_print") +@Data +public class AgentVoicePrintEntity { + /** + * 主键id + */ + @TableId(type = IdType.ASSIGN_UUID) + private String id; + /** + * 关联的智能体id + */ + private String agentId; + /** + * 关联的音频id + */ + private String audioId; + /** + * 声纹来源的人姓名 + */ + private String sourceName; + /** + * 描述声纹来源的人 + */ + private String introduce; + + /** + * 创建者 + */ + @TableField(fill = FieldFill.INSERT) + private Long creator; + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createDate; + + /** + * 更新者 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Long updater; + /** + * 更新时间 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateDate; +} 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 21fce9880..459b5a5a1 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 @@ -9,6 +9,7 @@ import xiaozhi.common.page.PageData; import xiaozhi.modules.agent.dto.AgentChatHistoryDTO; import xiaozhi.modules.agent.dto.AgentChatSessionDTO; import xiaozhi.modules.agent.entity.AgentChatHistoryEntity; +import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO; /** * 智能体聊天记录表处理service @@ -44,4 +45,30 @@ public interface AgentChatHistoryService extends IService getRecentlyFiftyByAgentId(String agentId); + + /** + * 根据音频数据ID获取聊天内容 + * + * @param audioId 音频id + * @return 聊天内容 + */ + String getContentByAudioId(String audioId); + + + /** + * 查询此音频id是否属于此智能体 + * + * @param audioId 音频id + * @param agentId 音频id + * @return T:属于 F:不属于 + */ + boolean isAudioOwnedByAgent(String audioId,String agentId); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentVoicePrintService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentVoicePrintService.java new file mode 100644 index 000000000..c9d38abd4 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentVoicePrintService.java @@ -0,0 +1,50 @@ +package xiaozhi.modules.agent.service; + +import java.util.List; + +import xiaozhi.modules.agent.dto.AgentVoicePrintSaveDTO; +import xiaozhi.modules.agent.dto.AgentVoicePrintUpdateDTO; +import xiaozhi.modules.agent.vo.AgentVoicePrintVO; + +/** + * 智能体声纹处理service + * + * @author zjy + */ +public interface AgentVoicePrintService { + /** + * 添加智能体新的声纹 + * + * @param dto 保存智能体声纹的数据 + * @return T:成功 F:失败 + */ + boolean insert(AgentVoicePrintSaveDTO dto); + + /** + * 删除智能体的指的声纹 + * + * @param userId 当前登录的用户id + * @param voicePrintId 声纹id + * @return 是否成功 T:成功 F:失败 + */ + boolean delete(Long userId, String voicePrintId); + + /** + * 获取指定智能体的所有声纹数据 + * + * @param userId 当前登录的用户id + * @param agentId 智能体id + * @return 声纹数据集合 + */ + List list(Long userId, String agentId); + + /** + * 更新智能体的指的声纹数据 + * + * @param userId 当前登录的用户id + * @param dto 修改的声纹的数据 + * @return 是否成功 T:成功 F:失败 + */ + boolean update(Long userId, AgentVoicePrintUpdateDTO dto); + +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatHistoryServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatHistoryServiceImpl.java index b28e80ad0..76da2fc83 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatHistoryServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentChatHistoryServiceImpl.java @@ -8,6 +8,7 @@ import java.util.stream.Collectors; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; @@ -16,11 +17,14 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import xiaozhi.common.constant.Constant; import xiaozhi.common.page.PageData; import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.common.utils.JsonUtils; +import xiaozhi.modules.agent.Enums.AgentChatHistoryType; import xiaozhi.modules.agent.dao.AiAgentChatHistoryDao; import xiaozhi.modules.agent.dto.AgentChatHistoryDTO; import xiaozhi.modules.agent.dto.AgentChatSessionDTO; import xiaozhi.modules.agent.entity.AgentChatHistoryEntity; import xiaozhi.modules.agent.service.AgentChatHistoryService; +import xiaozhi.modules.agent.vo.AgentChatHistoryUserVO; /** * 智能体聊天记录表处理service {@link AgentChatHistoryService} impl @@ -90,4 +94,78 @@ public class AgentChatHistoryServiceImpl extends ServiceImpl getRecentlyFiftyByAgentId(String agentId) { + // 构建查询条件(不添加按照创建时间排序,数据本来就是主键越大创建时间越大 + // 不添加这样可以减少排序全部数据在分页的全盘扫描消耗) + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.select(AgentChatHistoryEntity::getContent, AgentChatHistoryEntity::getAudioId) + .eq(AgentChatHistoryEntity::getAgentId, agentId) + .eq(AgentChatHistoryEntity::getChatType, AgentChatHistoryType.USER.getValue()) + .isNotNull(AgentChatHistoryEntity::getAudioId) + // 添加此行,确保查询结果按照创建时间降序排列 + // 使用id的原因:数据形式,id越大的创建时间就越晚,所以使用id的结果和创建时间降序排列结果一样 + // id作为降序排列的优势,性能高,有主键索引,不用在排序的时候重新进行排除扫描比较 + .orderByDesc(AgentChatHistoryEntity::getId); + + // 构建分页查询,查询前50页数据 + Page pageParam = new Page<>(0, 50); + IPage result = this.baseMapper.selectPage(pageParam, wrapper); + return result.getRecords().stream().map(item -> { + AgentChatHistoryUserVO vo = ConvertUtils.sourceToTarget(item, AgentChatHistoryUserVO.class); + // 处理 content 字段,确保只返回聊天内容 + if (vo != null && vo.getContent() != null) { + vo.setContent(extractContentFromString(vo.getContent())); + } + return vo; + }).toList(); + } + + /** + * 从 content 字段中提取聊天内容 + * 如果 content 是 JSON 格式(如 {"speaker": "未知说话人", "content": "现在几点了。"}),则提取 content + * 字段 + * 如果 content 是普通字符串,则直接返回 + * + * @param content 原始内容 + * @return 提取的聊天内容 + */ + private String extractContentFromString(String content) { + if (content == null || content.trim().isEmpty()) { + return content; + } + + // 尝试解析为 JSON + try { + Map jsonMap = JsonUtils.parseObject(content, Map.class); + if (jsonMap != null && jsonMap.containsKey("content")) { + Object contentObj = jsonMap.get("content"); + return contentObj != null ? contentObj.toString() : content; + } + } catch (Exception e) { + // 如果不是有效的 JSON,直接返回原内容 + } + + // 如果不是 JSON 格式或没有 content 字段,直接返回原内容 + return content; + } + + @Override + public String getContentByAudioId(String audioId) { + AgentChatHistoryEntity agentChatHistoryEntity = baseMapper + .selectOne(new LambdaQueryWrapper() + .select(AgentChatHistoryEntity::getContent) + .eq(AgentChatHistoryEntity::getAudioId, audioId)); + return agentChatHistoryEntity == null ? null : agentChatHistoryEntity.getContent(); + } + + @Override + public boolean isAudioOwnedByAgent(String audioId, String agentId) { + // 查询是否有指定音频id和智能体id的数据,如果有且只有一条说明此数据属性此智能体 + Long row = baseMapper.selectCount(new LambdaQueryWrapper() + .eq(AgentChatHistoryEntity::getAudioId, audioId) + .eq(AgentChatHistoryEntity::getAgentId, agentId)); + return row == 1; + } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentMcpAccessPointServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentMcpAccessPointServiceImpl.java index e6c7d4e4e..7d96f748c 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentMcpAccessPointServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentMcpAccessPointServiceImpl.java @@ -18,7 +18,7 @@ import xiaozhi.common.constant.Constant; import xiaozhi.common.utils.AESUtils; import xiaozhi.common.utils.HashEncryptionUtil; import xiaozhi.common.utils.JsonUtils; -import xiaozhi.modules.agent.dto.McpJsonRpcRequest; +import xiaozhi.modules.agent.Enums.XiaoZhiMcpJsonRpcJson; import xiaozhi.modules.agent.service.AgentMcpAccessPointService; import xiaozhi.modules.sys.service.SysParamsService; import xiaozhi.modules.sys.utils.WebSocketClientManager; @@ -61,57 +61,79 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic wsUrl = wsUrl.replace("/mcp/", "/call/"); try { - // 创建 WebSocket 连接 + // 创建 WebSocket 连接,增加超时时间到15秒 try (WebSocketClientManager client = WebSocketClientManager.build( new WebSocketClientManager.Builder() .uri(wsUrl) - .connectTimeout(5, TimeUnit.SECONDS) - .maxSessionDuration(9, TimeUnit.SECONDS))) { + .bufferSize(1024 * 1024) + .connectTimeout(8, TimeUnit.SECONDS) + .maxSessionDuration(10, TimeUnit.SECONDS))) { - // 发送初始化消息 - McpJsonRpcRequest initializeRequest = new McpJsonRpcRequest("initialize", - Map.of( - "protocolVersion", "2024-11-05", - "capabilities", Map.of( - "roots", Map.of("listChanged", false), - "sampling", Map.of()), - "clientInfo", Map.of( - "name", "xz-mcp-broker", - "version", "0.0.1")), - 1); - client.sendJson(initializeRequest); + // 步骤1: 发送初始化消息并等待响应 + log.info("发送MCP初始化消息,智能体ID: {}", id); + client.sendText(XiaoZhiMcpJsonRpcJson.getInitializeJson()); - // 等待初始化响应 - Thread.sleep(200); - - // 发送初始化完成通知 - // 对于通知类型的消息,手动构建JSON以避免包含null字段 - String notificationJson = "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}"; - client.sendText(notificationJson); - - // 等待 0.2 秒 - Thread.sleep(200); - - // 发送工具列表请求 - McpJsonRpcRequest toolsRequest = new McpJsonRpcRequest("tools/list", null, 2); - client.sendJson(toolsRequest); - - // 监听响应,直到收到包含 id=2 的响应(tools/list响应) - List responses = client.listener(response -> { + // 等待初始化响应 (id=1) - 移除固定延迟,改为响应驱动 + List initResponses = client.listenerWithoutClose(response -> { try { - // 先尝试解析为通用JSON对象来获取id Map jsonMap = JsonUtils.parseObject(response, Map.class); - return jsonMap != null && Integer.valueOf(2).equals(jsonMap.get("id")); + if (jsonMap != null && Integer.valueOf(1).equals(jsonMap.get("id"))) { + // 检查是否有result字段,表示初始化成功 + return jsonMap.containsKey("result") && !jsonMap.containsKey("error"); + } + return false; } catch (Exception e) { - log.warn("解析响应失败: {}", response, e); + log.warn("解析初始化响应失败: {}", response, e); return false; } }); - // 处理响应 - for (String response : responses) { + // 验证初始化响应 + boolean initSucceeded = false; + for (String response : initResponses) { + try { + Map jsonMap = JsonUtils.parseObject(response, Map.class); + if (jsonMap != null && Integer.valueOf(1).equals(jsonMap.get("id"))) { + if (jsonMap.containsKey("result")) { + log.info("MCP初始化成功,智能体ID: {}", id); + initSucceeded = true; + break; + } else if (jsonMap.containsKey("error")) { + log.error("MCP初始化失败,智能体ID: {}, 错误: {}", id, jsonMap.get("error")); + return List.of(); + } + } + } catch (Exception e) { + log.warn("处理初始化响应失败: {}", response, e); + } + } + + if (!initSucceeded) { + log.error("未收到有效的MCP初始化响应,智能体ID: {}", id); + return List.of(); + } + + // 步骤2: 发送初始化完成通知 - 只有在收到initialize响应后才发送 + log.info("发送MCP初始化完成通知,智能体ID: {}", id); + client.sendText(XiaoZhiMcpJsonRpcJson.getNotificationsInitializedJson()); + // 步骤3: 发送工具列表请求 - 立即发送,无需额外延迟 + log.info("发送MCP工具列表请求,智能体ID: {}", id); + client.sendText(XiaoZhiMcpJsonRpcJson.getToolsListJson()); + + // 等待工具列表响应 (id=2) + List toolsResponses = client.listener(response -> { + try { + Map jsonMap = JsonUtils.parseObject(response, Map.class); + return jsonMap != null && Integer.valueOf(2).equals(jsonMap.get("id")); + } catch (Exception e) { + log.warn("解析工具列表响应失败: {}", response, e); + return false; + } + }); + + // 处理工具列表响应 + for (String response : toolsResponses) { try { - // 先解析为通用JSON对象 Map jsonMap = JsonUtils.parseObject(response, Map.class); if (jsonMap != null && Integer.valueOf(2).equals(jsonMap.get("id"))) { // 检查是否有result字段 @@ -122,11 +144,16 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic if (toolsObj instanceof List) { List> toolsList = (List>) toolsObj; // 提取工具名称列表 - return toolsList.stream() + List result = toolsList.stream() .map(tool -> (String) tool.get("name")) .filter(name -> name != null) .collect(Collectors.toList()); + log.info("成功获取MCP工具列表,智能体ID: {}, 工具数量: {}", id, result.size()); + return result; } + } else if (jsonMap.containsKey("error")) { + log.error("获取工具列表失败,智能体ID: {}, 错误: {}", id, jsonMap.get("error")); + return List.of(); } } } catch (Exception e) { @@ -134,12 +161,12 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic } } - log.warn("未找到有效的工具列表响应"); + log.warn("未找到有效的工具列表响应,智能体ID: {}", id); return List.of(); } } catch (Exception e) { - log.error("获取智能体 MCP 工具列表失败,智能体ID: {}", id, e); + log.error("获取智能体 MCP 工具列表失败,智能体ID: {},错误原因:{}", id, e.getMessage()); return List.of(); } } @@ -204,4 +231,4 @@ public class AgentMcpAccessPointServiceImpl implements AgentMcpAccessPointServic // 加密后成token值 return AESUtils.encrypt(key, json); } -} +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java index 36aa11925..4f5681e28 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 @@ -41,6 +41,7 @@ import xiaozhi.modules.agent.service.AgentTemplateService; import xiaozhi.modules.agent.vo.AgentInfoVO; import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.model.dto.ModelProviderDTO; +import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; import xiaozhi.modules.model.service.ModelProviderService; import xiaozhi.modules.security.user.SecurityUser; @@ -324,9 +325,35 @@ public class AgentServiceImpl extends BaseServiceImpl imp // 删除音频数据 agentChatHistoryService.deleteByAgentId(existingEntity.getId(), true, false); } + + boolean b = validateLLMIntentParams(dto.getLlmModelId(), dto.getIntentModelId()); + if (!b) { + throw new RenException("LLM大模型和Intent意图识别,选择参数不匹配"); + } this.updateById(existingEntity); } + /** + * 验证大语言模型和意图识别的参数是否符合匹配 + * + * @param llmModelId 大语言模型id + * @param intentModelId 意图识别id + * @return T 匹配 : F 不匹配 + */ + private boolean validateLLMIntentParams(String llmModelId, String intentModelId) { + if (StringUtils.isBlank(llmModelId)) { + return true; + } + ModelConfigEntity llmModelData = modelConfigService.selectById(llmModelId); + String type = llmModelData.getConfigJson().get("type").toString(); + // 如果查询大语言模型是openai或者ollama,意图识别选参数都可以 + if ("openai".equals(type) || "ollama".equals(type)) { + return true; + } + // 除了openai和ollama的类型,不可以选择id为Intent_function_call(函数调用)的意图识别 + return !"Intent_function_call".equals(intentModelId); + } + @Override @Transactional(rollbackFor = Exception.class) public String createAgent(AgentCreateDTO dto) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentVoicePrintServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentVoicePrintServiceImpl.java new file mode 100644 index 000000000..31accbab9 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentVoicePrintServiceImpl.java @@ -0,0 +1,410 @@ +package xiaozhi.modules.agent.service.impl; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.concurrent.Executor; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import lombok.extern.slf4j.Slf4j; +import xiaozhi.common.constant.Constant; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.common.utils.JsonUtils; +import xiaozhi.modules.agent.dao.AgentVoicePrintDao; +import xiaozhi.modules.agent.dto.AgentVoicePrintSaveDTO; +import xiaozhi.modules.agent.dto.AgentVoicePrintUpdateDTO; +import xiaozhi.modules.agent.dto.IdentifyVoicePrintResponse; +import xiaozhi.modules.agent.entity.AgentVoicePrintEntity; +import xiaozhi.modules.agent.service.AgentChatAudioService; +import xiaozhi.modules.agent.service.AgentChatHistoryService; +import xiaozhi.modules.agent.service.AgentVoicePrintService; +import xiaozhi.modules.agent.vo.AgentVoicePrintVO; +import xiaozhi.modules.sys.service.SysParamsService; + +/** + * @author zjy + */ +@Service +@Slf4j +public class AgentVoicePrintServiceImpl extends ServiceImpl + implements AgentVoicePrintService { + private final AgentChatAudioService agentChatAudioService; + private final RestTemplate restTemplate; + private final SysParamsService sysParamsService; + private final AgentChatHistoryService agentChatHistoryService; + // Springboot提供的编程事务类 + private final TransactionTemplate transactionTemplate; + // 识别度 + private final Double RECOGNITION = 0.5; + private final Executor taskExecutor; + + public AgentVoicePrintServiceImpl(AgentChatAudioService agentChatAudioService, RestTemplate restTemplate, + SysParamsService sysParamsService, AgentChatHistoryService agentChatHistoryService, + TransactionTemplate transactionTemplate, @Qualifier("taskExecutor") Executor taskExecutor) { + this.agentChatAudioService = agentChatAudioService; + this.restTemplate = restTemplate; + this.sysParamsService = sysParamsService; + this.agentChatHistoryService = agentChatHistoryService; + this.transactionTemplate = transactionTemplate; + this.taskExecutor = taskExecutor; + } + + @Override + public boolean insert(AgentVoicePrintSaveDTO dto) { + // 获取音频数据 + ByteArrayResource resource = getVoicePrintAudioWAV(dto.getAgentId(), dto.getAudioId()); + // 识别一下此声音是否注册过 + IdentifyVoicePrintResponse response = identifyVoicePrint(dto.getAgentId(), resource); + if (response != null && response.getScore() > RECOGNITION) { + // 根据识别出的声纹ID查询对应的用户信息 + AgentVoicePrintEntity existingVoicePrint = baseMapper.selectById(response.getSpeakerId()); + String existingUserName = existingVoicePrint != null ? existingVoicePrint.getSourceName() : "未知用户"; + throw new RenException("此声音声纹对应的人(" + existingUserName + ")已经注册,请选择其他声音注册"); + } + AgentVoicePrintEntity entity = ConvertUtils.sourceToTarget(dto, AgentVoicePrintEntity.class); + // 开启事务 + return Boolean.TRUE.equals(transactionTemplate.execute(status -> { + try { + // 保存声纹信息 + int row = baseMapper.insert(entity); + // 插入一条数据,影响的数据不等于1说明出现了,保存问题回滚 + if (row != 1) { + status.setRollbackOnly(); // 标记事务回滚 + return false; + } + // 发送注册声纹请求 + registerVoicePrint(entity.getId(), resource); + return true; + } catch (RenException e) { + status.setRollbackOnly(); // 标记事务回滚 + throw e; + } catch (Exception e) { + status.setRollbackOnly(); // 标记事务回滚 + log.error("保存声纹错误原因:{}", e.getMessage()); + throw new RenException("保存声纹错误,请联系管理员"); + } + })); + } + + @Override + public boolean delete(Long userId, String voicePrintId) { + // 开启事务 + boolean b = Boolean.TRUE.equals(transactionTemplate.execute(status -> { + try { + // 删除声纹,按照指定当前登录用户和智能体 + int row = baseMapper.delete(new LambdaQueryWrapper() + .eq(AgentVoicePrintEntity::getId, voicePrintId) + .eq(AgentVoicePrintEntity::getCreator, userId)); + if (row != 1) { + status.setRollbackOnly(); // 标记事务回滚 + return false; + } + + return true; + } catch (Exception e) { + status.setRollbackOnly(); // 标记事务回滚 + log.error("删除声纹存在错误原因:{}", e.getMessage()); + throw new RenException("删除声纹出现了错误"); + } + })); + // 数据库声纹数据删除成功才继续执行删除声纹服务的数据 + if(b){ + taskExecutor.execute(()-> { + try { + cancelVoicePrint(voicePrintId); + }catch (RuntimeException e) { + log.error("删除声纹存在运行时错误原因:{},id:{}", e.getMessage(),voicePrintId); + } + }); + } + return b; + } + + @Override + public List list(Long userId, String agentId) { + // 按照指定当前登录用户和智能体查找数据 + List list = baseMapper.selectList(new LambdaQueryWrapper() + .eq(AgentVoicePrintEntity::getAgentId, agentId) + .eq(AgentVoicePrintEntity::getCreator, userId)); + return list.stream().map(entity -> { + // 遍历转换成AgentVoicePrintVO类型 + return ConvertUtils.sourceToTarget(entity, AgentVoicePrintVO.class); + }).toList(); + + } + + @Override + public boolean update(Long userId, AgentVoicePrintUpdateDTO dto) { + AgentVoicePrintEntity agentVoicePrintEntity = baseMapper + .selectOne(new LambdaQueryWrapper() + .eq(AgentVoicePrintEntity::getId, dto.getId()) + .eq(AgentVoicePrintEntity::getCreator, userId)); + if (agentVoicePrintEntity == null) { + return false; + } + // 获取音频Id + String audioId = dto.getAudioId(); + // 获取智能体id + String agentId = agentVoicePrintEntity.getAgentId(); + ByteArrayResource resource; + // audioId不等于空,且audioId和之前的保存的音频id不一样,则需要重新获取音频数据生成声纹 + if (!StringUtils.isEmpty(audioId) && !audioId.equals(agentVoicePrintEntity.getAudioId())) { + resource = getVoicePrintAudioWAV(agentId, audioId); + + // 识别一下此声音是否注册过 + IdentifyVoicePrintResponse response = identifyVoicePrint(agentId, resource); + // 返回分数高于RECOGNITION说明这个声纹已经有了 + if (response != null && response.getScore() > RECOGNITION) { + // 判断返回的id如果不是要修改的声纹id,说明这个声纹id,现在要注册的声音已经存在且不是原来的声纹,不允许修改 + if (!response.getSpeakerId().equals(dto.getId())) { + // 根据识别出的声纹ID查询对应的用户信息 + AgentVoicePrintEntity existingVoicePrint = baseMapper.selectById(response.getSpeakerId()); + String existingUserName = existingVoicePrint != null ? existingVoicePrint.getSourceName() : "未知用户"; + throw new RenException("此次修改不允许,此声音已经注册为声纹了(" + existingUserName + ")"); + } + } + } else { + resource = null; + } + // 开启事务 + return Boolean.TRUE.equals(transactionTemplate.execute(status -> { + try { + AgentVoicePrintEntity entity = ConvertUtils.sourceToTarget(dto, AgentVoicePrintEntity.class); + int row = baseMapper.updateById(entity); + if (row != 1) { + status.setRollbackOnly(); // 标记事务回滚 + return false; + } + if (resource != null) { + String id = entity.getId(); + // 先注销之前这个声纹id上的声纹向量 + cancelVoicePrint(id); + // 发送注册声纹请求 + registerVoicePrint(id, resource); + } + return true; + } catch (RenException e) { + status.setRollbackOnly(); // 标记事务回滚 + throw e; + } catch (Exception e) { + status.setRollbackOnly(); // 标记事务回滚 + log.error("修改声纹错误原因:{}", e.getMessage()); + throw new RenException("修改声纹错误,请联系管理员"); + } + })); + } + + /** + * 获取生纹接口URI对象 + * + * @return URI对象 + */ + private URI getVoicePrintURI() { + // 获取声纹接口地址 + String voicePrint = sysParamsService.getValue(Constant.SERVER_VOICE_PRINT, true); + try { + return new URI(voicePrint); + } catch (URISyntaxException e) { + log.error("路径格式不正确路径:{},\n错误信息:{}", voicePrint, e.getMessage()); + throw new RuntimeException("声纹接口的地址存在错误,请进入参数管理修改声纹接口地址"); + } + } + + /** + * 获取声纹地址基础路径 + * + * @param uri 声纹地址uri + * @return 基础路径 + */ + private String getBaseUrl(URI uri) { + String protocol = uri.getScheme(); + String host = uri.getHost(); + int port = uri.getPort(); + if (port == -1) { + return "%s://%s".formatted(protocol, host); + } else { + return "%s://%s:%s".formatted(protocol, host, port); + } + } + + /** + * 获取验证Authorization + * + * @param uri 声纹地址uri + * @return Authorization值 + */ + private String getAuthorization(URI uri) { + // 获取参数 + String query = uri.getQuery(); + // 获取aes加密密钥 + String str = "key="; + return "Bearer " + query.substring(query.indexOf(str) + str.length()); + } + + /** + * 获取声纹音频资源数据 + * + * @param audioId 音频Id + * @return 声纹音频资源数据 + */ + private ByteArrayResource getVoicePrintAudioWAV(String agentId, String audioId) { + // 判断这个音频是否属于当前智能体 + boolean b = agentChatHistoryService.isAudioOwnedByAgent(audioId, agentId); + if (!b) { + throw new RenException("音频数据不属于这个智能体"); + } + // 获取到音频数据 + byte[] audio = agentChatAudioService.getAudio(audioId); + // 如果音频数据为空的直接报错不进行下去 + if (audio == null || audio.length == 0) { + throw new RenException("音频数据是空的请检查上传数据"); + } + // 将字节数组包装为资源,返回 + return new ByteArrayResource(audio) { + @Override + public String getFilename() { + return "VoicePrint.WAV"; // 设置文件名 + } + }; + } + + /** + * 发送注册声纹http请求 + * + * @param id 声纹id + * @param resource 声纹音频资源 + */ + private void registerVoicePrint(String id, ByteArrayResource resource) { + // 处理声纹接口地址,获取前缀 + URI uri = getVoicePrintURI(); + String baseUrl = getBaseUrl(uri); + String requestUrl = baseUrl + "/voiceprint/register"; + // 创建请求体 + MultiValueMap body = new LinkedMultiValueMap<>(); + body.add("speaker_id", id); + body.add("file", resource); + + // 创建请求头 + HttpHeaders headers = new HttpHeaders(); + headers.set("Authorization", getAuthorization(uri)); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + // 创建请求体 + HttpEntity> requestEntity = new HttpEntity<>(body, headers); + // 发送 POST 请求 + ResponseEntity response = restTemplate.postForEntity(requestUrl, requestEntity, String.class); + + if (response.getStatusCode() != HttpStatus.OK) { + log.error("声纹注册失败,请求路径:{}", requestUrl); + throw new RenException("声纹保存失败,请求不成功"); + } + // 检查响应内容 + String responseBody = response.getBody(); + if (responseBody == null || !responseBody.contains("true")) { + log.error("声纹注册失败,请求处理失败内容:{}", responseBody == null ? "空内容" : responseBody); + throw new RenException("声纹保存失败,请求处理失败"); + } + } + + /** + * 发送注销声纹的请求 + * + * @param voicePrintId 声纹id + */ + private void cancelVoicePrint(String voicePrintId) { + URI uri = getVoicePrintURI(); + String baseUrl = getBaseUrl(uri); + String requestUrl = baseUrl + "/voiceprint/" + voicePrintId; + // 创建请求头 + HttpHeaders headers = new HttpHeaders(); + headers.set("Authorization", getAuthorization(uri)); + // 创建请求体 + HttpEntity> requestEntity = new HttpEntity<>(headers); + + // 发送 POST 请求 + ResponseEntity response = restTemplate.exchange(requestUrl, HttpMethod.DELETE, requestEntity, + String.class); + if (response.getStatusCode() != HttpStatus.OK) { + log.error("声纹注销失败,请求路径:{}", requestUrl); + throw new RenException("声纹注销失败,请求不成功"); + } + // 检查响应内容 + String responseBody = response.getBody(); + if (responseBody == null || !responseBody.contains("true")) { + log.error("声纹注销失败,请求处理失败内容:{}", responseBody == null ? "空内容" : responseBody); + throw new RenException("声纹注销失败,请求处理失败"); + } + } + + /** + * 发送识别声纹http请求 + * + * @param agentId 智能体id + * @param resource 声纹音频资源 + * @return 返回识别数据 + */ + private IdentifyVoicePrintResponse identifyVoicePrint(String agentId, ByteArrayResource resource) { + + // 获取该智能体所有注册的声纹 + List agentVoicePrintList = baseMapper + .selectList(new LambdaQueryWrapper() + .select(AgentVoicePrintEntity::getId) + .eq(AgentVoicePrintEntity::getAgentId, agentId)); + + // 声纹数量为0,说明还没注册过声纹不需要发生识别请求 + if (agentVoicePrintList.isEmpty()) { + return null; + } + // 处理声纹接口地址,获取前缀 + URI uri = getVoicePrintURI(); + String baseUrl = getBaseUrl(uri); + String requestUrl = baseUrl + "/voiceprint/identify"; + // 创建请求体 + MultiValueMap body = new LinkedMultiValueMap<>(); + + // 创建speaker_id参数 + String speakerIds = agentVoicePrintList.stream() + .map(AgentVoicePrintEntity::getId) + .collect(Collectors.joining(",")); + body.add("speaker_ids", speakerIds); + body.add("file", resource); + + // 创建请求头 + HttpHeaders headers = new HttpHeaders(); + headers.set("Authorization", getAuthorization(uri)); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + // 创建请求体 + HttpEntity> requestEntity = new HttpEntity<>(body, headers); + // 发送 POST 请求 + ResponseEntity response = restTemplate.postForEntity(requestUrl, requestEntity, String.class); + + if (response.getStatusCode() != HttpStatus.OK) { + log.error("声纹识别请求失败,请求路径:{}", requestUrl); + throw new RenException("声纹识别失败,请求不成功"); + } + // 检查响应内容 + String responseBody = response.getBody(); + if (responseBody != null) { + return JsonUtils.parseObject(responseBody, IdentifyVoicePrintResponse.class); + } + return null; + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentChatHistoryUserVO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentChatHistoryUserVO.java new file mode 100644 index 000000000..cec0427bc --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentChatHistoryUserVO.java @@ -0,0 +1,16 @@ +package xiaozhi.modules.agent.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +/** + * 智能体用户个人聊天数据的VO + */ +@Data +public class AgentChatHistoryUserVO { + @Schema(description = "聊天内容") + private String content; + + @Schema(description = "音频ID") + private String audioId; +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentVoicePrintVO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentVoicePrintVO.java new file mode 100644 index 000000000..b647e8b8f --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/vo/AgentVoicePrintVO.java @@ -0,0 +1,33 @@ +package xiaozhi.modules.agent.vo; + +import lombok.Data; + +import java.util.Date; + +/** + * 展示智能体声纹列表VO + */ +@Data +public class AgentVoicePrintVO { + + /** + * 主键id + */ + private String id; + /** + * 音频文件id + */ + private String audioId; + /** + * 声纹来源的人姓名 + */ + private String sourceName; + /** + * 描述声纹来源的人 + */ + private String introduce; + /** + * 创建时间 + */ + private Date createDate; +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java index 294dbbe23..476f09cdf 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java @@ -9,20 +9,26 @@ import java.util.Objects; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; + import lombok.AllArgsConstructor; import xiaozhi.common.constant.Constant; import xiaozhi.common.exception.ErrorCode; import xiaozhi.common.exception.RenException; import xiaozhi.common.redis.RedisKeys; import xiaozhi.common.redis.RedisUtils; +import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.JsonUtils; +import xiaozhi.modules.agent.dao.AgentVoicePrintDao; import xiaozhi.modules.agent.entity.AgentEntity; import xiaozhi.modules.agent.entity.AgentPluginMapping; import xiaozhi.modules.agent.entity.AgentTemplateEntity; +import xiaozhi.modules.agent.entity.AgentVoicePrintEntity; import xiaozhi.modules.agent.service.AgentMcpAccessPointService; import xiaozhi.modules.agent.service.AgentPluginMappingService; import xiaozhi.modules.agent.service.AgentService; import xiaozhi.modules.agent.service.AgentTemplateService; +import xiaozhi.modules.agent.vo.AgentVoicePrintVO; import xiaozhi.modules.config.service.ConfigService; import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.service.DeviceService; @@ -45,6 +51,7 @@ public class ConfigServiceImpl implements ConfigService { private final TimbreService timbreService; private final AgentPluginMappingService agentPluginMappingService; private final AgentMcpAccessPointService agentMcpAccessPointService; + private final AgentVoicePrintDao agentVoicePrintDao; @Override public Object getConfig(Boolean isCache) { @@ -162,6 +169,8 @@ public class ConfigServiceImpl implements ConfigService { mcpEndpoint = mcpEndpoint.replace("/mcp/", "/call/"); result.put("mcp_endpoint", mcpEndpoint); } + // 获取声纹信息 + buildVoiceprintConfig(agent.getId(), result); // 构建模块配置 buildModuleConfig( @@ -255,20 +264,76 @@ public class ConfigServiceImpl implements ConfigService { return config; } + /** + * 构建声纹配置信息 + * + * @param agentId 智能体ID + * @param result 结果Map + */ + private void buildVoiceprintConfig(String agentId, Map result) { + try { + // 获取声纹接口地址 + String voiceprintUrl = sysParamsService.getValue("server.voice_print", true); + if (StringUtils.isBlank(voiceprintUrl) || "null".equals(voiceprintUrl)) { + return; + } + + // 获取智能体关联的声纹信息(不需要用户权限验证) + List voiceprints = getVoiceprintsByAgentId(agentId); + if (voiceprints == null || voiceprints.isEmpty()) { + return; + } + + // 构建speakers列表 + List speakers = new ArrayList<>(); + for (AgentVoicePrintVO voiceprint : voiceprints) { + String speakerStr = String.format("%s,%s,%s", + voiceprint.getId(), + voiceprint.getSourceName(), + voiceprint.getIntroduce() != null ? voiceprint.getIntroduce() : ""); + speakers.add(speakerStr); + } + + // 构建声纹配置 + Map voiceprintConfig = new HashMap<>(); + voiceprintConfig.put("url", voiceprintUrl); + voiceprintConfig.put("speakers", speakers); + + result.put("voiceprint", voiceprintConfig); + } catch (Exception e) { + // 声纹配置获取失败时不影响其他功能 + System.err.println("获取声纹配置失败: " + e.getMessage()); + } + } + + /** + * 获取智能体关联的声纹信息 + * + * @param agentId 智能体ID + * @return 声纹信息列表 + */ + private List getVoiceprintsByAgentId(String agentId) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(AgentVoicePrintEntity::getAgentId, agentId); + queryWrapper.orderByAsc(AgentVoicePrintEntity::getCreateDate); + List entities = agentVoicePrintDao.selectList(queryWrapper); + return ConvertUtils.sourceToTarget(entities, AgentVoicePrintVO.class); + } + /** * 构建模块配置 * - * @param prompt 提示词 - * @param voice 音色 - * @param referenceAudio 参考音频路径 - * @param referenceText 参考文本 - * @param vadModelId VAD模型ID - * @param asrModelId ASR模型ID - * @param llmModelId LLM模型ID - * @param ttsModelId TTS模型ID - * @param memModelId 记忆模型ID - * @param intentModelId 意图模型ID - * @param result 结果Map + * @param prompt 提示词 + * @param voice 音色 + * @param referenceAudio 参考音频路径 + * @param referenceText 参考文本 + * @param vadModelId VAD模型ID + * @param asrModelId ASR模型ID + * @param llmModelId LLM模型ID + * @param ttsModelId TTS模型ID + * @param memModelId 记忆模型ID + * @param intentModelId 意图模型ID + * @param result 结果Map */ private void buildModuleConfig( String assistantName, @@ -298,14 +363,20 @@ public class ConfigServiceImpl implements ConfigService { continue; } ModelConfigEntity model = modelConfigService.getModelById(modelIds[i], isCache); + if (model == null) { + continue; + } Map typeConfig = new HashMap<>(); if (model.getConfigJson() != null) { typeConfig.put(model.getId(), model.getConfigJson()); // 如果是TTS类型,添加private_voice属性 - if ("TTS".equals(modelTypes[i])){ - if (voice != null) ((Map) model.getConfigJson()).put("private_voice", voice); - if (referenceAudio != null) ((Map) model.getConfigJson()).put("ref_audio", referenceAudio); - if (referenceText != null) ((Map) model.getConfigJson()).put("ref_text", referenceText); + if ("TTS".equals(modelTypes[i])) { + if (voice != null) + ((Map) model.getConfigJson()).put("private_voice", voice); + if (referenceAudio != null) + ((Map) model.getConfigJson()).put("ref_audio", referenceAudio); + if (referenceText != null) + ((Map) model.getConfigJson()).put("ref_text", referenceText); } // 如果是Intent类型,且type=intent_llm,则给他添加附加模型 if ("Intent".equals(modelTypes[i])) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java index 7a826a336..023510cd1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/OTAController.java @@ -51,13 +51,12 @@ public class OTAController { if (StringUtils.isBlank(clientId)) { clientId = deviceId; } - String macAddress = deviceReportReqDTO.getMacAddress(); - boolean macAddressValid = isMacAddressValid(macAddress); + boolean macAddressValid = isMacAddressValid(deviceId); // 设备Id和Mac地址应是一致的, 并且必须需要application字段 - if (!deviceId.equals(macAddress) || !macAddressValid || deviceReportReqDTO.getApplication() == null) { - return createResponse(DeviceReportRespDTO.createError("Invalid OTA request")); + if (!macAddressValid) { + return createResponse(DeviceReportRespDTO.createError("Invalid device ID")); } - return createResponse(deviceService.checkDeviceActive(macAddress, clientId, deviceReportReqDTO)); + return createResponse(deviceService.checkDeviceActive(deviceId, clientId, deviceReportReqDTO)); } @Operation(summary = "设备快速检查激活状态") @@ -78,10 +77,6 @@ public class OTAController { @GetMapping @Hidden public ResponseEntity getOTA() { - String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false); - if(StringUtils.isBlank(mqttUdpConfig)) { - return ResponseEntity.ok("OTA接口不正常,缺少websocket地址,请登录智控台,在参数管理找到【server.mqtt_udp】配置"); - } String wsUrl = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true); if (StringUtils.isBlank(wsUrl) || wsUrl.equals("null")) { return ResponseEntity.ok("OTA接口不正常,缺少websocket地址,请登录智控台,在参数管理找到【server.websocket】配置"); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java index 5c53b7880..f938001e0 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java @@ -22,9 +22,6 @@ public class DeviceReportRespDTO { @Schema(description = "WebSocket配置") private Websocket websocket; - - @Schema(description = "MQTT Gateway配置") - private MQTT mqtt; @Getter @Setter @@ -73,21 +70,4 @@ public class DeviceReportRespDTO { @Schema(description = "WebSocket服务器地址") private String url; } - - @Getter - @Setter - public static class MQTT { - @Schema(description = "MQTT 配置网址") - private String endpoint; - @Schema(description = "MQTT 客户端唯一标识符") - private String client_id; - @Schema(description = "MQTT 认证用户名") - private String username; - @Schema(description = "MQTT 认证密码") - private String password; - @Schema(description = "ESP32 发布消息的主题") - private String publish_topic; - @Schema(description = "ESP32 订阅的主题") - private String subscribe_topic; - } } 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 9b0e4a703..3cff111db 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 @@ -175,24 +175,6 @@ public class DeviceServiceImpl extends BaseServiceImpl } response.setWebsocket(websocket); - - // 添加MQTT UDP配置 - // 从系统参数获取WebSocket URL,如果未配置不使用默认值 - String mqttUdpConfig = sysParamsService.getValue(Constant.SERVER_MQTT_GATEWAY, false); - if(!StringUtils.isBlank(mqttUdpConfig)) { - DeviceReportRespDTO.MQTT mqtt= new DeviceReportRespDTO.MQTT(); - mqtt.setEndpoint(mqttUdpConfig); - mqtt.setClient_id(clientId); - String userNameString = deviceById.getId().replace(":", "_"); - mqtt.setUsername(userNameString); - mqtt.setPassword(deviceById.getBoard()); - String topicString = deviceById.getBoard() + '/' + deviceById.getAgentId(); - mqtt.setPublish_topic(topicString); - String subscribeString = "devices/p2p/"+userNameString; - mqtt.setSubscribe_topic(subscribeString); - response.setMqtt(mqtt); - } - if (deviceById != null) { // 如果设备存在,则异步更新上次连接时间和版本信息 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java index 5e22265f0..ed9e8c7fa 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/OtaServiceImpl.java @@ -66,7 +66,7 @@ public class OtaServiceImpl extends BaseServiceImpl implement // 同类固件只保留最新的一条 List otaList = baseDao.selectList(queryWrapper); if (otaList != null && otaList.size() > 0) { - OtaEntity otaBefore = otaList.get(0); + OtaEntity otaBefore = otaList.getFirst(); entity.setId(otaBefore.getId()); baseDao.updateById(entity); return true; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java index 8baff29d6..32a5c0cc6 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java @@ -21,11 +21,7 @@ import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.Result; import xiaozhi.modules.agent.service.AgentTemplateService; import xiaozhi.modules.config.service.ConfigService; -import xiaozhi.modules.model.dto.ModelBasicInfoDTO; -import xiaozhi.modules.model.dto.ModelConfigBodyDTO; -import xiaozhi.modules.model.dto.ModelConfigDTO; -import xiaozhi.modules.model.dto.ModelProviderDTO; -import xiaozhi.modules.model.dto.VoiceDTO; +import xiaozhi.modules.model.dto.*; import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; import xiaozhi.modules.model.service.ModelProviderService; @@ -52,6 +48,14 @@ public class ModelController { return new Result>().ok(modelList); } + @GetMapping("/llm/names") + @Operation(summary = "获取LLM模型信息") + @RequiresPermissions("sys:role:normal") + public Result> getLlmModelCodeList(@RequestParam(required = false) String modelName) { + List llmModelCodeList = modelConfigService.getLlmModelCodeList(modelName); + return new Result>().ok(llmModelCodeList); + } + @GetMapping("/{modelType}/provideTypes") @Operation(summary = "获取模型供应器列表") @RequiresPermissions("sys:role:superAdmin") diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/LlmModelBasicInfoDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/LlmModelBasicInfoDTO.java new file mode 100644 index 000000000..3995ceb83 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/LlmModelBasicInfoDTO.java @@ -0,0 +1,13 @@ +package xiaozhi.modules.model.dto; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * LLM的模型的基础展示数据 + */ +@EqualsAndHashCode(callSuper = true) +@Data +public class LlmModelBasicInfoDTO extends ModelBasicInfoDTO{ + private String type; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java b/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java index 9d15ac6df..634101e33 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/service/ModelConfigService.java @@ -4,6 +4,7 @@ import java.util.List; import xiaozhi.common.page.PageData; import xiaozhi.common.service.BaseService; +import xiaozhi.modules.model.dto.LlmModelBasicInfoDTO; import xiaozhi.modules.model.dto.ModelBasicInfoDTO; import xiaozhi.modules.model.dto.ModelConfigBodyDTO; import xiaozhi.modules.model.dto.ModelConfigDTO; @@ -13,6 +14,8 @@ public interface ModelConfigService extends BaseService { List getModelCodeList(String modelType, String modelName); + List getLlmModelCodeList(String modelName); + PageData getPageList(String modelType, String modelName, String page, String limit); ModelConfigDTO add(String modelType, String provideCode, ModelConfigBodyDTO modelConfigBodyDTO); 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 1f006d935..c156b408b 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 @@ -8,6 +8,7 @@ import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; @@ -23,6 +24,7 @@ import xiaozhi.common.utils.ConvertUtils; import xiaozhi.modules.agent.dao.AgentDao; import xiaozhi.modules.agent.entity.AgentEntity; import xiaozhi.modules.model.dao.ModelConfigDao; +import xiaozhi.modules.model.dto.LlmModelBasicInfoDTO; import xiaozhi.modules.model.dto.ModelBasicInfoDTO; import xiaozhi.modules.model.dto.ModelConfigBodyDTO; import xiaozhi.modules.model.dto.ModelConfigDTO; @@ -52,6 +54,25 @@ public class ModelConfigServiceImpl extends BaseServiceImpl getLlmModelCodeList(String modelName) { + List entities = modelConfigDao.selectList( + new QueryWrapper() + .eq("model_type", "llm") + .eq("is_enabled", 1) + .like(StringUtils.isNotBlank(modelName), "model_name", "%" + modelName + "%") + .select("id", "model_name", "config_json")); + // 处理获取到的内容 + return entities.stream().map(item -> { + LlmModelBasicInfoDTO dto = new LlmModelBasicInfoDTO(); + dto.setId(item.getId()); + dto.setModelName(item.getModelName()); + String type = item.getConfigJson().get("type").toString(); + dto.setType(type); + return dto; + }).toList(); + } + @Override public PageData getPageList(String modelType, String modelName, String page, String limit) { Map params = new HashMap(); @@ -94,6 +115,21 @@ public class ModelConfigServiceImpl extends BaseServiceImpl() + .eq(ModelConfigEntity::getId, llm)); + String selectModelType = (modelConfigEntity == null || modelConfigEntity.getModelType() == null) ? null + : modelConfigEntity.getModelType().toUpperCase(); + if (modelConfigEntity == null || !"LLM".equals(selectModelType)) { + throw new RenException("设置的LLM不存在"); + } + String type = modelConfigEntity.getConfigJson().get("type").toString(); + // 如果查询大语言模型是openai或者ollama,意图识别选参数都可以 + if (!"openai".equals(type) && !"ollama".equals(type)) { + throw new RenException("设置的LLM不是openai和ollama"); + } + } // 再更新供应器提供的模型 ModelConfigEntity modelConfigEntity = ConvertUtils.sourceToTarget(modelConfigBodyDTO, ModelConfigEntity.class); @@ -137,6 +173,8 @@ public class ModelConfigServiceImpl extends BaseServiceImpl(); @@ -212,13 +215,14 @@ public class SysParamsController { if (!url.toLowerCase().contains("key")) { throw new RenException("不是正确的MCP地址"); } + try { // 发送GET请求 ResponseEntity response = restTemplate.getForEntity(url, String.class); if (response.getStatusCode() != HttpStatus.OK) { throw new RenException("MCP接口访问失败,状态码:" + response.getStatusCode()); } - // 检查响应内容是否包含OTA相关信息 + // 检查响应内容是否包含mcp相关信息 String body = response.getBody(); if (body == null || !body.contains("success")) { throw new RenException("MCP接口返回内容格式不正确,可能不是一个真实的MCP接口"); @@ -227,4 +231,37 @@ public class SysParamsController { throw new RenException("MCP接口验证失败:" + e.getMessage()); } } + // 验证声纹接口地址是否正常 + private void validateVoicePrint(String paramCode, String url) { + if (!paramCode.equals(Constant.SERVER_VOICE_PRINT)) { + return; + } + if (StringUtils.isBlank(url) || url.equals("null")) { + throw new RenException("声纹接口地址不能为空"); + } + if (url.contains("localhost") || url.contains("127.0.0.1")) { + throw new RenException("声纹接口地址不能使用localhost或127.0.0.1"); + } + if (!url.toLowerCase().contains("key")) { + throw new RenException("不是正确的声纹接口地址"); + } + // 验证URL格式 + if (!url.toLowerCase().startsWith("http")) { + throw new RenException("声纹接口地址必须以http或https开头"); + } + try { + // 发送GET请求 + ResponseEntity response = restTemplate.getForEntity(url, String.class); + if (response.getStatusCode() != HttpStatus.OK) { + throw new RenException("声纹接口访问失败,状态码:" + response.getStatusCode()); + } + // 检查响应内容 + String body = response.getBody(); + if (body == null || !body.contains("healthy")) { + throw new RenException("声纹接口返回内容格式不正确,可能不是一个真实的MCP接口"); + } + } catch (Exception e) { + throw new RenException("声纹接口验证失败:" + e.getMessage()); + } + } } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java index 282b452e1..9f35836fd 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java @@ -56,7 +56,7 @@ public class SysUserServiceImpl extends BaseServiceImpl List listenerCustomWithoutClose( + BlockingQueue queue, + Predicate predicate) + throws InterruptedException, TimeoutException, ExecutionException { + List collected = new ArrayList<>(); + long deadline = System.currentTimeMillis() + maxSessionDurationUnit.toMillis(maxSessionDuration); + + while (true) { + if (errorFuture.isDone()) { + errorFuture.get(); + } + + long remaining = deadline - System.currentTimeMillis(); + if (remaining <= 0) { + throw new TimeoutException("等待批量消息超时"); + } + + T msg = queue.poll(remaining, TimeUnit.MILLISECONDS); + if (msg == null) { + throw new TimeoutException("等待批量消息超时"); + } + + collected.add(msg); + if (predicate.test(msg)) { + break; + } + } + // 不调用 close(),保持连接开放 + return collected; + } + /** * 同步接收多条消息,直到 predicate 为 true 或超时抛异常; * @@ -147,6 +182,17 @@ public class WebSocketClientManager implements Closeable { return listenerCustom(textMessageQueue, predicate); } + /** + * 同步接收多条消息,直到 predicate 为 true 或超时抛异常; + * 不自动关闭连接,适用于需要在同一连接上发送多个消息的场景 + * + * @return 返回监听期间的所有消息列表 + */ + public List listenerWithoutClose(Predicate predicate) + throws InterruptedException, TimeoutException, ExecutionException { + return listenerCustomWithoutClose(textMessageQueue, predicate); + } + public List listenerBinary(Predicate predicate) throws InterruptedException, TimeoutException, ExecutionException { return listenerCustom(binaryMessageQueue, predicate); @@ -266,10 +312,11 @@ public class WebSocketClientManager implements Closeable { if (stopWatch.isRunning()) { stopWatch.stop(); } - log.info("ws连接关闭, 目标URI: {}, 关闭时间: {}, 连接总时长: {}s", + log.info("ws连接关闭, 目标URI: {}, 关闭时间: {}, 连接总时长: {}s,断开原因:{}", targetUri, DateUtils.getDateTimeNow(DateUtils.DATE_TIME_MILLIS_PATTERN), - DateUtils.millsToSecond(stopWatch.getTotalTimeMillis())); + DateUtils.millsToSecond(stopWatch.getTotalTimeMillis()),status); } + } public static class Builder { @@ -279,6 +326,7 @@ public class WebSocketClientManager implements Closeable { private long maxSessionDuration = 5; // 最大连线时间,默认5秒 private TimeUnit maxSessionDurationUnit = TimeUnit.SECONDS; // 最大连线时间单位 private int queueCapacity = 100; // 消息队列容量 + private int bufferSize = 8 * 1024; //默认 8kb private WebSocketHttpHeaders headers; // 请求头 /** @@ -310,6 +358,10 @@ public class WebSocketClientManager implements Closeable { this.queueCapacity = c; return this; } + public Builder bufferSize(int c) { + this.bufferSize = c; + return this; + } public WebSocketClientManager build() throws InterruptedException, ExecutionException, TimeoutException, IOException { diff --git a/main/manager-api/src/main/resources/application-dev.yml b/main/manager-api/src/main/resources/application-dev.yml index b6d0ca422..f67ca542d 100644 --- a/main/manager-api/src/main/resources/application-dev.yml +++ b/main/manager-api/src/main/resources/application-dev.yml @@ -11,10 +11,18 @@ spring: datasource: druid: #MySQL + # driver-class-name: com.mysql.cj.jdbc.Driver + # # Railway MySQL Configuration - Updated for Railway database + # url: jdbc:mysql://yamanote.proxy.rlwy.net:16958/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true + # username: root + # password: cTefiuLmZSMqGpcQImUmBIsUBhNyUvrK driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://turntable.proxy.rlwy.net:38288/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true + # Railway MySQL Configuration - Updated for Railway database + url: jdbc:mysql://nozomi.proxy.rlwy.net:25037/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true username: root - password: nrTgFMCdwgjqZFFRXDhDZbCapfPNBxZK + password: OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm + + initial-size: 10 max-active: 100 min-idle: 10 @@ -38,6 +46,18 @@ spring: multi-statement-allow: true data: redis: - host: shortline.proxy.rlwy.net - port: 54353 - password: mClDIOpuKWkawXKBcfhWFDwHHnhuWegp + # Railway Redis Configuration + host: maglev.proxy.rlwy.net # Railway Redis服务器地址 + port: 16780 # Railway Redis服务器连接端口 + password: beVfOKcZjMUCBiZIQnvSMivhpSeijpKP # Railway Redis服务器连接密码 + username: default # Railway Redis用户名 + database: 0 # Redis数据库索引(默认为0) + timeout: 30000ms # 连接超时时间(毫秒)- 增加超时时间 + ssl: + enabled: false # 尝试禁用SSL,Railway可能不需要 + lettuce: + pool: + max-active: 8 # 连接池最大连接数(使用负值表示没有限制) + max-idle: 8 # 连接池中的最大空闲连接 + min-idle: 0 # 连接池中的最小空闲连接 + shutdown-timeout: 100ms # 客户端优雅关闭的等待时间 diff --git a/main/manager-api/src/main/resources/application-railway.yml b/main/manager-api/src/main/resources/application-railway.yml new file mode 100644 index 000000000..80142cdd6 --- /dev/null +++ b/main/manager-api/src/main/resources/application-railway.yml @@ -0,0 +1,61 @@ +knife4j: + production: false + enable: true + basic: + enable: false + username: renren + password: 2ZABCDEUgF + setting: + enableFooter: false + +spring: + datasource: + druid: + #Railway MySQL Configuration + driver-class-name: com.mysql.cj.jdbc.Driver + # Railway database connection + url: jdbc:mysql://nozomi.proxy.rlwy.net:25037/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true + username: root + password: OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm + initial-size: 10 + max-active: 100 + min-idle: 10 + max-wait: 6000 + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + time-between-eviction-runs-millis: 60000 + min-evictable-idle-time-millis: 300000 + test-while-idle: true + test-on-borrow: false + test-on-return: false + stat-view-servlet: + enabled: false + filter: + stat: + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: false + wall: + config: + multi-statement-allow: true + data: + redis: + # Railway Redis Configuration + host: maglev.proxy.rlwy.net + port: 16780 + password: beVfOKcZjMUCBiZIQnvSMivhpSeijpKP + username: default + database: 0 + timeout: 10000ms + lettuce: + pool: + max-active: 8 + max-idle: 8 + min-idle: 0 + shutdown-timeout: 100ms + +# Liquibase configuration for Railway +liquibase: + change-log: classpath:db/changelog/db.changelog-master.yaml + enabled: true + drop-first: false diff --git a/main/manager-api/src/main/resources/application.properties b/main/manager-api/src/main/resources/application.properties deleted file mode 100644 index b37876c14..000000000 --- a/main/manager-api/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -spring.datasource.url=jdbc:mysql://mysql.railway.internal:3306/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true -spring.datasource.username=root -spring.datasource.password=nrTgFMCdwgjqZFFRXDhDZbCapfPNBxZK \ No newline at end of file diff --git a/main/manager-api/src/main/resources/application.yml b/main/manager-api/src/main/resources/application.yml index 85fa21916..2e4fb4e27 100644 --- a/main/manager-api/src/main/resources/application.yml +++ b/main/manager-api/src/main/resources/application.yml @@ -15,7 +15,7 @@ server: spring: # 环境 dev|test|prod profiles: - active: dev + active: dev # Using dev profile with Railway database configuration messages: encoding: UTF-8 basename: i18n/messages @@ -26,14 +26,6 @@ spring: enabled: true main: allow-bean-definition-overriding: true - datasource: - url: jdbc:mysql://turntable.proxy.rlwy.net:38288/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true - username: root - password: nrTgFMCdwgjqZFFRXDhDZbCapfPNBxZK - redis: - host: shortline.proxy.rlwy.net - port: 54353 - password: mClDIOpuKWkawXKBcfhWFDwHHnhuWegp knife4j: enable: true diff --git a/main/manager-api/src/main/resources/db/changelog/202507031602.sql b/main/manager-api/src/main/resources/db/changelog/202507031602.sql new file mode 100644 index 000000000..92edf9b9c --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202507031602.sql @@ -0,0 +1,4 @@ +-- 添加声纹接口地址参数配置 +delete from `sys_params` where id = 114; +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) +VALUES (114, 'server.voice_print', 'null', 'string', 1, '声纹接口地址'); \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202507041018.sql b/main/manager-api/src/main/resources/db/changelog/202507041018.sql new file mode 100644 index 000000000..cffcfb169 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202507041018.sql @@ -0,0 +1,12 @@ +DROP TABLE IF EXISTS ai_agent_voice_print; +create table ai_agent_voice_print ( + id varchar(32) NOT NULL COMMENT '声纹ID', + agent_id varchar(32) NOT NULL COMMENT '关联的智能体ID', + source_name varchar(50) NOT NULL COMMENT '声纹来源的人的姓名', + introduce varchar(200) COMMENT '描述声纹来源的这个人', + create_date DATETIME COMMENT '创建时间', + creator bigint COMMENT '创建者', + update_date DATETIME COMMENT '修改时间', + updater bigint COMMENT '修改者', + PRIMARY KEY (id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='智能体声纹表' \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202507051233.sql b/main/manager-api/src/main/resources/db/changelog/202507051233.sql deleted file mode 100644 index a85688772..000000000 --- a/main/manager-api/src/main/resources/db/changelog/202507051233.sql +++ /dev/null @@ -1,5 +0,0 @@ -delete from `sys_params` where id = 108; -INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (108, 'server.mqtt_gateway', 'null', 'string', 1, 'mqtt gateway 配置'); - -delete from `sys_params` where id = 109; -INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (109, 'server.udp_gateway', 'null', 'string', 1, 'udp gateway 配置'); \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202507071130.sql b/main/manager-api/src/main/resources/db/changelog/202507071130.sql new file mode 100644 index 000000000..c3730ef73 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202507071130.sql @@ -0,0 +1,26 @@ +-- 添加阿里云流式ASR供应器 +delete from `ai_model_provider` where id = 'SYSTEM_ASR_AliyunStreamASR'; +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES +('SYSTEM_ASR_AliyunStreamASR', 'ASR', 'aliyun_stream', '阿里云语音识别(流式)', '[{"key":"appkey","label":"应用AppKey","type":"string"},{"key":"token","label":"临时Token","type":"string"},{"key":"access_key_id","label":"AccessKey ID","type":"string"},{"key":"access_key_secret","label":"AccessKey Secret","type":"string"},{"key":"host","label":"服务地址","type":"string"},{"key":"max_sentence_silence","label":"断句检测时间","type":"number"},{"key":"output_dir","label":"输出目录","type":"string"}]', 6, 1, NOW(), 1, NOW()); + +-- 添加阿里云流式ASR模型配置 +delete from `ai_model_config` where id = 'ASR_AliyunStreamASR'; +INSERT INTO `ai_model_config` VALUES ('ASR_AliyunStreamASR', 'ASR', 'AliyunStreamASR', '阿里云语音识别(流式)', 0, 1, '{\"type\": \"aliyun_stream\", \"appkey\": \"\", \"token\": \"\", \"access_key_id\": \"\", \"access_key_secret\": \"\", \"host\": \"nls-gateway-cn-shanghai.aliyuncs.com\", \"max_sentence_silence\": 800, \"output_dir\": \"tmp/\"}', NULL, NULL, 8, NULL, NULL, NULL, NULL); + +-- 更新阿里云流式ASR配置说明 +UPDATE `ai_model_config` SET +`doc_link` = 'https://nls-portal.console.aliyun.com/', +`remark` = '阿里云流式ASR配置说明: +1. 阿里云ASR和阿里云(流式)ASR的区别是:阿里云ASR是一次性识别,阿里云(流式)ASR是实时流式识别 +2. 流式ASR具有更低的延迟和更好的实时性,适合语音交互场景 +3. 需要在阿里云智能语音交互控制台创建应用并获取认证信息 +4. 支持中文实时语音识别,支持标点符号预测和逆文本规范化 +5. 需要网络连接,输出文件保存在tmp/目录 +申请步骤: +1. 访问 https://nls-portal.console.aliyun.com/ 开通智能语音交互服务 +2. 访问 https://nls-portal.console.aliyun.com/applist 创建项目并获取appkey +3. 访问 https://nls-portal.console.aliyun.com/overview 获取临时token(或配置access_key_id和access_key_secret自动获取) +4. 如需动态token管理,建议配置access_key_id和access_key_secret +5. max_sentence_silence参数控制断句检测时间(毫秒),默认800ms +如需了解更多参数配置,请参考:https://help.aliyun.com/zh/isi/developer-reference/real-time-speech-recognition +' WHERE `id` = 'ASR_AliyunStreamASR'; diff --git a/main/manager-api/src/main/resources/db/changelog/202507071530.sql b/main/manager-api/src/main/resources/db/changelog/202507071530.sql new file mode 100644 index 000000000..f1cf7a9b2 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202507071530.sql @@ -0,0 +1,56 @@ +-- 添加阿里云流式TTS供应器 +delete from `ai_model_provider` where id = 'SYSTEM_TTS_AliyunStreamTTS'; +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES +('SYSTEM_TTS_AliyunStreamTTS', 'TTS', 'aliyun_stream', '阿里云语音合成(流式)', '[{"key":"appkey","label":"应用AppKey","type":"string"},{"key":"token","label":"临时Token","type":"string"},{"key":"access_key_id","label":"AccessKey ID","type":"string"},{"key":"access_key_secret","label":"AccessKey Secret","type":"string"},{"key":"host","label":"服务地址","type":"string"},{"key":"voice","label":"默认音色","type":"string"},{"key":"format","label":"音频格式","type":"string"},{"key":"sample_rate","label":"采样率","type":"number"},{"key":"volume","label":"音量","type":"number"},{"key":"speech_rate","label":"语速","type":"number"},{"key":"pitch_rate","label":"音调","type":"number"},{"key":"output_dir","label":"输出目录","type":"string"}]', 15, 1, NOW(), 1, NOW()); + +-- 添加阿里云流式TTS模型配置 +delete from `ai_model_config` where id = 'TTS_AliyunStreamTTS'; +INSERT INTO `ai_model_config` VALUES ('TTS_AliyunStreamTTS', 'TTS', 'AliyunStreamTTS', '阿里云语音合成(流式)', 0, 1, '{\"type\": \"aliyun_stream\", \"appkey\": \"\", \"token\": \"\", \"access_key_id\": \"\", \"access_key_secret\": \"\", \"host\": \"nls-gateway-cn-beijing.aliyuncs.com\", \"voice\": \"longxiaochun\", \"format\": \"pcm\", \"sample_rate\": 16000, \"volume\": 50, \"speech_rate\": 0, \"pitch_rate\": 0, \"output_dir\": \"tmp/\"}', NULL, NULL, 18, NULL, NULL, NULL, NULL); + +-- 更新阿里云流式TTS配置说明 +UPDATE `ai_model_config` SET +`doc_link` = 'https://nls-portal.console.aliyun.com/', +`remark` = '阿里云流式TTS配置说明: +1. 阿里云TTS和阿里云(流式)TTS的区别是:阿里云TTS是一次性合成,阿里云(流式)TTS是实时流式合成 +2. 流式TTS具有更低的延迟和更好的实时性,适合语音交互场景 +3. 需要在阿里云智能语音交互控制台创建应用并获取认证信息 +4. 支持CosyVoice大模型音色,音质更加自然 +5. 支持实时调节音量、语速、音调等参数 +申请步骤: +1. 访问 https://nls-portal.console.aliyun.com/ 开通智能语音交互服务 +2. 访问 https://nls-portal.console.aliyun.com/applist 创建项目并获取appkey +3. 访问 https://nls-portal.console.aliyun.com/overview 获取临时token(或配置access_key_id和access_key_secret自动获取) +4. 如需动态token管理,建议配置access_key_id和access_key_secret +5. 可选择北京、上海等不同地域的服务器以优化延迟 +6. voice参数支持CosyVoice大模型音色,如longxiaochun、longyueyue等 +如需了解更多参数配置,请参考:https://help.aliyun.com/zh/isi/developer-reference/real-time-speech-synthesis +' WHERE `id` = 'TTS_AliyunStreamTTS'; + +-- 添加阿里云流式TTS音色 +delete from `ai_tts_voice` where tts_model_id = 'TTS_AliyunStreamTTS'; +-- 温柔女声系列 +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0001', 'TTS_AliyunStreamTTS', '龙小淳-温柔姐姐', 'longxiaochun', '中文及中英文混合', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0002', 'TTS_AliyunStreamTTS', '龙小夏-温柔女声', 'longxiaoxia', '中文及中英文混合', NULL, NULL, NULL, NULL, 2, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0003', 'TTS_AliyunStreamTTS', '龙玫-温柔女声', 'longmei', '中文及中英文混合', NULL, NULL, NULL, NULL, 3, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0004', 'TTS_AliyunStreamTTS', '龙瑰-温柔女声', 'longgui', '中文及中英文混合', NULL, NULL, NULL, NULL, 4, NULL, NULL, NULL, NULL); +-- 御姐女声系列 +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0005', 'TTS_AliyunStreamTTS', '龙玉-御姐女声', 'longyu', '中文及中英文混合', NULL, NULL, NULL, NULL, 5, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0006', 'TTS_AliyunStreamTTS', '龙娇-御姐女声', 'longjiao', '中文及中英文混合', NULL, NULL, NULL, NULL, 6, NULL, NULL, NULL, NULL); +-- 男声系列 +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0007', 'TTS_AliyunStreamTTS', '龙臣-译制片男声', 'longchen', '中文及中英文混合', NULL, NULL, NULL, NULL, 7, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0008', 'TTS_AliyunStreamTTS', '龙修-青年男声', 'longxiu', '中文及中英文混合', NULL, NULL, NULL, NULL, 8, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0009', 'TTS_AliyunStreamTTS', '龙橙-阳光男声', 'longcheng', '中文及中英文混合', NULL, NULL, NULL, NULL, 9, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0010', 'TTS_AliyunStreamTTS', '龙哲-成熟男声', 'longzhe', '中文及中英文混合', NULL, NULL, NULL, NULL, 10, NULL, NULL, NULL, NULL); +-- 专业播报系列 +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0011', 'TTS_AliyunStreamTTS', 'Bella2.0-新闻女声', 'loongbella', '中文及中英文混合', NULL, NULL, NULL, NULL, 11, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0012', 'TTS_AliyunStreamTTS', 'Stella2.0-飒爽女声', 'loongstella', '中文及中英文混合', NULL, NULL, NULL, NULL, 12, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0013', 'TTS_AliyunStreamTTS', '龙书-新闻男声', 'longshu', '中文及中英文混合', NULL, NULL, NULL, NULL, 13, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0014', 'TTS_AliyunStreamTTS', '龙婧-严肃女声', 'longjing', '中文及中英文混合', NULL, NULL, NULL, NULL, 14, NULL, NULL, NULL, NULL); +-- 特色音色系列 +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0015', 'TTS_AliyunStreamTTS', '龙奇-活泼童声', 'longqi', '中文及中英文混合', NULL, NULL, NULL, NULL, 15, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0016', 'TTS_AliyunStreamTTS', '龙华-活泼女童', 'longhua', '中文及中英文混合', NULL, NULL, NULL, NULL, 16, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0017', 'TTS_AliyunStreamTTS', '龙无-无厘头男声', 'longwu', '中文及中英文混合', NULL, NULL, NULL, NULL, 17, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0018', 'TTS_AliyunStreamTTS', '龙大锤-幽默男声', 'longdachui', '中文及中英文混合', NULL, NULL, NULL, NULL, 18, NULL, NULL, NULL, NULL); +-- 粤语系列 +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0019', 'TTS_AliyunStreamTTS', '龙嘉怡-粤语女声', 'longjiayi', '粤语及粤英混合', NULL, NULL, NULL, NULL, 19, NULL, NULL, NULL, NULL); +INSERT INTO `ai_tts_voice` VALUES ('TTS_AliyunStreamTTS_0020', 'TTS_AliyunStreamTTS', '龙桃-粤语女声', 'longtao', '粤语及粤英混合', NULL, NULL, NULL, NULL, 20, NULL, NULL, NULL, NULL); diff --git a/main/manager-api/src/main/resources/db/changelog/202507081646.sql b/main/manager-api/src/main/resources/db/changelog/202507081646.sql new file mode 100644 index 000000000..6631ae18b --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202507081646.sql @@ -0,0 +1,3 @@ +-- 智能体声纹添加新字段 +ALTER TABLE ai_agent_voice_print + ADD COLUMN audio_id VARCHAR(32) NOT NULL COMMENT '音频ID'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202507101203.sql b/main/manager-api/src/main/resources/db/changelog/202507101203.sql new file mode 100644 index 000000000..66896ef8c --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202507101203.sql @@ -0,0 +1,38 @@ +-- OpenAI ASR模型供应器 +delete from `ai_model_provider` where id = 'SYSTEM_ASR_OpenaiASR'; +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES +('SYSTEM_ASR_OpenaiASR', 'ASR', 'openai', 'OpenAI语音识别', '[{"key": "base_url", "type": "string", "label": "基础URL"}, {"key": "model_name", "type": "string", "label": "模型名称"}, {"key": "api_key", "type": "string", "label": "API密钥"}, {"key": "output_dir", "type": "string", "label": "输出目录"}]', 9, 1, NOW(), 1, NOW()); + + +-- OpenAI ASR模型配置 +delete from `ai_model_config` where id = 'ASR_OpenaiASR'; +INSERT INTO `ai_model_config` VALUES ('ASR_OpenaiASR', 'ASR', 'OpenaiASR', 'OpenAI语音识别', 0, 1, '{\"type\": \"openai\", \"api_key\": \"\", \"base_url\": \"https://api.openai.com/v1/audio/transcriptions\", \"model_name\": \"gpt-4o-mini-transcribe\", \"output_dir\": \"tmp/\"}', NULL, NULL, 9, NULL, NULL, NULL, NULL); + +-- groq ASR模型配置 +delete from `ai_model_config` where id = 'ASR_GroqASR'; +INSERT INTO `ai_model_config` VALUES ('ASR_GroqASR', 'ASR', 'GroqASR', 'Groq语音识别', 0, 1, '{\"type\": \"openai\", \"api_key\": \"\", \"base_url\": \"https://api.groq.com/openai/v1/audio/transcriptions\", \"model_name\": \"whisper-large-v3-turbo\", \"output_dir\": \"tmp/\"}', NULL, NULL, 10, NULL, NULL, NULL, NULL); + + +-- 更新OpenAI ASR配置说明 +UPDATE `ai_model_config` SET +`doc_link` = 'https://platform.openai.com/docs/api-reference/audio/createTranscription', +`remark` = 'OpenAI ASR配置说明: +1. 需要在OpenAI开放平台创建组织并获取api_key +2. 支持中、英、日、韩等多种语音识别,具体参考文档https://platform.openai.com/docs/guides/speech-to-text +3. 需要网络连接 +4. 输出文件保存在tmp/目录 +申请步骤: +**OpenAi ASR申请步骤:** +1.登录OpenAI Platform。https://auth.openai.com/log-in +2.创建api-key https://platform.openai.com/settings/organization/api-keys +3.模型可以选择gpt-4o-transcribe或GPT-4o mini Transcribe +' WHERE `id` = 'ASR_OpenaiASR'; + +-- 更新Groq ASR配置说明 +UPDATE `ai_model_config` SET +`doc_link` = 'https://console.groq.com/docs/speech-to-text', +`remark` = 'Groq ASR配置说明: +1.登录groq Console。https://console.groq.com/home +2.创建api-key https://console.groq.com/keys +3.模型可以选择whisper-large-v3-turbo或whisper-large-v3(distil-whisper-large-v3-en仅支持英语转录) +' WHERE `id` = 'ASR_GroqASR'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202508081701.sql b/main/manager-api/src/main/resources/db/changelog/202508081701.sql new file mode 100644 index 000000000..4f427514c --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202508081701.sql @@ -0,0 +1,32 @@ +-- 添加Index-TTS-vLLM流式TTS供应器 +delete from `ai_model_provider` where id = 'SYSTEM_TTS_IndexStreamTTS'; +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES +('SYSTEM_TTS_IndexStreamTTS', 'TTS', 'index_stream', 'Index-TTS-vLLM流式语音合成', '[{"key":"api_url","label":"API服务地址","type":"string"},{"key":"voice","label":"默认音色","type":"string"},{"key":"audio_format","label":"音频格式","type":"string"},{"key":"output_dir","label":"输出目录","type":"string"}]', 16, 1, NOW(), 1, NOW()); + +-- 添加Index-TTS-vLLM流式TTS模型配置 +delete from `ai_model_config` where id = 'TTS_IndexStreamTTS'; +INSERT INTO `ai_model_config` VALUES ('TTS_IndexStreamTTS', 'TTS', 'IndexStreamTTS', 'Index-TTS-vLLM流式语音合成', 0, 1, '{\"type\": \"index_stream\", \"api_url\": \"http://127.0.0.1:11996/tts\", \"voice\": \"jay_klee\", \"audio_format\": \"pcm\", \"output_dir\": \"tmp/\"}', NULL, NULL, 19, NULL, NULL, NULL, NULL); + +-- 更新Index-TTS-vLLM流式TTS配置说明 +UPDATE `ai_model_config` SET +`doc_link` = 'https://github.com/Ksuriuri/index-tts-vllm', +`remark` = 'Index-TTS-vLLM流式TTS配置说明: +1. Index-TTS-vLLM是基于Index-TTS项目的vLLM推理服务,提供流式语音合成功能 +2. 支持多种音色,音质自然,适合各种语音交互场景 +3. 需要先部署Index-TTS-vLLM服务,然后配置API地址 +4. 支持实时流式合成,具有较低的延迟 +5. 支持自定义音色,可在项目assets文件夹下注册新音色 +部署步骤: +1. 克隆项目:git clone https://github.com/Ksuriuri/index-tts-vllm.git +2. 安装依赖:pip install -r requirements.txt +3. 启动服务:python app.py +4. 服务默认运行在 http://127.0.0.1:11996 +5. 如需其他音色,可到项目assets文件夹下注册 +6. 支持多种音频格式:pcm、wav、mp3等 +如需了解更多配置,请参考:https://github.com/Ksuriuri/index-tts-vllm/blob/master/README.md +' WHERE `id` = 'TTS_IndexStreamTTS'; + +-- 添加Index-TTS-vLLM流式TTS音色 +delete from `ai_tts_voice` where tts_model_id = 'TTS_IndexStreamTTS'; +-- 默认音色 +INSERT INTO `ai_tts_voice` VALUES ('TTS_IndexStreamTTS_0001', 'TTS_IndexStreamTTS', 'Jay Klee', 'jay_klee', '中文及中英文混合', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL); diff --git a/main/manager-api/src/main/resources/db/changelog/202508111734.sql b/main/manager-api/src/main/resources/db/changelog/202508111734.sql new file mode 100644 index 000000000..fb3162b10 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202508111734.sql @@ -0,0 +1,16 @@ +-- 更新HuoshanDoubleStreamTTS供应器增加语速,音调等配置 +UPDATE `ai_model_provider` +SET fields = '[{"key": "ws_url", "type": "string", "label": "WebSocket地址"}, {"key": "appid", "type": "string", "label": "应用ID"}, {"key": "access_token", "type": "string", "label": "访问令牌"}, {"key": "resource_id", "type": "string", "label": "资源ID"}, {"key": "speaker", "type": "string", "label": "默认音色"}, {"key": "speech_rate", "type": "number", "label": "语速(-50~100)"}, {"key": "loudness_rate", "type": "number", "label": "音量(-50~100)"}, {"key": "pitch", "type": "number", "label": "音高(-12~12)"}]' +WHERE id = 'SYSTEM_TTS_HSDSTTS'; + +UPDATE `ai_model_config` SET +`doc_link` = 'https://console.volcengine.com/speech/service/10007', +`remark` = '火山引擎语音合成服务配置说明: +1. 访问 https://www.volcengine.com/ 注册并开通火山引擎账号 +2. 访问 https://console.volcengine.com/speech/service/10007 开通语音合成大模型,购买音色 +3. 在页面底部获取appid和access_token +5. 资源ID固定为:volc.service_type.10029(大模型语音合成及混音) +6. 语速:-50~100,可不填,正常默认值0,可填-50~100 +7. 音量:-50~100,可不填,正常默认值0,可填-50~100 +8. 音高:-12~12,可不填,正常默认值0,可填-12~12 +9. 填入配置文件中' WHERE `id` = 'TTS_HuoshanDoubleStreamTTS'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202508131557.sql b/main/manager-api/src/main/resources/db/changelog/202508131557.sql new file mode 100644 index 000000000..decfd0db5 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202508131557.sql @@ -0,0 +1,26 @@ +-- 添加 paddle_speech 流式 TTS 供应器 +DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_TTS_PaddleSpeechTTS'; +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) +VALUES ('SYSTEM_TTS_PaddleSpeechTTS', 'TTS', 'paddle_speech', 'PaddleSpeechTTS', +'[{"key":"protocol","label":"协议类型","type":"string","options":["websocket","http"]},{"key":"url","label":"服务地址","type":"string"},{"key":"spk_id","label":"音色","type":"int"},{"key":"sample_rate","label":"采样率","type":"float"},{"key":"speed","label":"语速","type":"float"},{"key":"volume","label":"音量","type":"float"},{"key":"save_path","label":"保存路径","type":"string"}]', +17, 1, NOW(), 1, NOW()); + +-- 添加 paddle_speech 流式 TTS 模型配置 +DELETE FROM `ai_model_config` WHERE id = 'TTS_PaddleSpeechTTS'; +INSERT INTO `ai_model_config` VALUES ('TTS_PaddleSpeechTTS', 'TTS', 'PaddleSpeechTTS', 'PaddleSpeechTTS', 0, 1, +'{"type": "paddle_speech", "protocol": "websocket", "url": "ws://127.0.0.1:8092/paddlespeech/tts/streaming", "spk_id": "0", "sample_rate": 24000, "speed": 1.0, "volume": 1.0, "save_path": "./streaming_tts.wav"}', +NULL, NULL, 20, NULL, NULL, NULL, NULL); + +-- 更新 PaddleSpeechTTS 配置说明 +UPDATE `ai_model_config` SET +`doc_link` = 'https://github.com/PaddlePaddle/PaddleSpeech', +`remark` = 'PaddleSpeechTTS 配置说明: +1. PaddleSpeech 是百度飞桨开源的语音合成工具,支持本地离线部署和模型训练。paddlepaddle百度飞浆框架地址:https://www.paddlepaddle.org.cn/ +2. 支持 WebSocket 和 HTTP 协议,默认使用 WebSocket 进行流式传输(参考部署文档:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/paddlespeech-deploy.md)。 +3. 使用前要在本地部署 paddlespeech 服务,服务默认运行在 ws://127.0.0.1:8092/paddlespeech/tts/streaming +4. 支持自定义发音人、语速、音量和采样率。 +' WHERE `id` = 'TTS_PaddleSpeechTTS'; + +-- 删除旧音色并添加默认音色 +DELETE FROM `ai_tts_voice` WHERE tts_model_id = 'TTS_PaddleSpeechTTS'; +INSERT INTO `ai_tts_voice` VALUES ('TTS_PaddleSpeechTTS_0000', 'TTS_PaddleSpeechTTS', '默认', '0', '中文', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL); \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202508141200.sql b/main/manager-api/src/main/resources/db/changelog/202508141200.sql deleted file mode 100644 index 265d1343d..000000000 --- a/main/manager-api/src/main/resources/db/changelog/202508141200.sql +++ /dev/null @@ -1,7 +0,0 @@ --- Add diana voice for SiliconFlow CosyVoice TTS -INSERT INTO `ai_tts_voice` VALUES ('TTS_CosyVoiceSiliconflow0003', 'TTS_CosyVoiceSiliconflow', 'CosyVoice Diana', 'diana', '中文', NULL, NULL, 6, NULL, NULL, NULL, NULL); - --- Update default SiliconFlow configuration to use diana voice and correct API endpoint -UPDATE `ai_model_config` -SET config_json = '{"type": "siliconflow", "model": "FunAudioLLM/CosyVoice2-0.5B", "voice": "diana", "output_dir": "tmp/", "access_token": "", "response_format": "mp3", "speed": 1.0, "gain": 0}' -WHERE id = 'TTS_CosyVoiceSiliconflow'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/add_english_sherpa_models.sql b/main/manager-api/src/main/resources/db/changelog/add_english_sherpa_models.sql deleted file mode 100644 index 96e2b53b6..000000000 --- a/main/manager-api/src/main/resources/db/changelog/add_english_sherpa_models.sql +++ /dev/null @@ -1,19 +0,0 @@ --- Add English-only Sherpa-ONNX ASR model configurations --- Author: Assistant --- Date: 2025-08-15 - --- Add Whisper Tiny English model -INSERT INTO `ai_model_config` VALUES ('ASR_SherpaWhisperTinyEN', 'ASR', 'SherpaWhisperTinyEN', 'Sherpa Whisper Tiny English', 0, 1, '{\"type\": \"sherpa_onnx_local\", \"model_dir\": \"models/sherpa-onnx-whisper-tiny.en\", \"model_type\": \"whisper\", \"output_dir\": \"tmp/\"}', NULL, NULL, 10, NULL, NULL, NULL, NULL); - --- Add Whisper Base English model -INSERT INTO `ai_model_config` VALUES ('ASR_SherpaWhisperBaseEN', 'ASR', 'SherpaWhisperBaseEN', 'Sherpa Whisper Base English', 0, 1, '{\"type\": \"sherpa_onnx_local\", \"model_dir\": \"models/sherpa-onnx-whisper-base.en\", \"model_type\": \"whisper\", \"output_dir\": \"tmp/\"}', NULL, NULL, 11, NULL, NULL, NULL, NULL); - --- Add Whisper Small English model -INSERT INTO `ai_model_config` VALUES ('ASR_SherpaWhisperSmallEN', 'ASR', 'SherpaWhisperSmallEN', 'Sherpa Whisper Small English', 0, 1, '{\"type\": \"sherpa_onnx_local\", \"model_dir\": \"models/sherpa-onnx-whisper-small.en\", \"model_type\": \"whisper\", \"output_dir\": \"tmp/\"}', NULL, NULL, 12, NULL, NULL, NULL, NULL); - --- Add working English-only models -INSERT INTO `ai_model_config` VALUES ('ASR_SherpaZipformerEN', 'ASR', 'SherpaZipformerEN', 'Sherpa Zipformer English (Good Balance)', 0, 1, '{\"type\": \"sherpa_onnx_local\", \"model_dir\": \"models/sherpa-onnx-zipformer-en-2023-04-01\", \"model_type\": \"zipformer\", \"output_dir\": \"tmp/\"}', NULL, NULL, 13, NULL, NULL, NULL, NULL); - -INSERT INTO `ai_model_config` VALUES ('ASR_SherpaZipformerGigaspeechEN', 'ASR', 'SherpaZipformerGigaspeechEN', 'Sherpa Zipformer Gigaspeech English (Large Vocab)', 0, 1, '{\"type\": \"sherpa_onnx_local\", \"model_dir\": \"models/sherpa-onnx-zipformer-gigaspeech-2023-12-12\", \"model_type\": \"zipformer\", \"output_dir\": \"tmp/\"}', NULL, NULL, 14, NULL, NULL, NULL, NULL); - -INSERT INTO `ai_model_config` VALUES ('ASR_SherpaParaformerEN', 'ASR', 'SherpaParaformerEN', 'Sherpa Paraformer English (Alternative)', 0, 1, '{\"type\": \"sherpa_onnx_local\", \"model_dir\": \"models/sherpa-onnx-paraformer-en-2023-10-24\", \"model_type\": \"paraformer\", \"output_dir\": \"tmp/\"}', NULL, NULL, 15, NULL, NULL, NULL, NULL); \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index 8449d91f5..0e8d3dc35 100755 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -241,19 +241,65 @@ databaseChangeLog: encoding: utf8 path: classpath:db/changelog/202506261637.sql - changeSet: - - - id: 202507051233 - - author: marlonz + id: 202507101203 + author: luruxian changes: - sqlFile: encoding: utf8 - path: classpath:db/changelog/202507051233.sql + path: classpath:db/changelog/202507101203.sql - changeSet: - id: 202508141200 - author: kiro + id: 202507071130 + author: cgd + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202507071130.sql + - changeSet: + id: 202507071530 + author: cgd + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202507071530.sql + - changeSet: + id: 202507031602 + author: zjy changes: - sqlFile: encoding: utf8 - path: classpath:db/changelog/202508141200.sql + path: classpath:db/changelog/202507031602.sql + - changeSet: + id: 202507041018 + author: zjy + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202507041018.sql + - changeSet: + id: 202507081646 + author: zjy + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202507081646.sql + - changeSet: + id: 202508081701 + author: hrz + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202508081701.sql + - changeSet: + id: 202508111734 + author: RanChen + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202508111734.sql + - changeSet: + id: 202508131557 + author: RanChen + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202508131557.sql diff --git a/main/manager-api/src/main/resources/mapper/security/SysUserTokenDao.xml b/main/manager-api/src/main/resources/mapper/security/SysUserTokenDao.xml index 2aca0ab89..4f49414a0 100644 --- a/main/manager-api/src/main/resources/mapper/security/SysUserTokenDao.xml +++ b/main/manager-api/src/main/resources/mapper/security/SysUserTokenDao.xml @@ -4,11 +4,11 @@ diff --git a/main/manager-api/src/main/resources/mapper/sys/SysParamsDao.xml b/main/manager-api/src/main/resources/mapper/sys/SysParamsDao.xml index 3d19352ee..8faf43116 100644 --- a/main/manager-api/src/main/resources/mapper/sys/SysParamsDao.xml +++ b/main/manager-api/src/main/resources/mapper/sys/SysParamsDao.xml @@ -5,7 +5,7 @@ diff --git a/main/manager-mobile/.commitlintrc.cjs b/main/manager-mobile/.commitlintrc.cjs new file mode 100644 index 000000000..98ee7dfc2 --- /dev/null +++ b/main/manager-mobile/.commitlintrc.cjs @@ -0,0 +1,3 @@ +module.exports = { + extends: ['@commitlint/config-conventional'], +} diff --git a/main/manager-mobile/.editorconfig b/main/manager-mobile/.editorconfig new file mode 100644 index 000000000..7f0986477 --- /dev/null +++ b/main/manager-mobile/.editorconfig @@ -0,0 +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 # 始终在文件末尾插入一个新行 + +[*.md] # 表示仅 md 文件适用以下规则 +max_line_length = off # 关闭最大行长度限制 +trim_trailing_whitespace = false # 关闭末尾空格修剪 diff --git a/main/manager-mobile/.gitignore b/main/manager-mobile/.gitignore new file mode 100644 index 000000000..34ddbdf3d --- /dev/null +++ b/main/manager-mobile/.gitignore @@ -0,0 +1,44 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +.DS_Store +dist +*.local + +# Editor directories and files +.idea +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? +.hbuilderx + +.stylelintcache +.eslintcache + +docs/.vitepress/dist +docs/.vitepress/cache + +src/types + +# lock 文件还是不要了,我主要的版本写死就好了 +# pnpm-lock.yaml +# package-lock.json + +# TIPS:如果某些文件已经加入了版本管理,现在重新加入 .gitignore 是不生效的,需要执行下面的操作 +# `git rm -r --cached .` 然后提交 commit 即可。 + +# git rm -r --cached file1 file2 ## 针对某些文件 +# git rm -r --cached dir1 dir2 ## 针对某些文件夹 +# git rm -r --cached . ## 针对所有文件 + +# 更新 uni-app 官方版本 +# npx @dcloudio/uvm@latest diff --git a/main/manager-mobile/.npmrc b/main/manager-mobile/.npmrc new file mode 100644 index 000000000..10ecfe224 --- /dev/null +++ b/main/manager-mobile/.npmrc @@ -0,0 +1,8 @@ +# registry = https://registry.npmjs.org +registry = https://registry.npmmirror.com + +strict-peer-dependencies=false +auto-install-peers=true +shamefully-hoist=true +ignore-workspace-root-check=true +install-workspace-root=true diff --git a/main/manager-mobile/LICENSE b/main/manager-mobile/LICENSE new file mode 100644 index 000000000..8738d3b5d --- /dev/null +++ b/main/manager-mobile/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Junsen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/main/manager-mobile/README.md b/main/manager-mobile/README.md new file mode 100644 index 000000000..3a4f33a38 --- /dev/null +++ b/main/manager-mobile/README.md @@ -0,0 +1,170 @@ +## 智控台移动版(manager-mobile) +基于 uni-app v3 + Vue 3 + Vite 的跨端移动管理端,支持 App(Android & iOS)和微信小程序。 + +### 平台兼容性 + +| H5 | iOS | Android | 微信小程序 | +| -- | --- | ------- | ---------- | +| √ | √ | √ | √ | + +提示:不同 UI 组件在不同平台的适配度略有差异,请以对应组件库文档为准。 + +### 开发环境要求 +- Node >= 18 +- pnpm >= 7.30(建议使用项目中声明的 `pnpm@10.x`) +- 可选:HBuilderX(App 调试/打包)、微信开发者工具(微信小程序) + +### 快速开始 +1) 配置环境变量 + - 复制 `env/.env.example` 为 `env/.env.development` + - 根据实际情况修改配置项(特别是 `VITE_SERVER_BASEURL`、`VITE_UNI_APPID`、`VITE_WX_APPID`) + +2) 安装依赖 + +```bash +pnpm i +``` + +3) 本地开发(热更新) +- h5: `pnpm dev:h5`,然后观察启动日志显示的ip端口号 +- 微信小程序:`pnpm dev:mp` 或 `pnpm dev:mp-weixin`,然后用微信开发者工具导入 `dist/dev/mp-weixin` +- App:用 HBuilderX 导入 `manager-mobile`,然后参考下面的教程就能运行了 + +### 环境变量与配置 +项目使用自定义 `env` 目录存放环境文件,按 Vite 规范命名:`.env.development`、`.env.production` 等。 + +关键变量(部分): +- VITE_APP_TITLE:应用名称(写入 `manifest.config.ts`) +- VITE_UNI_APPID:uni-app 应用 appid(App) +- VITE_WX_APPID:微信小程序 appid(mp-weixin) +- VITE_FALLBACK_LOCALE:默认语言,如 `zh-Hans` +- VITE_SERVER_BASEURL:服务端基础地址(HTTP 请求 baseURL) +- VITE_DELETE_CONSOLE:构建时是否移除 console(`true`/`false`) +- VITE_SHOW_SOURCEMAP:是否生成 sourcemap(默认关闭) +- VITE_LOGIN_URL:未登录跳转的登录页路径(路由拦截器使用) + +示例(`env/.env.development`): +```env +VITE_APP_TITLE=小智 +VITE_FALLBACK_LOCALE=zh-Hans +VITE_UNI_APPID= +VITE_WX_APPID= + +VITE_SERVER_BASEURL=http://localhost:8080 + +VITE_DELETE_CONSOLE=false +VITE_SHOW_SOURCEMAP=false +VITE_LOGIN_URL=/pages/login/index +``` + +说明: +- `manifest.config.ts` 会从 `env` 读取标题、appid、语言等配置。 + +### 重要注意事项 +⚠️ **部署前必须修改的配置项:** + +1. **应用 ID 配置** + - `VITE_UNI_APPID`:需要在 [DCloud 开发者中心](https://dev.dcloud.net.cn/) 创建应用并获取 AppID + - `VITE_WX_APPID`:需要在 [微信公众平台](https://mp.weixin.qq.com/) 注册小程序并获取 AppID + +2. **服务端地址** + - `VITE_SERVER_BASEURL`:修改为您的实际服务端地址 + +3. **应用信息** + - `VITE_APP_TITLE`:修改为您的应用名称 + - 更新 `src/static/logo.png` 等图标资源 + +4. **其他配置** + - 检查 `manifest.config.ts` 中的应用配置信息 + - 根据需要修改 `src/layouts/fg-tabbar/tabbarList.ts` 中的 tabbar 配置 + +### 详细操作指南 + +#### 1. 获取 uni-app AppID +![生成AppID](../../docs/images/manager-mobile/生成appid.png) +- 复制生成的 AppID 到环境变量 `VITE_UNI_APPID` 中 + +#### 2. 本地运行步骤 +![本地运行](../../docs/images/manager-mobile/本地运行.png) + +**App 本地调试:** +1. 用 HBuilderX 导入 `manager-mobile` 目录 +2. 重新识别项目 +3. 连接手机或使用模拟器进行真机调试 + +**项目识别问题解决:** +![重新识别项目](../../docs/images/manager-mobile/重新识别项目.png) + +如果 HBuilderX 无法正确识别项目类型: +- 在项目根目录右键选择"重新识别项目类型" +- 确保项目被识别为 "uni-app" 项目 + +### 路由与鉴权 +- 在 `src/main.ts` 中注册了路由拦截插件 `routeInterceptor`。 +- 黑名单拦截:仅对配置为需要登录的页面进行校验(来源 `@/utils` 的 `getNeedLoginPages`)。 +- 登录判断:基于用户信息(`pinia` 的 `useUserStore`),未登录将跳转到 `VITE_LOGIN_URL`,并附带重定向回原页面的参数。 + +### 网络请求 +- 基于 `alova` + `@alova/adapter-uniapp`,统一在 `src/http/request/alova.ts` 创建实例。 +- `baseURL` 读取环境配置(`getEnvBaseUrl`),可通过 `method.config.meta.domain` 动态切换域名。 +- 认证:默认从本地 `token`(`uni.getStorageSync('token')`)注入 `Authorization` 头,缺失则重定向登录。 +- 响应:统一处理 `statusCode !== 200` 的 HTTP 错误与业务 `code !== 0` 的错误;`401` 会清除 token 并跳转登录。 + +### 构建与发布 + +**微信小程序:** +1. 确保已配置正确的 `VITE_WX_APPID` +2. 运行 `pnpm build:mp`,产物在 `dist/build/mp-weixin` +3. 用微信开发者工具导入项目目录,并上传代码 +4. 在微信公众平台提交审核 + +**Android & iOS App:** + +#### 3. App 打包发行步骤 + +**步骤一:准备打包** +![打包发行步骤1](../../docs/images/manager-mobile/打包发行步骤1.png) + +1. 确保已配置正确的 `VITE_UNI_APPID` +2. 运行 `pnpm build:app`,产物在 `dist/build/app` +3. 用 HBuilderX 导入项目目录 +4. 在 HBuilderX 中点击"发行" → "原生App-云打包" + +**步骤二:配置打包参数** +![打包发行步骤2](../../docs/images/manager-mobile/打包发行步骤2.png) + +1. **应用图标和启动图**:上传应用图标和启动页面图片 +2. **应用版本号**:设置版本号和版本名称 +3. **签名证书**: + - Android:上传 keystore 证书文件 + - iOS:配置开发者证书和描述文件 +4. **包名配置**:设置应用的包名(Bundle ID) +5. **打包类型**:选择测试包或正式包 +6. 点击"打包"开始云打包流程 + +**发布到应用商店:** +- **Android**:将生成的 APK 文件上传到各大 Android 应用市场 +- **iOS**:将生成的 IPA 文件通过 App Store Connect 上传到 App Store(需要 Apple 开发者账号) + +### 约定与工程化 +- 页面与分包:由 `@uni-helper/vite-plugin-uni-pages` 与 `pages.config.ts` 统一生成;tabbar 配置在 `src/layouts/fg-tabbar/tabbarList.ts`。 +- 组件与 hooks 自动导入:见 `vite.config.ts` 中 `unplugin-auto-import` 与 `@uni-helper/vite-plugin-uni-components`。 +- 样式:使用 UnoCSS 与 `src/style/index.scss`。 +- 状态管理:`pinia` + `pinia-plugin-persistedstate`。 +- 代码规范:内置 `eslint`、`husky`、`lint-staged`,提交前自动格式化(`lint-staged`)。 + +### 常用脚本 +```bash +# 开发 +pnpm dev:mp # 等价 dev:mp-weixin + +# 构建 +pnpm build:mp # 等价 build:mp-weixin + +# 其他 +pnpm type-check +pnpm lint && pnpm lint:fix +``` + +### License +MIT diff --git a/main/manager-mobile/eslint.config.mjs b/main/manager-mobile/eslint.config.mjs new file mode 100644 index 000000000..54ce246d6 --- /dev/null +++ b/main/manager-mobile/eslint.config.mjs @@ -0,0 +1,43 @@ +import uniHelper from '@uni-helper/eslint-config' + +export default uniHelper({ + unocss: true, + vue: true, + markdown: false, + ignores: [ + 'src/uni_modules/', + 'dist', + // unplugin-auto-import 生成的类型文件,每次提交都改变,所以加入这里吧,与 .gitignore 配合使用 + 'auto-import.d.ts', + // vite-plugin-uni-pages 生成的类型文件,每次切换分支都一堆不同的,所以直接 .gitignore + 'uni-pages.d.ts', + // 插件生成的文件 + 'src/pages.json', + 'src/manifest.json', + // 忽略自动生成文件 + 'src/service/app/**', + ], + rules: { + 'no-console': 'off', + 'no-unused-vars': 'off', + 'vue/no-unused-refs': 'off', + 'unused-imports/no-unused-vars': 'off', + 'eslint-comments/no-unlimited-disable': 'off', + 'jsdoc/check-param-names': 'off', + 'jsdoc/require-returns-description': 'off', + 'ts/no-empty-object-type': 'off', + 'no-extend-native': 'off', + }, + formatters: { + /** + * Format CSS, LESS, SCSS files, also the ` diff --git a/main/manager-mobile/src/api/agent/agent.ts b/main/manager-mobile/src/api/agent/agent.ts new file mode 100644 index 000000000..09f352f24 --- /dev/null +++ b/main/manager-mobile/src/api/agent/agent.ts @@ -0,0 +1,185 @@ +import type { + Agent, + AgentCreateData, + AgentDetail, + ModelOption, + RoleTemplate, +} from './types' +import { http } from '@/http/request/alova' + +// 获取智能体详情 +export function getAgentDetail(id: string) { + return http.Get(`/agent/${id}`, { + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 获取角色模板列表 +export function getRoleTemplates() { + return http.Get('/agent/template', { + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 获取模型选项 +export function getModelOptions(modelType: string, modelName: string = '') { + return http.Get('/models/names', { + params: { + modelType, + modelName, + }, + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 获取智能体列表 +export function getAgentList() { + return http.Get('/agent/list', { + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 创建智能体 +export function createAgent(data: AgentCreateData) { + return http.Post('/agent', data, { + meta: { + ignoreAuth: false, + toast: true, + }, + }) +} + +// 删除智能体 +export function deleteAgent(id: string) { + return http.Delete(`/agent/${id}`, { + meta: { + ignoreAuth: false, + toast: true, + }, + }) +} + +// 获取TTS音色列表 +export function getTTSVoices(ttsModelId: string, voiceName: string = '') { + return http.Get<{ id: string, name: string }[]>(`/models/${ttsModelId}/voices`, { + params: { + voiceName, + }, + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 更新智能体 +export function updateAgent(id: string, data: Partial) { + return http.Put(`/agent/${id}`, data, { + meta: { + ignoreAuth: false, + toast: true, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 获取插件列表 +export function getPluginFunctions() { + return http.Get(`/models/provider/plugin/names`, { + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 获取mcp接入点 +export function getMcpAddress(agentId: string) { + return http.Get(`/agent/mcp/address/${agentId}`, { + meta: { + ignoreAuth: false, + toast: false, + }, + }) +} + +// 获取mcp工具 +export function getMcpTools(agentId: string) { + return http.Get(`/agent/mcp/tools/${agentId}`, { + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 获取声纹列表 +export function getVoicePrintList(agentId: string) { + return http.Get(`/agent/voice-print/list/${agentId}`, { + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 获取语音对话记录 +export function getChatHistoryUser(agentId: string) { + return http.Get(`/agent/${agentId}/chat-history/user`, { + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 新增声纹说话人 +export function createVoicePrint(data: { agentId: string, audioId: string, sourceName: string, introduce: string }) { + return http.Post('/agent/voice-print', data, { + meta: { + ignoreAuth: false, + toast: true, + }, + }) +} diff --git a/main/manager-mobile/src/api/agent/types.ts b/main/manager-mobile/src/api/agent/types.ts new file mode 100644 index 000000000..66559a23c --- /dev/null +++ b/main/manager-mobile/src/api/agent/types.ts @@ -0,0 +1,107 @@ +// 智能体列表数据类型 +export interface Agent { + id: string + agentName: string + ttsModelName: string + ttsVoiceName: string + llmModelName: string + vllmModelName: string + memModelId: string + systemPrompt: string + summaryMemory: string | null + lastConnectedAt: string | null + deviceCount: number +} + +// 智能体创建数据类型 +export interface AgentCreateData { + agentName: string +} + +// 智能体详情数据类型 +export interface AgentDetail { + id: string + userId: string + agentCode: string + agentName: string + asrModelId: string + vadModelId: string + llmModelId: string + vllmModelId: string + ttsModelId: string + ttsVoiceId: string + memModelId: string + intentModelId: string + chatHistoryConf: number + systemPrompt: string + summaryMemory: string + langCode: string + language: string + sort: number + creator: string + createdAt: string + updater: string + updatedAt: string + functions: AgentFunction[] +} + +export interface AgentFunction { + id?: string + agentId?: string + pluginId: string + paramInfo: Record | null +} + +// 角色模板数据类型 +export interface RoleTemplate { + id: string + agentCode: string + agentName: string + asrModelId: string + vadModelId: string + llmModelId: string + vllmModelId: string + ttsModelId: string + ttsVoiceId: string + memModelId: string + intentModelId: string + chatHistoryConf: number + systemPrompt: string + summaryMemory: string + langCode: string + language: string + sort: number + creator: string + createdAt: string + updater: string + updatedAt: string +} + +// 模型选项数据类型 +export interface ModelOption { + id: string + modelName: string +} + +export interface PluginField { + key: string + type: string + label: string + default: string + selected?: boolean + editing?: boolean +} + +export interface PluginDefinition { + id: string + modelType: string + providerCode: string + name: string + fields: PluginField[] // 注意:原始是字符串,需要先 JSON.parse + sort: number + updater: string + updateDate: string + creator: string + createDate: string + [key: string]: any +} diff --git a/main/manager-mobile/src/api/auth.ts b/main/manager-mobile/src/api/auth.ts new file mode 100644 index 000000000..07cc3fa83 --- /dev/null +++ b/main/manager-mobile/src/api/auth.ts @@ -0,0 +1,127 @@ +import { http } from '@/http/request/alova' + +// 登录接口数据类型 +export interface LoginData { + username: string + password: string + captcha: string + captchaId: string + areaCode?: string + mobile?: string +} + +// 登录响应数据类型 +export interface LoginResponse { + token: string + expire: number + clientHash: string +} + +// 验证码响应数据类型 +export interface CaptchaResponse { + captchaId: string + captchaImage: string +} + +// 获取验证码 +export function getCaptcha(uuid: string) { + return http.Get('/user/captcha', { + params: { uuid }, + meta: { + ignoreAuth: true, + toast: false, + }, + }) +} + +// 用户登录 +export function login(data: LoginData) { + return http.Post('/user/login', data, { + meta: { + ignoreAuth: true, + toast: true, + }, + }) +} + +// 用户信息响应数据类型 +export interface UserInfo { + id: number + username: string + realName: string + email: string + mobile: string + status: number + superAdmin: number +} + +// 公共配置响应数据类型 +export interface PublicConfig { + enableMobileRegister: boolean + version: string + year: string + allowUserRegister: boolean + mobileAreaList: Array<{ + name: string + key: string + }> + beianIcpNum: string + beianGaNum: string + name: string +} + +// 获取用户信息 +export function getUserInfo() { + return http.Get('/user/info', { + meta: { + ignoreAuth: false, + toast: false, + }, + }) +} + +// 获取公共配置 +export function getPublicConfig() { + return http.Get('/user/pub-config', { + meta: { + ignoreAuth: true, + toast: false, + }, + }) +} + +// 注册数据类型 +export interface RegisterData { + username: string + password: string + confirmPassword: string + captcha: string + captchaId: string + areaCode: string + mobile: string + mobileCaptcha: string +} + +// 发送短信验证码 +export function sendSmsCode(data: { + phone: string + captcha: string + captchaId: string +}) { + return http.Post('/user/smsVerification', data, { + meta: { + ignoreAuth: true, + toast: false, + }, + }) +} + +// 用户注册 +export function register(data: RegisterData) { + return http.Post('/user/register', data, { + meta: { + ignoreAuth: true, + toast: true, + }, + }) +} diff --git a/main/manager-mobile/src/api/chat-history/chat-history.ts b/main/manager-mobile/src/api/chat-history/chat-history.ts new file mode 100644 index 000000000..89c3f1ef7 --- /dev/null +++ b/main/manager-mobile/src/api/chat-history/chat-history.ts @@ -0,0 +1,60 @@ +import type { + ChatMessage, + ChatSessionsResponse, + GetSessionsParams, +} from './types' +import { http } from '@/http/request/alova' + +/** + * 获取聊天会话列表 + * @param agentId 智能体ID + * @param params 分页参数 + */ +export function getChatSessions(agentId: string, params: GetSessionsParams) { + return http.Get(`/agent/${agentId}/sessions`, { + params, + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +/** + * 获取聊天记录详情 + * @param agentId 智能体ID + * @param sessionId 会话ID + */ +export function getChatHistory(agentId: string, sessionId: string) { + return http.Get(`/agent/${agentId}/chat-history/${sessionId}`, { + meta: { + ignoreAuth: false, + toast: false, + }, + }) +} + +/** + * 获取音频下载ID + * @param audioId 音频ID + */ +export function getAudioId(audioId: string) { + return http.Post(`/agent/audio/${audioId}`, {}, { + meta: { + ignoreAuth: false, + toast: false, + }, + }) +} + +/** + * 获取音频播放地址 + * @param downloadId 下载ID + */ +export function getAudioPlayUrl(downloadId: string) { + // 根据需求文档,这个是直接返回二进制的,所以我们直接构造URL + return `/agent/play/${downloadId}` +} diff --git a/main/manager-mobile/src/api/chat-history/index.ts b/main/manager-mobile/src/api/chat-history/index.ts new file mode 100644 index 000000000..ecf782a43 --- /dev/null +++ b/main/manager-mobile/src/api/chat-history/index.ts @@ -0,0 +1,2 @@ +export * from './chat-history' +export * from './types' diff --git a/main/manager-mobile/src/api/chat-history/types.ts b/main/manager-mobile/src/api/chat-history/types.ts new file mode 100644 index 000000000..b895ed475 --- /dev/null +++ b/main/manager-mobile/src/api/chat-history/types.ts @@ -0,0 +1,38 @@ +// 聊天会话列表项 +export interface ChatSession { + sessionId: string + createdAt: string + chatCount: number +} + +// 聊天会话列表响应 +export interface ChatSessionsResponse { + total: number + list: ChatSession[] +} + +// 聊天消息 +export interface ChatMessage { + createdAt: string + chatType: 1 | 2 // 1是用户,2是AI + content: string + audioId: string | null + macAddress: string +} + +// 用户消息内容(需要解析JSON) +export interface UserMessageContent { + speaker: string + content: string +} + +// 获取聊天会话列表参数 +export interface GetSessionsParams { + page: number + limit: number +} + +// 音频播放相关 +export interface AudioResponse { + data: string // 音频下载ID +} diff --git a/main/manager-mobile/src/api/device/device.ts b/main/manager-mobile/src/api/device/device.ts new file mode 100644 index 000000000..fc9d5f69b --- /dev/null +++ b/main/manager-mobile/src/api/device/device.ts @@ -0,0 +1,55 @@ +import type { Device, FirmwareType } from './types' +import { http } from '@/http/request/alova' + +/** + * 获取设备类型列表 + */ +export function getFirmwareTypes() { + return http.Get('/admin/dict/data/type/FIRMWARE_TYPE') +} + +/** + * 获取绑定设备列表 + * @param agentId 智能体ID + */ +export function getBindDevices(agentId: string) { + return http.Get(`/device/bind/${agentId}`, { + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +/** + * 添加设备 + * @param agentId 智能体ID + * @param code 验证码 + */ +export function bindDevice(agentId: string, code: string) { + return http.Post(`/device/bind/${agentId}/${code}`, null) +} + +/** + * 设置设备OTA升级开关 + * @param deviceId 设备ID (MAC地址) + * @param autoUpdate 是否自动升级 0|1 + */ +export function updateDeviceAutoUpdate(deviceId: string, autoUpdate: number) { + return http.Put(`/device/update/${deviceId}`, { + autoUpdate, + }) +} + +/** + * 解绑设备 + * @param deviceId 设备ID (MAC地址) + */ +export function unbindDevice(deviceId: string) { + return http.Post('/device/unbind', { + deviceId, + }) +} diff --git a/main/manager-mobile/src/api/device/index.ts b/main/manager-mobile/src/api/device/index.ts new file mode 100644 index 000000000..aa5f61790 --- /dev/null +++ b/main/manager-mobile/src/api/device/index.ts @@ -0,0 +1,2 @@ +export * from './device' +export * from './types' diff --git a/main/manager-mobile/src/api/device/types.ts b/main/manager-mobile/src/api/device/types.ts new file mode 100644 index 000000000..4b6165c53 --- /dev/null +++ b/main/manager-mobile/src/api/device/types.ts @@ -0,0 +1,21 @@ +export interface FirmwareType { + name: string + key: string +} + +export interface Device { + id: string + userId: string + macAddress: string + lastConnectedAt: string + autoUpdate: number + board: string + alias?: string + agentId: string + appVersion: string + sort: number + updater?: string + updateDate: string + creator: string + createDate: string +} diff --git a/main/manager-mobile/src/api/voiceprint/index.ts b/main/manager-mobile/src/api/voiceprint/index.ts new file mode 100644 index 000000000..af56e69ac --- /dev/null +++ b/main/manager-mobile/src/api/voiceprint/index.ts @@ -0,0 +1,2 @@ +export * from './types' +export * from './voiceprint' diff --git a/main/manager-mobile/src/api/voiceprint/types.ts b/main/manager-mobile/src/api/voiceprint/types.ts new file mode 100644 index 000000000..726b17833 --- /dev/null +++ b/main/manager-mobile/src/api/voiceprint/types.ts @@ -0,0 +1,29 @@ +// 声纹信息响应类型 +export interface VoicePrint { + id: string + audioId: string + sourceName: string + introduce: string + createDate: string +} + +// 语音对话记录类型 +export interface ChatHistory { + content: string + audioId: string +} + +// 创建说话人数据类型 +export interface CreateSpeakerData { + agentId: string + audioId: string + sourceName: string + introduce: string +} + +// 通用响应类型 +export interface ApiResponse { + code: number + msg: string + data: T +} diff --git a/main/manager-mobile/src/api/voiceprint/voiceprint.ts b/main/manager-mobile/src/api/voiceprint/voiceprint.ts new file mode 100644 index 000000000..600696dd1 --- /dev/null +++ b/main/manager-mobile/src/api/voiceprint/voiceprint.ts @@ -0,0 +1,62 @@ +import type { + ChatHistory, + CreateSpeakerData, + VoicePrint, +} from './types' +import { http } from '@/http/request/alova' + +// 获取声纹列表 +export function getVoicePrintList(agentId: string) { + return http.Get(`/agent/voice-print/list/${agentId}`, { + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 获取语音对话记录(用于选择声纹向量) +export function getChatHistory(agentId: string) { + return http.Get(`/agent/${agentId}/chat-history/user`, { + meta: { + ignoreAuth: false, + toast: false, + }, + cacheFor: { + expire: 0, + }, + }) +} + +// 新增说话人 +export function createVoicePrint(data: CreateSpeakerData) { + return http.Post('/agent/voice-print', data, { + meta: { + ignoreAuth: false, + toast: true, + }, + }) +} + +// 删除声纹 +export function deleteVoicePrint(id: string) { + return http.Delete(`/agent/voice-print/${id}`, { + meta: { + ignoreAuth: false, + toast: true, + }, + }) +} + +// 更新声纹信息 +export function updateVoicePrint(data: VoicePrint) { + return http.Put('/agent/voice-print', data, { + meta: { + ignoreAuth: false, + toast: true, + }, + }) +} diff --git a/main/manager-mobile/src/components/.gitkeep b/main/manager-mobile/src/components/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/main/manager-mobile/src/components/custom-tabs/index.vue b/main/manager-mobile/src/components/custom-tabs/index.vue new file mode 100644 index 000000000..f5ef0705d --- /dev/null +++ b/main/manager-mobile/src/components/custom-tabs/index.vue @@ -0,0 +1,131 @@ + + + + + diff --git a/main/manager-mobile/src/env.d.ts b/main/manager-mobile/src/env.d.ts new file mode 100644 index 000000000..b4a2c97b2 --- /dev/null +++ b/main/manager-mobile/src/env.d.ts @@ -0,0 +1,34 @@ +/// +/// + +declare module '*.vue' { + import type { DefineComponent } from 'vue' + + const component: DefineComponent<{}, {}, any> + export default component +} + +interface ImportMetaEnv { + /** 网站标题,应用名称 */ + readonly VITE_APP_TITLE: string + /** 服务端口号 */ + readonly VITE_SERVER_PORT: string + /** 后台接口地址 */ + readonly VITE_SERVER_BASEURL: string + /** H5是否需要代理 */ + readonly VITE_APP_PROXY: 'true' | 'false' + /** H5是否需要代理,需要的话有个前缀 */ + readonly VITE_APP_PROXY_PREFIX: string // 一般是/api + /** 上传图片地址 */ + readonly VITE_UPLOAD_BASEURL: string + /** 是否清除console */ + readonly VITE_DELETE_CONSOLE: string + // 更多环境变量... +} + +interface ImportMeta { + readonly env: ImportMetaEnv +} + +declare const __VITE_APP_PROXY__: 'true' | 'false' +declare const __UNI_PLATFORM__: 'app' | 'h5' | 'mp-alipay' | 'mp-baidu' | 'mp-kuaishou' | 'mp-lark' | 'mp-qq' | 'mp-tiktok' | 'mp-weixin' | 'mp-xiaochengxu' diff --git a/main/manager-mobile/src/hooks/.gitkeep b/main/manager-mobile/src/hooks/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/main/manager-mobile/src/hooks/usePageAuth.ts b/main/manager-mobile/src/hooks/usePageAuth.ts new file mode 100644 index 000000000..fd006c812 --- /dev/null +++ b/main/manager-mobile/src/hooks/usePageAuth.ts @@ -0,0 +1,50 @@ +import { onLoad } from '@dcloudio/uni-app' +import { useUserStore } from '@/store' +import { needLoginPages as _needLoginPages, getNeedLoginPages } from '@/utils' + +const loginRoute = import.meta.env.VITE_LOGIN_URL +const isDev = import.meta.env.DEV +function isLogined() { + const userStore = useUserStore() + return !!userStore.userInfo.username +} +// 检查当前页面是否需要登录 +export function usePageAuth() { + onLoad((options) => { + // 获取当前页面路径 + const pages = getCurrentPages() + const currentPage = pages[pages.length - 1] + const currentPath = `/${currentPage.route}` + + // 获取需要登录的页面列表 + let needLoginPages: string[] = [] + if (isDev) { + needLoginPages = getNeedLoginPages() + } + else { + needLoginPages = _needLoginPages + } + + // 检查当前页面是否需要登录 + const isNeedLogin = needLoginPages.includes(currentPath) + if (!isNeedLogin) { + return + } + + const hasLogin = isLogined() + if (hasLogin) { + return true + } + + // 构建重定向URL + const queryString = Object.entries(options || {}) + .map(([key, value]) => `${key}=${encodeURIComponent(String(value))}`) + .join('&') + + const currentFullPath = queryString ? `${currentPath}?${queryString}` : currentPath + const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(currentFullPath)}` + + // 重定向到登录页 + uni.redirectTo({ url: redirectRoute }) + }) +} diff --git a/main/manager-mobile/src/hooks/useRequest.ts b/main/manager-mobile/src/hooks/useRequest.ts new file mode 100644 index 000000000..017a710ad --- /dev/null +++ b/main/manager-mobile/src/hooks/useRequest.ts @@ -0,0 +1,51 @@ +import type { Ref } from 'vue' + +interface IUseRequestOptions { + /** 是否立即执行 */ + immediate?: boolean + /** 初始化数据 */ + initialData?: T +} + +interface IUseRequestReturn { + loading: Ref + error: Ref + data: Ref + run: () => Promise +} + +/** + * useRequest是一个定制化的请求钩子,用于处理异步请求和响应。 + * @param func 一个执行异步请求的函数,返回一个包含响应数据的Promise。 + * @param options 包含请求选项的对象 {immediate, initialData}。 + * @param options.immediate 是否立即执行请求,默认为false。 + * @param options.initialData 初始化数据,默认为undefined。 + * @returns 返回一个对象{loading, error, data, run},包含请求的加载状态、错误信息、响应数据和手动触发请求的函数。 + */ +export default function useRequest( + func: () => Promise>, + options: IUseRequestOptions = { immediate: false }, +): IUseRequestReturn { + const loading = ref(false) + const error = ref(false) + const data = ref(options.initialData) as Ref + const run = async () => { + loading.value = true + return func() + .then((res) => { + data.value = res.data + error.value = false + return data.value + }) + .catch((err) => { + error.value = err + throw err + }) + .finally(() => { + loading.value = false + }) + } + + options.immediate && run() + return { loading, error, data, run } +} diff --git a/main/manager-mobile/src/hooks/useUpload.ts b/main/manager-mobile/src/hooks/useUpload.ts new file mode 100644 index 000000000..3080d5a79 --- /dev/null +++ b/main/manager-mobile/src/hooks/useUpload.ts @@ -0,0 +1,160 @@ +import { ref } from 'vue' +import { getEnvBaseUploadUrl } from '@/utils' + +const VITE_UPLOAD_BASEURL = `${getEnvBaseUploadUrl()}` + +type TfileType = 'image' | 'file' +type TImage = 'png' | 'jpg' | 'jpeg' | 'webp' | '*' +type TFile = 'doc' | 'docx' | 'ppt' | 'zip' | 'xls' | 'xlsx' | 'txt' | TImage + +interface TOptions { + formData?: Record + maxSize?: number + accept?: T extends 'image' ? TImage[] : TFile[] + fileType?: T + success?: (params: any) => void + error?: (err: any) => void +} + +export default function useUpload(options: TOptions = {} as TOptions) { + const { + formData = {}, + maxSize = 5 * 1024 * 1024, + accept = ['*'], + fileType = 'image', + success, + error: onError, + } = options + + const loading = ref(false) + const error = ref(null) + const data = ref(null) + + const handleFileChoose = ({ tempFilePath, size }: { tempFilePath: string, size: number }) => { + if (size > maxSize) { + uni.showToast({ + title: `文件大小不能超过 ${maxSize / 1024 / 1024}MB`, + icon: 'none', + }) + return + } + + // const fileExtension = file?.tempFiles?.name?.split('.').pop()?.toLowerCase() + // const isTypeValid = accept.some((type) => type === '*' || type.toLowerCase() === fileExtension) + + // if (!isTypeValid) { + // uni.showToast({ + // title: `仅支持 ${accept.join(', ')} 格式的文件`, + // icon: 'none', + // }) + // return + // } + + loading.value = true + uploadFile({ + tempFilePath, + formData, + onSuccess: (res) => { + const { data: _data } = JSON.parse(res) + data.value = _data + // console.log('上传成功', res) + success?.(_data) + }, + onError: (err) => { + error.value = err + onError?.(err) + }, + onComplete: () => { + loading.value = false + }, + }) + } + + const run = () => { + // 微信小程序从基础库 2.21.0 开始, wx.chooseImage 停止维护,请使用 uni.chooseMedia 代替。 + // 微信小程序在2023年10月17日之后,使用本API需要配置隐私协议 + const chooseFileOptions = { + count: 1, + success: (res: any) => { + console.log('File selected successfully:', res) + // 小程序中res:{errMsg: "chooseImage:ok", tempFiles: [{fileType: "image", size: 48976, tempFilePath: "http://tmp/5iG1WpIxTaJf3ece38692a337dc06df7eb69ecb49c6b.jpeg"}]} + // h5中res:{errMsg: "chooseImage:ok", tempFilePaths: "blob:http://localhost:9000/f74ab6b8-a14d-4cb6-a10d-fcf4511a0de5", tempFiles: [File]} + // h5的File有以下字段:{name: "girl.jpeg", size: 48976, type: "image/jpeg"} + // App中res:{errMsg: "chooseImage:ok", tempFilePaths: "file:///Users/feige/xxx/gallery/1522437259-compressed-IMG_0006.jpg", tempFiles: [File]} + // App的File有以下字段:{path: "file:///Users/feige/xxx/gallery/1522437259-compressed-IMG_0006.jpg", size: 48976} + let tempFilePath = '' + let size = 0 + // #ifdef MP-WEIXIN + tempFilePath = res.tempFiles[0].tempFilePath + size = res.tempFiles[0].size + // #endif + // #ifndef MP-WEIXIN + tempFilePath = res.tempFilePaths[0] + size = res.tempFiles[0].size + // #endif + handleFileChoose({ tempFilePath, size }) + }, + fail: (err: any) => { + console.error('File selection failed:', err) + error.value = err + onError?.(err) + }, + } + + if (fileType === 'image') { + // #ifdef MP-WEIXIN + uni.chooseMedia({ + ...chooseFileOptions, + mediaType: ['image'], + }) + // #endif + + // #ifndef MP-WEIXIN + uni.chooseImage(chooseFileOptions) + // #endif + } + else { + uni.chooseFile({ + ...chooseFileOptions, + type: 'all', + }) + } + } + + return { loading, error, data, run } +} + +async function uploadFile({ + tempFilePath, + formData, + onSuccess, + onError, + onComplete, +}: { + tempFilePath: string + formData: Record + onSuccess: (data: any) => void + onError: (err: any) => void + onComplete: () => void +}) { + uni.uploadFile({ + url: VITE_UPLOAD_BASEURL, + filePath: tempFilePath, + name: 'file', + formData, + success: (uploadFileRes) => { + try { + const data = uploadFileRes.data + onSuccess(data) + } + catch (err) { + onError(err) + } + }, + fail: (err) => { + console.error('Upload failed:', err) + onError(err) + }, + complete: onComplete, + }) +} diff --git a/main/manager-mobile/src/http/README.md b/main/manager-mobile/src/http/README.md new file mode 100644 index 000000000..fd34fd52b --- /dev/null +++ b/main/manager-mobile/src/http/README.md @@ -0,0 +1,36 @@ +# 请求库 + +当前项目使用 Alova 作为唯一的 HTTP 请求库: + +## 使用方式 + +- **Alova HTTP**:路径(src/http/request/alova.ts) +- **示例代码**:src/api/foo-alova.ts 和 src/api/foo.ts +- **API文档**:https://alova.js.org/ + +## 配置说明 + +Alova 实例已配置: +- 自动 Token 认证和刷新 +- 统一错误处理和提示 +- 支持动态域名切换 +- 内置请求/响应拦截器 + +## 使用示例 + +```typescript +import { http } from '@/http/request/alova' + +// GET 请求 +http.Get('/api/path', { + params: { id: 1 }, + headers: { 'Custom-Header': 'value' }, + meta: { toast: false } // 关闭错误提示 +}) + +// POST 请求 +http.Post('/api/path', data, { + params: { query: 'param' }, + headers: { 'Content-Type': 'application/json' } +}) +``` \ No newline at end of file diff --git a/main/manager-mobile/src/http/request/alova.ts b/main/manager-mobile/src/http/request/alova.ts new file mode 100644 index 000000000..288e2542c --- /dev/null +++ b/main/manager-mobile/src/http/request/alova.ts @@ -0,0 +1,120 @@ +import type { uniappRequestAdapter } from '@alova/adapter-uniapp' +import type { IResponse } from './types' +import AdapterUniapp from '@alova/adapter-uniapp' +import { createAlova } from 'alova' +import { createServerTokenAuthentication } from 'alova/client' +import VueHook from 'alova/vue' +import { getEnvBaseUrl } from '@/utils' +import { toast } from '@/utils/toast' +import { ContentTypeEnum, ResultEnum, ShowMessage } from './enum' + +/** + * 创建请求实例 + */ +const { onAuthRequired, onResponseRefreshToken } = createServerTokenAuthentication< + typeof VueHook, + typeof uniappRequestAdapter +>({ + refreshTokenOnError: { + isExpired: (error) => { + return error.response?.status === ResultEnum.Unauthorized + }, + handler: async () => { + try { + // await authLogin(); + } + catch (error) { + // 切换到登录页 + await uni.reLaunch({ url: '/pages/login/index' }) + throw error + } + }, + }, +}) + +/** + * alova 请求实例 + */ +const alovaInstance = createAlova({ + baseURL: getEnvBaseUrl(), + ...AdapterUniapp(), + timeout: 5000, + statesHook: VueHook, + + beforeRequest: onAuthRequired((method) => { + // 设置默认 Content-Type + method.config.headers = { + 'Content-Type': ContentTypeEnum.JSON, + 'Accept': 'application/json, text/plain, */*', + ...method.config.headers, + } + + const { config } = method + const ignoreAuth = config.meta?.ignoreAuth + console.log('ignoreAuth===>', ignoreAuth) + + // 处理认证信息 + if (!ignoreAuth) { + const token = uni.getStorageSync('token') + if (!token) { + // 跳转到登录页 + uni.reLaunch({ url: '/pages/login/index' }) + throw new Error('[请求错误]:未登录') + } + // 添加 Authorization 头 + method.config.headers.Authorization = `Bearer ${token}` + } + + // 处理动态域名 + if (config.meta?.domain) { + method.baseURL = config.meta.domain + console.log('当前域名', method.baseURL) + } + }), + + responded: onResponseRefreshToken((response, method) => { + const { config } = method + const { requestType } = config + const { + statusCode, + data: rawData, + errMsg, + } = response as UniNamespace.RequestSuccessCallbackResult + + console.log(response) + + // 处理特殊请求类型(上传/下载) + if (requestType === 'upload' || requestType === 'download') { + return response + } + + // 处理 HTTP 状态码错误 + if (statusCode !== 200) { + const errorMessage = ShowMessage(statusCode) || `HTTP请求错误[${statusCode}]` + console.error('errorMessage===>', errorMessage) + toast.error(errorMessage) + throw new Error(`${errorMessage}:${errMsg}`) + } + + // 处理业务逻辑错误 + const { code, msg, data } = rawData as IResponse + if (code !== ResultEnum.Success) { + // 检查是否为token失效 + if (code === ResultEnum.Unauthorized) { + // 清除token并跳转到登录页 + uni.removeStorageSync('token') + uni.reLaunch({ url: '/pages/login/index' }) + throw new Error(`请求错误[${code}]:${msg}`) + } + + if (config.meta?.toast !== false) { + toast.warning(msg) + } + throw new Error(`请求错误[${code}]:${msg}`) + } + // 处理成功响应,返回业务数据 + return data + }), +}) + +export const http = alovaInstance diff --git a/main/manager-mobile/src/http/request/enum.ts b/main/manager-mobile/src/http/request/enum.ts new file mode 100644 index 000000000..1868fe085 --- /dev/null +++ b/main/manager-mobile/src/http/request/enum.ts @@ -0,0 +1,66 @@ +export enum ResultEnum { + Success = 0, // 成功 + Error = 400, // 错误 + Unauthorized = 401, // 未授权 + Forbidden = 403, // 禁止访问(原为forbidden) + NotFound = 404, // 未找到(原为notFound) + MethodNotAllowed = 405, // 方法不允许(原为methodNotAllowed) + RequestTimeout = 408, // 请求超时(原为requestTimeout) + InternalServerError = 500, // 服务器错误(原为internalServerError) + NotImplemented = 501, // 未实现(原为notImplemented) + BadGateway = 502, // 网关错误(原为badGateway) + ServiceUnavailable = 503, // 服务不可用(原为serviceUnavailable) + GatewayTimeout = 504, // 网关超时(原为gatewayTimeout) + HttpVersionNotSupported = 505, // HTTP版本不支持(原为httpVersionNotSupported) +} +export enum ContentTypeEnum { + JSON = 'application/json;charset=UTF-8', + FORM_URLENCODED = 'application/x-www-form-urlencoded;charset=UTF-8', + FORM_DATA = 'multipart/form-data;charset=UTF-8', +} +/** + * 根据状态码,生成对应的错误信息 + * @param {number|string} status 状态码 + * @returns {string} 错误信息 + */ +export function ShowMessage(status: number | string): string { + let message: string + switch (status) { + case 400: + message = '请求错误(400)' + break + case 401: + message = '未授权,请重新登录(401)' + break + case 403: + message = '拒绝访问(403)' + break + case 404: + message = '请求出错(404)' + break + case 408: + message = '请求超时(408)' + break + case 500: + message = '服务器错误(500)' + break + case 501: + message = '服务未实现(501)' + break + case 502: + message = '网络错误(502)' + break + case 503: + message = '服务不可用(503)' + break + case 504: + message = '网络超时(504)' + break + case 505: + message = 'HTTP版本不受支持(505)' + break + default: + message = `连接出错(${status})!` + } + return `${message},请检查网络或联系管理员!` +} diff --git a/main/manager-mobile/src/http/request/types.ts b/main/manager-mobile/src/http/request/types.ts new file mode 100644 index 000000000..824aa4f4e --- /dev/null +++ b/main/manager-mobile/src/http/request/types.ts @@ -0,0 +1,22 @@ +// 通用响应格式 +export interface IResponse { + code: number | string + data: T + msg: string + status: string | number +} + +// 分页请求参数 +export interface PageParams { + page: number + pageSize: number + [key: string]: any +} + +// 分页响应数据 +export interface PageResult { + list: T[] + total: number + page: number + pageSize: number +} diff --git a/main/manager-mobile/src/layouts/default.vue b/main/manager-mobile/src/layouts/default.vue new file mode 100644 index 000000000..360c6b216 --- /dev/null +++ b/main/manager-mobile/src/layouts/default.vue @@ -0,0 +1,17 @@ + + + diff --git a/main/manager-mobile/src/layouts/fg-tabbar/fg-tabbar.vue b/main/manager-mobile/src/layouts/fg-tabbar/fg-tabbar.vue new file mode 100644 index 000000000..819aa6fb0 --- /dev/null +++ b/main/manager-mobile/src/layouts/fg-tabbar/fg-tabbar.vue @@ -0,0 +1,68 @@ + + + diff --git a/main/manager-mobile/src/layouts/fg-tabbar/tabbar.md b/main/manager-mobile/src/layouts/fg-tabbar/tabbar.md new file mode 100644 index 000000000..2485b06db --- /dev/null +++ b/main/manager-mobile/src/layouts/fg-tabbar/tabbar.md @@ -0,0 +1,17 @@ +# tabbar 说明 + +`tabbar` 分为 `4 种` 情况: + +- 0 `无 tabbar`,只有一个页面入口,底部无 `tabbar` 显示;常用语临时活动页。 +- 1 `原生 tabbar`,使用 `switchTab` 切换 tabbar,`tabbar` 页面有缓存。 + - 优势:原生自带的 tabbar,最先渲染,有缓存。 + - 劣势:只能使用 2 组图片来切换选中和非选中状态,修改颜色只能重新换图片(或者用 iconfont)。 +- 2 `有缓存自定义 tabbar`,使用 `switchTab` 切换 tabbar,`tabbar` 页面有缓存。使用了第三方 UI 库的 `tabbar` 组件,并隐藏了原生 `tabbar` 的显示。 + - 优势:可以随意配置自己想要的 `svg icon`,切换字体颜色方便。有缓存。可以实现各种花里胡哨的动效等。 + - 劣势:首次点击 tababr 会闪烁。 +- 3 `无缓存自定义 tabbar`,使用 `navigateTo` 切换 `tabbar`,`tabbar` 页面无缓存。使用了第三方 UI 库的 `tabbar` 组件。 + - 优势:可以随意配置自己想要的 svg icon,切换字体颜色方便。可以实现各种花里胡哨的动效等。 + - 劣势:首次点击 `tababr` 会闪烁,无缓存。 + + +> 注意:花里胡哨的效果需要自己实现,本模版不提供。 diff --git a/main/manager-mobile/src/layouts/fg-tabbar/tabbar.ts b/main/manager-mobile/src/layouts/fg-tabbar/tabbar.ts new file mode 100644 index 000000000..03be03fb2 --- /dev/null +++ b/main/manager-mobile/src/layouts/fg-tabbar/tabbar.ts @@ -0,0 +1,11 @@ +/** + * tabbar 状态,增加 storageSync 保证刷新浏览器时在正确的 tabbar 页面 + * 使用reactive简单状态,而不是 pinia 全局状态 + */ +export const tabbarStore = reactive({ + curIdx: uni.getStorageSync('app-tabbar-index') || 0, + setCurIdx(idx: number) { + this.curIdx = idx + uni.setStorageSync('app-tabbar-index', idx) + }, +}) diff --git a/main/manager-mobile/src/layouts/fg-tabbar/tabbarList.ts b/main/manager-mobile/src/layouts/fg-tabbar/tabbarList.ts new file mode 100644 index 000000000..5273136c7 --- /dev/null +++ b/main/manager-mobile/src/layouts/fg-tabbar/tabbarList.ts @@ -0,0 +1,76 @@ +import type { TabBar } from '@uni-helper/vite-plugin-uni-pages' + +type FgTabBarItem = TabBar['list'][0] & { + icon: string + iconType: 'uiLib' | 'unocss' | 'iconfont' +} + +/** + * tabbar 选择的策略,更详细的介绍见 tabbar.md 文件 + * 0: 'NO_TABBAR' `无 tabbar` + * 1: 'NATIVE_TABBAR' `完全原生 tabbar` + * 2: 'CUSTOM_TABBAR_WITH_CACHE' `有缓存自定义 tabbar` + * 3: 'CUSTOM_TABBAR_WITHOUT_CACHE' `无缓存自定义 tabbar` + * + * 温馨提示:本文件的任何代码更改了之后,都需要重新运行,否则 pages.json 不会更新导致错误 + */ +export const TABBAR_MAP = { + NO_TABBAR: 0, + NATIVE_TABBAR: 1, + CUSTOM_TABBAR_WITH_CACHE: 2, + CUSTOM_TABBAR_WITHOUT_CACHE: 3, +} +// TODO:通过这里切换使用tabbar的策略 +export const selectedTabbarStrategy = TABBAR_MAP.NATIVE_TABBAR + +// selectedTabbarStrategy==NATIVE_TABBAR(1) 时,需要填 iconPath 和 selectedIconPath +// selectedTabbarStrategy==CUSTOM_TABBAR(2,3) 时,需要填 icon 和 iconType +// selectedTabbarStrategy==NO_TABBAR(0) 时,tabbarList 不生效 +export const tabbarList: FgTabBarItem[] = [ + { + iconPath: 'static/tabbar/robot.png', + selectedIconPath: 'static/tabbar/robot_activate.png', + pagePath: 'pages/index/index', + text: '首页', + icon: 'home', + // 选用 UI 框架自带的 icon 时,iconType 为 uiLib + iconType: 'uiLib', + }, + { + iconPath: 'static/tabbar/network.png', + selectedIconPath: 'static/tabbar/network_activate.png', + pagePath: 'pages/device-config/index', + text: '配网', + icon: 'i-carbon-network-3', + iconType: 'uiLib', + }, + { + iconPath: 'static/tabbar/system.png', + selectedIconPath: 'static/tabbar/system_activate.png', + pagePath: 'pages/settings/index', + text: '系统', + icon: 'i-carbon-settings', + iconType: 'uiLib', + }, +] + +// NATIVE_TABBAR(1) 和 CUSTOM_TABBAR_WITH_CACHE(2) 时,需要tabbar缓存 +export const cacheTabbarEnable = selectedTabbarStrategy === TABBAR_MAP.NATIVE_TABBAR + || selectedTabbarStrategy === TABBAR_MAP.CUSTOM_TABBAR_WITH_CACHE + +const _tabbar: TabBar = { + // 只有微信小程序支持 custom。App 和 H5 不生效 + custom: selectedTabbarStrategy === TABBAR_MAP.CUSTOM_TABBAR_WITH_CACHE, + color: '#e6e6e6', + selectedColor: '#667dea', + backgroundColor: '#fff', + borderStyle: 'black', + height: '50px', + fontSize: '10px', + iconWidth: '24px', + spacing: '3px', + list: tabbarList as unknown as TabBar['list'], +} + +// 0和1 需要显示底部的tabbar的各种配置,以利用缓存 +export const tabBar = cacheTabbarEnable ? _tabbar : undefined diff --git a/main/manager-mobile/src/layouts/tabbar.vue b/main/manager-mobile/src/layouts/tabbar.vue new file mode 100644 index 000000000..0c1bb1c6e --- /dev/null +++ b/main/manager-mobile/src/layouts/tabbar.vue @@ -0,0 +1,19 @@ + + + diff --git a/main/manager-mobile/src/main.ts b/main/manager-mobile/src/main.ts new file mode 100644 index 000000000..ab429500f --- /dev/null +++ b/main/manager-mobile/src/main.ts @@ -0,0 +1,19 @@ +import { VueQueryPlugin } from '@tanstack/vue-query' +import { createSSRApp } from 'vue' +import App from './App.vue' +import { routeInterceptor } from './router/interceptor' + +import store from './store' +import '@/style/index.scss' +import 'virtual:uno.css' + +export function createApp() { + const app = createSSRApp(App) + app.use(store) + app.use(routeInterceptor) + app.use(VueQueryPlugin) + + return { + app, + } +} diff --git a/main/manager-mobile/src/pages-sub/demo/index.vue b/main/manager-mobile/src/pages-sub/demo/index.vue new file mode 100644 index 000000000..4231cff4e --- /dev/null +++ b/main/manager-mobile/src/pages-sub/demo/index.vue @@ -0,0 +1,27 @@ + +{ + "layout": "default", + "style": { + "navigationBarTitleText": "分包页面" + } +} + + + + + + + diff --git a/main/manager-mobile/src/pages/agent/edit.vue b/main/manager-mobile/src/pages/agent/edit.vue new file mode 100644 index 000000000..36809fa60 --- /dev/null +++ b/main/manager-mobile/src/pages/agent/edit.vue @@ -0,0 +1,701 @@ + + +