Compare commits

...

170 commits
v0.9.7 ... main

Author SHA1 Message Date
wengzh
3219a28039
Merge pull request #3569 from xinnan-tech/py-wakeup
Some checks failed
Tests / Python (xiaozhi-server) (push) Successful in 16m25s
Tests / Java (manager-api) (push) Failing after 10m51s
Tests / Vue (manager-web) (push) Successful in 12m54s
Py wakeup
2026-11-19 17:15:19 +08:00
Sakura-RanChen
aa524af1d3 调整相关测试 2026-11-19 17:11:57 +08:00
koala553
39d4905137
fix: 修复唤醒词未正确传递的问题 (#3565) 2026-11-19 17:03:01 +08:00
wengzh
bc4bc661f5
Merge pull request #3568 from xinnan-tech/py-test-kwargs
Py test kwargs
2026-11-19 15:58:19 +08:00
Sakura-RanChen
a2f949c347 调整字段名过长显示异常 2026-11-19 15:41:41 +08:00
Sakura-RanChen
ad0e514666 调整说明 2026-11-19 15:01:10 +08:00
wengzh
74fd778601
Merge pull request #3525 from xinnan-tech/web-fix-sm2
fix(manager): 升级 sm-crypto 至 0.5.8 修复 SM2 弱随机数漏洞 (CVE-2026-73567)
2026-11-19 14:43:33 +08:00
Sakura-RanChen
e6d711e8fe fix(secure-random): 修复随机源预热挂起导致登录永久转圈 2026-11-19 14:24:47 +08:00
wengzh
d7751f468e
Merge pull request #3524 from xinnan-tech/py-test-ollama
Py test ollama
2026-11-19 11:33:27 +08:00
Sakura-RanChen
285d47783c
Merge branch 'main' into py-test-ollama 2026-11-19 11:26:41 +08:00
wengzh
01f65ee5c4
Merge pull request #3484 from xinnan-tech/py-test-mcp
Py test mcp
2026-11-19 11:23:45 +08:00
Sakura-RanChen
4e898819dd
Merge branch 'main' into py-test-mcp 2026-11-19 11:14:40 +08:00
Sakura-RanChen
c1906d5dff
Merge branch 'main' into py-test-ollama 2026-11-19 11:13:30 +08:00
Sakura-RanChen
462b288bda 调整测试 2026-11-19 11:03:51 +08:00
Sakura-RanChen
7c5fe74410 调整读取逻辑和相关测试 2026-11-19 10:32:21 +08:00
wengzh
cda17f4d6a
Merge pull request #3548 from zhenglieAllen/zhenglieAllen/fix/check-model-key-none
Some checks failed
Tests / Java (manager-api) (push) Failing after 16s
Tests / Vue (manager-web) (push) Successful in 2m46s
Tests / Python (xiaozhi-server) (push) Successful in 3m24s
fix(util): check_model_key 遇到空 api_key 不再抛 TypeError
2026-11-19 09:52:20 +08:00
Sakura-RanChen
4ae96c6e02 fix: 配置读取缺失 2026-11-19 09:40:51 +08:00
Sakura-RanChen
a1919f7db3 补充sql,增加字段校验 2026-11-18 17:11:09 +08:00
kjartan0
5b0c8c303b
feat(llm): 支持 OpenAI 兼容后端透传 chat_template_kwargs (extra_body) (#3564)
Co-authored-by: Kjartan <kjartan0@users.noreply.github.com>
2026-11-18 16:13:19 +08:00
Sakura-RanChen
9100e7ecd2 无快照时不回落共享连接态 2026-11-18 15:14:21 +08:00
Sakura-RanChen
4c04b9dd37 调整并发模拟,减少明文 2026-11-18 14:54:51 +08:00
Sakura-RanChen
f441703e6c 补充形参 2026-11-18 11:43:38 +08:00
wengzh
61a8c04477
feat(web_search): 新增 SpecStream 搜索源 (#3560)
Some checks failed
Tests / Python (xiaozhi-server) (push) Successful in 10m44s
Tests / Java (manager-api) (push) Failing after 30s
Tests / Vue (manager-web) (push) Successful in 11m40s
* feat(web_search): 新增SpecStream搜索源

* docs(web_search): SpecStream API Key申请链接指向注册页

* docs: 更新SpecStream搜索的免费额度信息

---------

Co-authored-by: Tarek Etman <tarek@specstream.ai>
2026-11-16 14:53:37 +08:00
wengzh
b545623b38
Merge pull request #3561 from xinnan-tech/py-test-mem
Py test mem
2026-11-16 14:52:51 +08:00
Sakura-RanChen
63e2bcec8a revert(config): 移除 mem_report_only 出厂配置块,维持单模块 fail-fast 契约
回退 #3547 的核心改动。
mem_report_only 仅在智控台模式下有意义:选项及配置块由 manager-api数据库下发,不依赖本地 config.yaml。
2026-11-13 17:42:16 +08:00
zhenglieAllen
c74a6aaa68
fix(config): 修正 XunfeiSparkLLM 的 base_url 误填成火山方舟地址 (#3546)
现象:把 selected_module.VLLM 设为 XunfeiSparkLLM 后,视觉理解请求全部失败
(鉴权失败或 404),而且讯飞的 api_key 会被发到火山引擎。

原因:config.yaml 里 VLLM.XunfeiSparkLLM.base_url 填的是
https://ark.cn-beijing.volces.com/api/v3 —— 那是上面 LLM.DoubaoLLM 的火山
方舟地址,疑似复制粘贴时带串了。core/providers/vllm/openai.py 取端点时
base_url 优先于 url,所以这个值会直接生效;配套的 model_name: lite 是讯飞
的模型名,在火山方舟上并不存在。

改法:base_url 改成讯飞星火官方 OpenAI 兼容端点
https://spark-api-open.xf-yun.com/v1,并在注释里写明端点与模型名的出处。

测试:新增 tests/config/test_provider_endpoints.py,用一张「provider ->
端点主机名」对照表把这类串台钉死。修复前该用例失败,修复后通过。

Co-authored-by: Allen <zljtx2008@gmail.com>
2026-11-13 16:51:00 +08:00
zhenglieAllen
0d7180d898
fix(config): 给 mem_report_only 补上 Memory 配置块 (#3547)
* fix(config): 给 mem_report_only 补上 Memory 配置块

现象
把 selected_module.Memory 设成 mem_report_only 后,服务在连接初始化阶段
直接崩:

    KeyError: 'mem_report_only'

原因
core/providers/memory/mem_report_only/ 下有完整的 provider 实现,
core/connection.py 的 _initialize_memory 里也显式处理了它
(`if memory_type == "nomem" or memory_type == "mem_report_only"`),
但 config.yaml 的 Memory 段只配了 mem0ai / powermem / nomem /
mem_local_short 四项,没有 mem_report_only。

而 core/connection.py 取配置的方式是直接下标:

    memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]]["type"]

于是只要在 selected_module 里选了 mem_report_only,这个下标就取不到,
连接初始化阶段 KeyError。data/.config.yaml 那边也是整段替换
(self.config["Memory"] = private_config["Memory"]),用户光改
selected_module 而不重复声明一遍 Memory 段,一样会炸。

改法
在 config.yaml 的 Memory 段补上 mem_report_only 配置块(type:
mem_report_only),让出厂配置自洽 —— 选了就能直接用,不需要用户自己
再补一段配置。

测试
新增 tests/config/test_provider_registry.py,钉死两条不变量:
- selected_module 里选中的 provider 必须在对应配置段里存在(防启动期 KeyError);
- 每个 provider 段的每个键,type 字段都必须指向真实存在的实现
  (防「配置有、实现没有」);
- Memory 这类一一对应的模块,实现里有的 provider 配置里必须有(防本次
  这种「实现有、配置没有」)。

修复前 test_every_implemented_provider_is_configured[Memory] 失败,
修复后通过。本地全量:5 failed / 99 passed / 33 skipped / 8 errors,
失败项与改动前完全一致(本地缺 portalocker / pytest-asyncio / edge_tts,
CI 由 requirements.txt 提供),无回归。

* docs(readme): 组件列表补齐 mem_report_only 与科大讯飞视觉模型

现象
README 的「本项目支持的平台/组件列表」有两处和实际出厂配置对不上:

1. VLLM 视觉模型表只列了「阿里百炼、智谱ChatGLMVLLM」,但 config.yaml 的
   VLLM 段出厂就带了 XunfeiSparkLLM(讯飞星火)这个 provider。
2. Memory 记忆存储表只列了 mem0ai / powermem / mem_local_short / nomem,
   没有 mem_report_only —— 而 core/providers/memory/mem_report_only/ 里有
   实现,core/connection.py 里也显式处理了它。

原因
这两个表是手工维护的,新增 provider 时没有同步。VLLM 段的讯飞星火尤其
隐蔽:它的 base_url 还被误填成了火山方舟的地址(ark.cn-beijing.volces.com),
看起来像是没在用,于是没人往表里补。

改法
6 份 README(README.md + docs/readme/ 下的 en/de/es/vi/pt_BR)同步更新:

- VLLM 视觉模型表的「支持平台」列补上科大讯飞 / iFLYTEK。免费平台列不动 ——
  讯飞星火虽有免费额度,但每个模型要单独开通服务后才能用,不属于开箱免费。
- Memory 记忆存储表补上 mem_report_only 一行(使用方式「仅上报」,
  备注「只上报聊天记录,不做记忆总结」,取自 provider 自身的 docstring)。

测试
纯文档改动,无代码路径变化。本次一并把 VLLM 表和 Memory 表跟 config.yaml
的实际内容对齐,避免再出现「文档列的组件在配置里选不到」的情况。

---------

Co-authored-by: Allen <zljtx2008@gmail.com>
2026-11-13 16:31:17 +08:00
wengzh
2dfaf44269
Merge pull request #3559 from xinnan-tech/py-tts-session
Some checks failed
Tests / Java (manager-api) (push) Failing after 41s
Tests / Vue (manager-web) (push) Successful in 11m51s
Tests / Python (xiaozhi-server) (push) Successful in 13m37s
fix(tts): 流式 TTS 会话延迟到首个有效文本开启,修复慢 LLM 场景合成结果为空
2026-11-13 16:13:40 +08:00
Sakura-RanChen
e41bc98a25 fix(tts): 流式 TTS 会话延迟到首个有效文本开启,修复慢 LLM 场景合成结果为空 2026-11-13 10:10:20 +08:00
wengzh
4b1a54a41c
Merge pull request #3545 from xinnan-tech/py-ha-state
Some checks failed
Tests / Java (manager-api) (push) Failing after 2m31s
Tests / Vue (manager-web) (push) Successful in 3m34s
Tests / Python (xiaozhi-server) (push) Successful in 30m21s
Py ha state
2026-11-09 14:43:00 +08:00
Allen
579538478b fix(util): check_model_key 遇到空 api_key 不再抛 TypeError
现象:provider 构造期报
    TypeError: argument of type 'NoneType' is not iterable
而且栈顶落在 core/utils/util.py 的 check_model_key,看不出是哪个模块的
key 没配。智控台下发的配置里未必带 api_key 字段(本地 LLM 场景也常把
它留空),HA 插件配置没填 api_key 时同样中招:hass_state 和
hass_play_music 都调 initialize_hass_handler,整个插件初始化被打断。

原因:check_model_key 直接写 ``"你" in modelKey``,modelKey 为 None 时
这行就炸了;modelKey 为空串时则静默返回 None,等于没检查。

改法:先把 None / 空串当成「未设置」处理,返回提示文案而不是抛异常。
    if not modelKey:
        return f"配置错误: {modelType} 的 API key 未设置"
出厂占位符的分支保持原样,提示文案里仍带当前值,方便用户对照改。

测试:
- 新增 tests/core/utils/test_check_model_key.py:缺 key / 占位符 / 真 key
  三种情况的契约
- tests/plugins_func/test_hass_init.py 补一条端到端:插件配置里没有
  api_key 时 initialize_hass_handler 不再崩
- 全量 pytest tests/ -q 无新增失败

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-11-07 22:33:44 +08:00
wengzh
4f6e9ec6b1
Merge pull request #3544 from xinnan-tech/py-hass-devices
Py hass devices
2026-11-05 16:37:11 +08:00
Sakura-RanChen
dd367c9e43 补充调整 2026-11-05 16:35:18 +08:00
Bao1573
b4e144afef
fix(hass): hass_get_state 的亮度按百分比报 (#3542)
HA 的 brightness 量程是 0~255,原样交给模型会被念成"一百五十三";灯关着时是 null,还会报"亮度是:None"。换算成百分比,和设置亮度用的 brightness_pct 同一个单位,开着的灯最低报 1%(同 HA 前端);不是数字时不报这一项。附测试。
2026-11-05 16:07:40 +08:00
Sakura-RanChen
9f5f520576 fix: 修复ha读取异常 2026-11-05 15:36:04 +08:00
Bao1573
70f1a7bfd8
fix(hass): devices 写成列表时也能拼进提示词 (#3541)
config.yaml 示例和手机端智控台给的 devices 是列表,append_devices_to_prompt 却按字符串直接拼,每次连接都报 can only concatenate str (not "list") to str,设备清单进不了提示词,模型只能猜 entity_id。列表按每项一行拼,字符串原样用,其它当空。附测试。
2026-11-05 11:50:39 +08:00
wengzh
e61f5aee28
Merge pull request #3543 from xinnan-tech/py-tool-cache
fix: prevent tool description cache mutation (#3540)
2026-11-05 10:41:46 +08:00
koala553
c59b29c723
fix: prevent tool description cache mutation (#3540) 2026-11-05 10:10:17 +08:00
wengzh
c8e60d1325
Merge pull request #3539 from xinnan-tech/py-Outcrawl
Py outcrawl
2026-11-04 11:38:20 +08:00
Sakura-RanChen
6589f7f481 调整为code判断 2026-11-04 11:26:20 +08:00
Nirupam Bhowmick
7d9f47b0d1
feat(web_search): 新增Outcrawl搜索源 (#3538) 2026-11-04 10:22:41 +08:00
hrz
5b0de039c9
让 CI 真正跑起三类测试并修掉挡路的测试缺陷 (#3475)
* 让 CI 真正跑起三类测试并修掉挡路的测试缺陷

之前 CI 只跑了一小部分,Java 那边的测试被 pom 里的开关整个跳过了。
这条把它打开,并补上 MySQL、Redis 两个容器,Java、契约、Python 三类
测试都在 CI 里真跑起来。

另外修了两个挡路的地方:一条 Java 用例单跑会因为实体信息没注册而报错,
现在自己注册;Python 的假网络层把整个 httpx 类换掉了,第三方库拼请求
时报错,改成只换发请求那一步。

* 给 runner 补上 libopus,修掉音频用例报错

opuslib_next 是 ctypes 绑定,真正编解码靠系统里的 libopus。runner 上默认
没有,import 失败后测试里换上的是自己写的桩,桩里的编码器只有构造方法,
一调就报错。正式镜像里是装了这个库的,CI 少了这一步。

顺手把桩的报错改成一句人话,别再让人对着缺方法的报错猜根因。

* 本地没起库也能构建,CI 里集成测试不许跳过

三个要连 MySQL 和 Redis 的集成测试加了守卫:依赖连不上就整类跳过,日志写明缺什么,构建照样是绿的;CI 上依赖不通就直接失败。另外加了一个门禁检查脚本和 CI 步骤,盯住这三个类有没有真跑,守卫哪天手滑把它们全跳过了,CI 必须变红。README 里补了本地怎么起依赖、怎么只编译不跑测试。
2026-11-03 17:44:29 +08:00
Sakura-RanChen
398f0bd097 调整相关逻辑, 2026-11-03 15:56:07 +08:00
wengzh
4e1405a6f6
Merge pull request #3537 from xinnan-tech/py-test-tool
Py test tool
2026-11-03 15:03:17 +08:00
Sakura-RanChen
e09df59c13 调整相关逻辑 2026-11-03 11:53:21 +08:00
Sakura-RanChen
f9138e65b7 update: 使用专用线程池避免阻塞默认池 2026-11-03 10:43:53 +08:00
Bao1573
9b8a9b585d
fix(tools): 服务端插件的同步函数放线程池,不阻塞事件循环 (#3528)
ServerPluginExecutor.execute 在事件循环上被 await,而 hass_state、天气等插件用 requests 同步阻塞,工具执行期间整个循环停转、正在发的音频节拍也停。同步函数改用 run_in_executor 放到线程池;async def 插件照常 await;传参规则不变。附测试。
2026-11-02 15:29:34 +08:00
Sakura-RanChen
7f0d416e66
Merge branch 'main' into py-test-ollama 2026-11-02 11:12:49 +08:00
Sakura-RanChen
c282397cd2 fix: 修复review反馈——fields追加式更新与占位符判定 2026-11-02 11:09:40 +08:00
Sakura-RanChen
7e450fca0d fix(manager-mobile): 修复Node 随机源误判、垫片健壮性及补丁哈希更新 2026-11-02 10:33:33 +08:00
欣南科技
92337881a7
Merge pull request #3531 from xinnan-tech/fix/readme-asr-bailian-lmstudio
Fix/readme asr bailian lmstudio
2026-11-01 07:38:49 +08:00
欣南科技
a93b71f9e7
Merge branch 'main' into fix/readme-asr-bailian-lmstudio 2026-11-01 07:38:36 +08:00
hrz
325f52469a
设备呼叫文档改对热词字段的位置 (#3509)
* 设备呼叫文档改对热词字段的位置

热词文件名称是语音识别供应器的字段,文档里写成配到语音合成上,用户照着在语音合成里找根本找不到;同一句 AEC 提示连写三遍,只留一条。

* 设备呼叫文档改对热词配置的供应器名称

把接口类型改成供应器,列出还有热词文件名称的两条模型,补上点确认保存和改完要重连设备。

* 设备呼叫文档里热词字段的说法改准

「这一项」读起来像供应器下拉的子项,实际是弹窗调用信息区域里独立的一个输入框,两处都改成照实说。

* Clarify AEC functionality requirement in guide

Added repeated instruction for enabling AEC functionality during firmware compilation.
2026-11-01 07:10:28 +08:00
hrz
3230a69c99
Merge pull request #3515 from shinjiyu/fix/config-provider-copy-accuracy
fix(config): 纠正供应器占位文案与 PaddleSpeech 协议说明
2026-11-01 06:56:22 +08:00
shinjiyu
1ac4c09946 fix(config): 按审核意见补齐占位文案与 PaddleSpeech 协议收敛
- AliLLM 占位改为「你的阿里云百炼API密钥」;ASR 段「语音合成」改为「语音识别」;XunfeiSparkLLM 占位改为 api_key
- PaddleSpeech:启动时校验 protocol;代码兜底 URL 与 config 对齐为本机;智控台新增 changeset 去掉 http 选项
2026-10-30 20:55:56 +08:00
Sakura-RanChen
42f7e55c72 fix(manager): 升级 sm-crypto 至 0.5.8 修复 SM2 弱随机数漏洞 (CVE-2026-73567) 2026-10-30 15:18:18 +08:00
Sakura-RanChen
5f6e191d11 补充api_key示例 2026-10-29 16:04:20 +08:00
suharvest
27833f918c
fix(ollama): support custom api_key and normalize base_url (closes #3517) (#3518) 2026-10-29 14:44:39 +08:00
wengzh
1a095d5bed
Merge pull request #3523 from xinnan-tech/py-test-fix
Py test fix
2026-10-29 14:20:59 +08:00
Sakura-RanChen
01289b8fd4 仅保留mcp2.x行为 2026-10-29 14:17:38 +08:00
shinjiyu
ef2fcdbcb1
fix(server_mcp): read Tool.input_schema for mcp 2.3.0 (#3522)
mcp==2.3.0 Tool stores the JSON Schema on input_schema (alias
inputSchema). Accessing tool.inputSchema raises AttributeError and
aborts server_mcp init after a successful tools/list.

Use getattr fallback so function-calling conversion works.

Closes #3521

Co-authored-by: shinjiyu <shinjiyu@users.noreply.github.com>
2026-10-29 14:08:44 +08:00
hrz
942ac2fe12
通讯录没起名时不再取对方设备的名字 (#3473)
* 别把对方给设备起的名字抄进自己的通讯录

通讯录里没起名的时候,以前会跑去设备表查目标设备的名字。那是设备主人在智控台上自己起的,
直接抄进调用方的通讯录,等于把别人的昵称漏了出去。现在改成一律用 MAC 尾号称呼,
只有目标是自己那台设备时,才用自己设备表里的名字。补了单测,覆盖对方已起名、目标是自己、
显式起名、目标没登记这几种情况。

* 取自己的设备名改用不会撞行的查法

设备表里同一个 MAC 可能有两行只差大小写,一次只准取一条的查法撞上就抛异常,保存通讯录整个接口带崩。改成按归属查的那一种,按 id 取第一条。

补齐自己那台设备在设备表里没起名时退回尾号称呼的用例,另有几条用例的名字跟实际测的东西对不上,一并改掉。
2026-10-29 11:56:48 +08:00
wengzh
4dbed0ab1d
Merge pull request #3520 from xinnan-tech/py-test-weather
fix: harden weather and news plugins (#3465)
2026-10-29 10:10:50 +08:00
Jacob
15d9b0fba1
fix: harden weather and news plugins (#3465)
* fix: harden weather and news plugins

* 修掉天气新闻插件的三处鲁棒性缺陷

城市查询不再写死国内范围,境外城市也能查到。实时天气和七天预报要都拿到才走 JSON,缺一个就整体退回网页路径,不产出残缺报告。网页抓取加上跟随跳转,旧链接的 302 也能拿到内容。城市查不到时不再让用户去核对地名,多数情况是密钥失效。报告补上气压和降水量。新闻 URL 拼接抽成纯函数,配了 23 项单测。

---------

Co-authored-by: hrz <1710360675@qq.com>
2026-10-29 09:46:01 +08:00
wengzh
8c5330f742
Merge pull request #3516 from xinnan-tech/py-test-think
Py test think
2026-10-28 16:38:12 +08:00
Sakura-RanChen
549261fdff PR 提供的keep 逃生门要求用户自行发现问题、了解该魔法值并手改 configJson,对普通用户不可达。
调整LLM thinking 域名禁用规则支持按模型名豁免(避免 MaaS glm-5.3 被注入参数后 400)
2026-10-28 16:18:58 +08:00
SecInsight
2cb0562ade
feat(llm): 华为云 MaaS 思考强度实例级配置 + 管理台 select 字段类型 (#3446)
- openai provider: THINKING_DISABLED_DOMAINS 补 modelarts-maas.com
- openai provider: 实例配置支持可选 thinking 字段(off/low/medium/high/keep),
  实例值优先于域名默认表; keep=完全直通(适配强制思考且拒绝该参数的模型, 如 MaaS glm-5.3)
- manager-web: 模型配置表单渲染器支持 select 字段类型(el-select + field.options)
  (ModelEditDialog / AddModelDialog 两处渲染点与类型映射)

Co-authored-by: SecInsight <secinsight@users.noreply.github.com>
Co-authored-by: Sakura-RanChen <1908198662@qq.com>
2026-10-28 15:20:28 +08:00
Sakura-RanChen
3bf619e2dd 调整相关逻辑 2026-10-28 11:45:13 +08:00
shinjiyu
ccc77799d9 fix(config): 纠正 AliLLM 占位文案与 PaddleSpeech 协议说明
- AliLLM 的 api_key 占位误写成 deepseek,照抄会把错误 key 填进百炼(#3495)
- PaddleSpeechTTS 实际只实现 websocket,去掉 config/报错里对 http 的承诺(#3503)
2026-10-28 06:02:21 +08:00
hrz
d9c2e8c5d9
德语版README把MCP接入点改用Zugriffspunkt (#3511)
Endpunkt说的是终端点,这里是访问点,术语换过来跟英文版一致。
2026-10-27 21:18:24 +08:00
hrz
1a675e4d6b
部署文档改准:示例配置、镜像架构和日志样例 (#3507)
* 部署文档改准:示例配置、镜像架构和日志样例

最简配置示例里选中的模型改成仓库默认那个;镜像架构那句改成同时提供两种架构;升级步骤去掉单模块没有的 web 容器;compose 文件名、章节编号、配置路径和日志版本号一并改对。

* 部署文档的启动日志样例改成实际模块串

全局日志器拿不到各模块的名字,样例里那串缩写换成实际输出的样子。

* 部署文档的升级步骤编号改对并补全日志样例

升级那几步改成4开头,删掉单模块用不到的web镜像,样例补上视觉分析接口那行,分隔符也对齐实际输出。

* 部署文档里配置说明的路径改成仓库链接

按 docker 方式部署的人,xiaozhi-server 目录下并没有 config.yaml,这句路径换成能点开的仓库链接,两种方式都用得上。
2026-10-27 21:13:05 +08:00
hrz
40a7ed0391
三份译文里的术语跟本文件其它地方对齐 (#3506)
德语版把回答速度统一成反应速度,英语版和葡语版把 MCP 接入点统一成本文件其它地方用的说法。
2026-10-27 21:10:55 +08:00
hrz
62e316f298
把 README 的错字修正和品牌名统一带到 main (#3504)
* 修中文 README 的四处错字并统一品牌名写法

中文 README 自己有四处错:括号不配对、该写客户端的地方写成了客户、提示语用逗号收尾、OpenAI 写成了小写。葡语版和越南语版跟着源文一起小写的几处也改了。

* 把中文源的括号和越南语版的句号改对

中文源文 Memory 那行第 3 格还是全角括号,改成半角,
跟另外五版一样。越南语版提示语那行还是逗号收尾,改成句号。
2026-10-27 21:09:57 +08:00
hrz
76cef92cb2
修正性能测试和声纹识别两份文档里跟代码对不上的十二处 (#3502)
* 修正两份操作文档里跟代码对不上的地方

性能测试那份把配置路径写错、没提要先装依赖,步骤里少了非流式语音合成,流式语音合成要配哪些供应器也没写;声纹识别那份的重启命令指向两个不同的编排文件,有两句话连写三遍,编号也乱了,示例漏了相似度阈值。逐条改到跟代码一致。

* 把性能测试文档的说明改得跟代码一致

供应器表里两家的写法与代码相反,改成如实描述;步骤清单补回流式语音识别;
示例里的视觉模型段改成能跑通的形态;声纹文档两个重复的标题改掉一个。

* 性能测试文档的说法跟Linkerai跳过行为对齐

它没配就整项跳过,不再算进报错后跳过那一类。与#3510的行为对齐。

* 性能测试文档改对缺供应器时的记法

不是跳过,是报错后记成失败,结果表里多一行。带守卫的那几家才是整项跳过。

* 强调易错处
2026-10-27 21:09:09 +08:00
hrz
826c25d3e5
修正 PaddleSpeech 部署文档里对不上代码的四处 (#3501)
* 修正 PaddleSpeech 部署文档里对不上的地方

示例配置里写了 provider 根本不读的那项采样率,还说 http 协议能自动选,其实只实现了 websocket;代码那一节是空的;启动命令没说在哪个目录跑,配置文件的路径只给了 Windows 写法。逐条改到跟代码一致。

* 补上 PaddleSpeech 部署文档的配置目录和环境说明

配置文件那节改成新建,写明 data 目录被 gitignore 忽略,要先建出来。
数字人页面的启动命令改成从仓库根目录算,另开一个终端。
代码块围栏换成 bash,另补一段说明小智服务用哪个 Python 环境,
以及数字人页面那套依赖在哪。

* PaddleSpeech 部署文档修四处会照抄失败的地方

启动命令的围栏改成 bash;建 data 目录那条标明在仓库根目录执行;启动服务那段不再重复 cd;数字人那节补一句 numpy 的依赖来自哪两个文件。

* 修正conda环境名
2026-10-27 21:05:07 +08:00
hrz
f1965167cc
性能测试跳过未配置的Linkerai语音合成 (#3510)
配置里没有这个供应器时整项跳过,不再报一条测试失败。
2026-10-27 15:35:38 +08:00
wengzh
6c352e5978
Merge pull request #3436 from xinnan-tech/perf/hello-handshake-fast
hello 握手首屏响应从 4s 降到 200ms
2026-10-27 14:34:13 +08:00
Sakura-RanChen
032f6f1582 fix: 修复唤醒流程错误阻塞事件接收循环 2026-10-27 10:36:35 +08:00
hrz
a377d89dcd
补齐德语版平台表里漏掉的四个供应器 (#3500)
德语版把火山和阿里拆得比中文细,拆的时候漏了同族的另一个:LLM 少火山网关,TTS 少火山网关和百炼,ASR 少豆包流式 V2。补上,名字按德语版自己的写法。
2026-10-26 22:47:47 +08:00
hrz
d35b9f8b00
修中文 README 的四处错字并统一品牌名写法 (#3498)
中文 README 自己有四处错:括号不配对、该写客户端的地方写成了客户、提示语用逗号收尾、OpenAI 写成了小写。葡语版和越南语版跟着源文一起小写的几处也改了。
2026-10-26 22:30:14 +08:00
hrz
d687121e99
把四份 README 里图片的说明文字译成本地语言 (#3497)
en、de、pt_BR、vi 四份里 15 条演示图的说明文字和架构图那句还是中文,这轮全部译成本地语言,越南语版的校徽说明、葡语版声纹那句也一起改掉。图片路径一个字没动。
2026-10-26 22:29:27 +08:00
hrz
badf6fe3d0
按中文源文补齐四份 README 的描述和术语 (#3494)
横向扫尾清单里的几处:star-history 图表代码还是旧的,换成中文那版;
德语版开头少了知识库这一项;英德葡三版的意图识别行丢了外挂大模型和
自主函数调用这两层说法;越南语版首屏把声纹写成语音识别,
部署表的特点列和版本比较基准也写窄了。
2026-10-26 22:28:49 +08:00
hrz
adb4a15f2d
同步西语版 README 与中文源文的平台清单和说明 (#3492)
* 同步西语版 README 与中文源文的平台清单和说明

西语版落后中文源文一整轮:平台表少了 CustomTTS、SherpaParaformerASR、VoskASR 这些,
旧的 GizwitsTTS、ACGNTTS 还在,Index-TTS、PaddleSpeech 的键名也旧了。
部署表里那组核数和内存全库查不到出处,按中文删掉;界面语种、插件加载、
测试工具和声纹说明那段一并对齐。中文源文和其它四个语言版没动。

* 把音频交互测试工具的用法改成指向 README

原来在用法里内嵌装依赖的命令,句子太长。改成指向 main/digital-human 的 README,
依赖怎么装、模型从哪来,那份 README 里都写了。

* 补上意图识别行里外挂的大模型这一层

中文源文写的是支持外挂的大模型意图识别,西语版只写了模型本身,
把可以外挂这层意思漏了。补上。
2026-10-26 22:27:32 +08:00
hrz
a5f9a782d6
补齐五份 README 的供应器清单和音频测试工具用法 (#3491)
* 补上阿里百炼和 LM Studio 并统一越南语品牌写法

ASR 那行中文只写阿里云,配置里阿里系有三条,另外四份也按各自写法补上百炼。LM Studio 走的是 openai 接口,仓里没有独立的供应器,所以并进 openai 那一行,免费平台那列不动。越南语版三处 iFlytek 统一成官方写法 iFLYTEK。

* 补上音频交互测试工具的前置步骤

digital-human 的说明里要求先装 wakeword 依赖再启动,README 里原来只写了启动命令,照着做会缺依赖。五个语言版的用法都补上这一步。

* 把性能测试脚本的提示写清文档在仓库根

脚本是在 main/xiaozhi-server 下执行的,那儿没有 docs 目录,文档在仓库根,原来的提示照字面找不到文件。

* 统一德语版百炼流式语音识别的写法

同一份文件里 LLM 那行写的是 Alibaba Bailian,语音识别这行写成了 Aliyun Bailian,
同一家供应商两种拼法。改成跟 LLM 那行一样。

* 把音频交互测试工具的用法改成指向 README

原来在用法里内嵌装依赖的命令,句子太长。改成指向 main/digital-human 的 README,
依赖怎么装、模型从哪来,那份 README 里都写了。
2026-10-26 22:26:15 +08:00
hrz
7ab4cc5c90 把音频交互测试工具的用法改成指向 README
原来在用法里内嵌装依赖的命令,句子太长。改成指向 main/digital-human 的 README,
依赖怎么装、模型从哪来,那份 README 里都写了。
2026-10-26 21:13:51 +08:00
hrz
9c4790c8d0 统一德语版百炼流式语音识别的写法
同一份文件里 LLM 那行写的是 Alibaba Bailian,语音识别这行写成了 Aliyun Bailian,
同一家供应商两种拼法。改成跟 LLM 那行一样。
2026-10-26 19:00:26 +08:00
hrz
4fd51c6f7f 把性能测试脚本的提示写清文档在仓库根
脚本是在 main/xiaozhi-server 下执行的,那儿没有 docs 目录,文档在仓库根,原来的提示照字面找不到文件。
2026-10-26 18:46:47 +08:00
hrz
e7e0a886bf 补上音频交互测试工具的前置步骤
digital-human 的说明里要求先装 wakeword 依赖再启动,README 里原来只写了启动命令,照着做会缺依赖。五个语言版的用法都补上这一步。
2026-10-26 18:46:40 +08:00
hrz
3ff080bb0d 补上阿里百炼和 LM Studio 并统一越南语品牌写法
ASR 那行中文只写阿里云,配置里阿里系有三条,另外四份也按各自写法补上百炼。LM Studio 走的是 openai 接口,仓里没有独立的供应器,所以并进 openai 那一行,免费平台那列不动。越南语版三处 iFlytek 统一成官方写法 iFLYTEK。
2026-10-26 18:46:37 +08:00
hrz
ca8ff121d4
按代码实际情况修正五份 README 的平台清单和说明 (#3489)
* 修正 README 里过时的平台清单和漏掉的供应器

删掉服务端已经不存在的 GizwitsTTS、ACGNTTS、灵犀流式TTS,补上漏写的 CustomTTS、GroqASR、Qwen3ASRFlash 等。声纹一栏改成真正的 voiceprint-api 服务。管理后台的界面语种、插件的加载时机、部署表里的配置要求、音频测试工具的前置步骤,都按代码里的实际情况改写。

* 改掉性能测试脚本里写错的文档路径

脚本启动时提示的 doc/performance_testerer.md 找不到,真实文件是 docs/performance_tester.md。

* 把离线模型补进免费平台列并撤掉音频工具那处改动

两个离线模型走的是本机,不消耗付费接口,和列里已有的本地模型一样,所以补进免费平台列。音频交互测试工具要装 wakeword 依赖这一条,和另一处改同一张表的改动挨着,两边同时开必冲突,先从这次改动里拿掉,等那边合上再单独提。
2026-10-26 18:37:15 +08:00
hrz
9f63b255fb
修好四个语言版 README 里的图片路径 (#3488)
这四个文件在 docs/readme 目录下,图片却写成 docs/images/demoN.png,浏览器按 docs/readme 去找,全是 404。改成 ../images/demoN.png,跟西语版和其他图片的写法一致。四个文件各 15 处,只动路径,别的没碰。
2026-10-26 18:36:39 +08:00
hrz
9d34360a2c
把 README 里核心模块那一行改成不写数量 (#3487)
* 把 README 里核心模块的数量改成四个

模型响应测试工具那一行列了 ASR、LLM、VLLM、TTS 四个模块,却写着三个核心模块。中文源文和 en、de、pt_BR、vi 四个语言版统一改成四个,每份只动表示数量的那个词。

* 把核心模块那一行改成不写数量

先改成四个之后发现还是会错:performance_tester 目录下实际有六个脚本,脚本数还会随供应器增加,写死数量早晚再错一次。最终去掉数量词,改成「等核心模块」,五个语言版同步。
2026-10-26 18:35:27 +08:00
hrz
2f18e2ee0a
Merge pull request #3486 from beeman/beeman/translate-readme
Add Spanish translation of README
2026-10-26 18:34:51 +08:00
hrz
fd05dd5159
把西语 README 里核心模块的数量改成四个
模型响应测试工具那一行列了 ASR、LLM、VLLM、TTS 四个模块,却写着三个核心模块,这里改成四个。只动表示数量的那个词,句子的其余部分不动。
2026-10-26 17:38:20 +08:00
Sakura-RanChen
82d2acc78c - audio_to_data 缓存键加入文件 mtime:regen 覆写 wav 后旧缓存自动失效,
并在 regen 后预编码新文件,唤醒回复不再播旧音频且延迟收益保留
- enhanced_prompt 缓存键补上 emoji_enabled 与 prompt 哈希:
  同设备不同客户端(ESP32/digital-human)不再互相污染,改配置即时生效
- 删除 initialize 响应后的 tools/list 兜底补发:id=2 同连接复用
  违反 JSON-RPC 与设备端严格递增约定(#3461/#3485),且兜不住任何场景
2026-10-26 17:09:09 +08:00
Sakura-RanChen
77be288c8e Merge branch 'perf/hello-handshake-fast' of https://github.com/xinnan-tech/xiaozhi-esp32-server into perf/hello-handshake-fast
# Conflicts:
#	main/xiaozhi-server/requirements.txt
2026-10-26 17:04:54 +08:00
hrz
ba22f5b765
把西语 README 里重复的一句改回中文
上一版把研发团队那一行的中文也译成了西语,于是两行说的是同一件事。仓库里另外四个语言版本都是本地语言一行加中文原句一行,这里改回中文行,跟它们保持一致,也去掉了重复。
2026-10-26 16:45:22 +08:00
hrz
0492dc5924 del:移除测试项 2026-10-26 16:36:46 +08:00
hrz
ffd4ab74d7
修正西语 README 的术语和措辞
按评审意见改掉两处必改:HomeAssistant 不再拆成两个词,警告里的担保对象改回第三方服务商。另外统一了配置方案的说法,补上收费和大模型这两层意思,把 RAG 改成 Rag,漏译的那行中文也译了。只动这一个文件。
2026-10-26 16:26:44 +08:00
wengzh
f0ebebfa85
Merge pull request #3485 from xinnan-tech/py-test-tool
Py test tool
2026-10-26 15:15:04 +08:00
Bram Borggreve
61136b958b
Add Spanish translation of README
- Created docs/readme/README_es.md with Spanish translation
- Maintains same structure and links as original
- Provides Spanish-speaking users access to project documentation
- Adds an Español badge to the existing READMEs
2026-10-26 02:06:13 -05:00
Sakura-RanChen
ee726f49e6 Merge remote-tracking branch 'origin/main' into perf/hello-handshake-fast
# Conflicts:
#	main/xiaozhi-server/requirements.txt
2026-10-26 15:05:17 +08:00
Sakura-RanChen
05f0da0639 补充接入点工具id调整 2026-10-26 14:40:31 +08:00
shinjiyu
af1982c424
fix: device MCP tools/call 避开握手占用的 JSON-RPC id 1/2 (#3462)
握手阶段写死 id=1 (initialize) / id=2 (tools/list),但 MCPClient.next_id
从 1 起算,导致前两次 tools/call 复用同一连接上的 request id。合规设备端
会拒收并触发服务端 30s 超时(表现为前两次调用失败、第三次起恢复)。

将 next_id 初始值改为 3,与官方协议序列及 #3461 复现一致;同时去掉
mcp_handler 里重复的 MCPClient 定义,改为从 mcp_client 导入。

Fixes #3461

Co-authored-by: shinjiyu <shinjiyu@users.noreply.github.com>
2026-10-26 14:05:40 +08:00
Sakura-RanChen
1120be2f60 增加控制台配置,调整部分逻辑 2026-10-26 11:40:00 +08:00
shinjiyu
9880ce998f
fix: 把已识别说话人附到 MCP 接入点 tools/call (#3443)
声纹接口返回的 speaker_id 此前只换成展示名交给 LLM,接入点转发工具参数时不会带上说话人。识别成功后把 speakerId / speakerName 写入 tools/call 的 params._meta,工具参数保持原样;可用 mcp_forward_speaker 关闭。

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: shinjiyu <shinjiyu@users.noreply.github.com>
2026-10-26 10:04:51 +08:00
hrz
9bd668aebc
Merge pull request #3449 from TXyy2023/codex/issue-3050-preserve-model-type
fix(manager-api): 保存模型时保留供应器登记的类型大小写
2026-10-23 22:17:36 +08:00
hrz
d027432432
Merge pull request #3458 from monsterlag/fix/issue-3064-b736
fix(manager-web): 修复短屏下模型配置知识库入口被裁剪
2026-10-23 21:53:42 +08:00
hrz
3972df6e4e 加固模型配置导航的契约测试
原来的用例只取第一条样式规则,后面谁再补一条同名规则就能把滚动改回去,测试照样是绿的。这次把导航用到的样式选择器逐条列出来核对,外层容器也要求只能有一条规则,这样有人悄悄覆盖时测试会当场报错。
2026-10-23 13:39:19 +00:00
hrz
8f2dda09cf
Bump to 0.9.8 (#3469) 2026-10-23 18:54:05 +08:00
hrz
d4ff9c5c17
修掉通讯录的两处越权(读 + 写),并补上三处空指针 (#3460)
* 读取设备通讯录先验设备归属

登录用户传任意 MAC 就能读到别人设备通讯录里的备注和称呼。归属判断收进一个方法,读取通讯录、改别名、改权限都走它,不属于当前用户的设备一律按查不到处理。

* 通讯录存别名不再空指针

对方设备没登记时取备注会直接崩,整条权限授予请求跟着挂掉。取不到就退回尾号称呼,呼叫时主叫没登记也不再崩,顺手删掉一行调试打印。

* 解绑先验归属,通讯录别名不再落空

解绑接口原来不核对设备归属,谁知道对方的设备 id 就能把那台设备的通讯录清空,设备本身倒是因为带了用户条件没删掉。现在先看归属,不是自己的直接不动。

设备登记了但用户没起名时,别名会落成空,缓存刷新把整条跳过,对方再也呼不过来。改成和呼叫那处一样,两级判空都取不到才退回尾号称呼。顺带加了一条回填,把写进去的空值补上。

呼叫那条测试原来会真发请求也没验到东西,改成桩掉网关直接看发出去的称呼。

* 通讯录空别名兜底,撞名加后缀

缓存拼表之前,空别名先用尾号称呼顶上,不再整条跳过,用户没起名的设备也能被呼到。

昵称在同一个人的通讯录里是索引,两台撞名时后写的会盖掉先写的,按昵称呼会呼错设备。加后缀区分,规则和存表时那套一致。取名靠先后,而查询不带排序,所以先按地址排一遍,同样的数据每次刷新结果一样。

数据库没有排序保证,去重全靠顺序,所以这里先排再拼。迁移脚本不用动,运行时的兜底能管住它没覆盖到的行。

* 通讯录取名两条路径对上了

后缀原来只写进缓存,接口直查库返回原值,同一份数据给的是两个名字。
用户照控制台看到的名字呼叫,命中的不是同一台设备。

把取名抽成一个方法,两边都走一遍。顺带把权限位排到地址前面,
撞名时能呼的那台先拿原名,反过来用户怎么点都只会说没权限。

迁移取末两位时改成跟着小写化,和运行期算出的是同一个称呼。

* 同一个人被拆成两本通讯录,一台设备消失

两条记录的归属地址只差大小写时,会被算成两个人,各拿一个同名,
写进同一本时后者盖掉前者,一台设备就从缓存里消失了。

把归属地址归一抽成一个方法,算称呼、写缓存、查缓存都走它。

* 通讯录接口按最近改过的排前,这个约定有用例钉住

智控台页面是按对方地址把备注合进去的,接口返回顺序它并不关心,
所以现在这么排对界面没有效果。

用例留着是防它被当无用代码删掉,删了会有用例报出来。

* 迁移串到别人的私名,撞车的组改走尾号称呼

通讯录回填名字时,设备表里同一个 MAC 有两行(同一台被两个用户各登记一次),
MySQL 自己挑一行填进去,跟这行属于谁无关。改成只有一台时才取智控台名字,
多台就退回按 MAC 末两位算的称呼。名字照样填上,缓存照样刷新,对方还是呼得到。

补了 12 条在真库上跑的用例,另配一条排查重复 MAC 的语句。

* 去掉走不到的分支和没人用的桩,补上末尾换行

getUser() 取不到 subject 或 principal 时返回的是空对象,不是 null,
user == null 走不到,删掉;用例改成桩空对象,测真正的匿名那条路。
归属判断挪进 service 之后,controller 层四处 SecurityUser 的桩没人用了,删掉。
四个文件末尾少了换行,补上。另加一条用例钉住判重分组的比较规则:
只折叠大小写,不折叠分隔符。

* 移除回填通讯录别名的迁移,运行时已经兜住了

这个迁移是本 PR 带进来的。它要把空别名刷成称呼,可运行时的兜底已经做了一样的事,
而且覆盖得更宽:那边连纯空格、地址为空和不足两位的都管。删掉它,功能不受影响。

删它有两条理由。一是重复。二是它按 MAC 去设备表取名字,
而一个 MAC 在设备表里可能有多行——同一台设备被两个用户各登记一次就能造出来,
这时候取到的是别人给自己设备起的名字。写在这里,是怕后来的人以为这个坑不存在。

* 归属校验撞到重复 MAC 不再报错

库里同一 MAC 可能有两行只差大小写,selectOne 会抛 TooManyResultsException,把读通讯录接口整个带崩。改成 selectList 按 id 取第一条做归属校验,撞行时正常返回,不再报错。
2026-10-23 17:43:05 +08:00
wengzh
3709540efd
Merge pull request #3445 from xinnan-tech/fix/huoshan-double-stream-4-bugs-y15
huoshan_double_stream 修 4 个会话协议与监听竞态 bug
2026-10-23 17:37:05 +08:00
wengzh
333050ae2e
Merge pull request #3464 from xinnan-tech/chore/bump-deps-20261023
chore(deps): 批量升级 15 个依赖,适配 mcp 2.x
2026-10-23 17:05:05 +08:00
Sakura-RanChen
95ce49ffc9 删除 benchmark/ 下 3438~3441 回归验证脚本
四处修复均已验证收敛,脚本不进 CI、裸跑依赖 manager-api,保留仅为仓库噪声;后续若再动 huoshan_double_stream 时以 pytest 覆盖
2026-10-23 17:04:52 +08:00
Sakura-RanChen
be75e7bd39 chore(deps): 批量升级 15 个依赖,适配 mcp 2.x
源 PR: #3426 #3427 #3428 #3429

剔除 4 项:
- edge-tts 7.3.1->7.2.8 是降级
- powermem >=1.1.7 要求 Python>=3.11
- openai 3.29.0 与 powermem 冲突(powermem 要求 openai<3.0.0)
- ruamel.yaml 0.19.1 与 hyperpyyaml 冲突

mcp 2.x 适配: streamablehttp_client 更名为 streamable_http_client,headers/timeout
改由 http_client 承载,产出从 3 元组变 2 元组,ProgressFnT 移到 mcp.shared.dispatcher
2026-10-23 15:15:50 +08:00
hrz
24fbf7eee2
登录 token 12h 静默失效补 silent refresh 接口 #3392 (#3402)
* 登录 token 12h 静默失效补 silent refresh 接口 #3392

方案 A:后端 POST /xiaozhi/user/refresh(anon),旧 token 校验通过后强制覆盖为新 token 字符串,旧 token 在 DB 查不到即失效。前端 httpRequest 在 sendRequest 入口检查 token 剩余有效期,剩 1h 内触发 silent refresh(独立 fly 实例 + 单飞锁),成功后 setToken 替换并自动继续发送当前请求,失败走 clearAuth 跳登录。

* refreshToken 改 CAS 防并发 race + 拆前端副作用 #3392

P1:SysUserTokenDao 新增 refreshTokenCAS,条件 UPDATE(oldToken + 未过期 + userId),受影响 0 行抛 TOKEN_INVALID;refreshToken 改调它,避免读-改-写 race。P2:refreshToken 加 @Transactional;httpRequest.getTokenExpireAt 内的 localStorage.setItem 挪到独立 persistTokenExpireAt,由 shouldRefresh 入口调用。

* getTokenExpireAt 改读 localStorage 与持久化同源 #3392

pr01 三改:原代码 getTokenExpireAt 读 store(state.token 缓存),与 persistTokenExpireAt 写 localStorage 不同源,导致 _localStoredAt 缺失 → NaN → shouldRefresh 永 false → silent refresh 永不触发。修复:getTokenExpireAt 改读 localStorage,persistTokenExpireAt 同步刷 store,保证两端一致。e2e 已验证:注入 expire=1800 token → reload → role-config mount 触发 sendRequest → Network 抓到 POST /user/refresh 200 → localStorage token 被替换为新 12h token(含 _localStoredAt)。

* 应用启动同步 localStorage token 到 store #3392

PR #3402 扩展:守卫放行后首次 API 请求时,vuex state.token 还是 null,httpRequest 读 store 取不到 Authorization 头,会被后端 401 → clearAuth 跳登录。在 main.js 应用启动阶段就把 localStorage 里的 token commit 进 store,避免 race。不动 refresh 链路与其它业务文件。
2026-10-23 09:47:41 +08:00
monsterlag
855a64cbb9 fix(manager-web): keep model navigation scrollable on short screens 2026-10-22 04:06:52 +00:00
hrz
fdf280f84a
模板 GET 入口迁回 AgentTemplateController #3395 (#3401)
* 模板 GET 入口迁回 AgentTemplateController #3395

根因:AgentController 已存在 GET /agent/template/templateList,AgentTemplateController 缺显式 GET,于是路由虽通却跨 controller 暴露模板数据,且职责错位。修复:删 AgentController.templateList,同名 @GetMapping(无 path)落到 AgentTemplateController,权限 normal、orderByAsc sort、复用现有 service.list。验证:spring-boot 启动期无 Ambiguous;/agent/template、/page、/{id} 三路由均被 Shiro 一致拦截,权限/路径正确。

* 补 P2 注释说明 normal 权限反直觉是有意保留 #3395

在 getAgentTemplates 上方加 2 行注释,说明单独 normal 权限是为保持原行为契约(普通用户也能查可用模板),与类级 superAdmin 故意分离;非疏忽。无逻辑变更。

* 去除未使用引用

---------

Co-authored-by: Sakura-RanChen <1908198662@qq.com>
2026-10-22 11:42:48 +08:00
wengzh
498191519c
Merge pull request #3452 from xinnan-tech/py-test-wakeup
Py test wakeup
2026-10-22 11:08:38 +08:00
wengzh
f614489d81
Merge pull request #3454 from xinnan-tech/web-test-json
Web test json
2026-10-20 15:44:16 +08:00
Sakura-RanChen
6f958ee4a6 fix: 新增模型页面dict字段错误解析 2026-10-20 15:34:40 +08:00
TXyy2023
b226ee5430
fix(manager-web): decode stored dictionaries before editing (#3450) 2026-10-20 11:53:02 +08:00
Sakura-RanChen
9c30b5e035 文件直接写入wav,无需经过二次编解码 2026-10-20 10:45:31 +08:00
TXyy2023
d531d04281
fix(tts): handle retained audio files in wakeup cache (#3451) 2026-10-20 10:00:20 +08:00
Sakura-RanChen
d8f8a4a083 - 取消屏障保证:新连接创建前 _cancel_monitor_task 已等旧监听任务完全退出,
旧任务不可能读新连接或误关新连接(check_huoshan_3440 动态断言覆盖)
- mismatch 分支仅保留纯跳过,删除旧会话结束事件的复位遗留,
  activate_session 写入点收敛到会话生命周期(start / matched 结束 / close)
- 删除 _session_start_future 启动确认机制:start_session 发送即返回,
  SessionFailed 由 monitor 记 error 并复位 activate_session,无挂起风险
- 回归脚本同步调整:3438 重写为新行为断言,3440 用屏障断言替换 snapshot 断言
2026-10-19 17:52:25 +08:00
TXyy2023
37d4330224 test(model): verify registered types with MySQL and Redis 2026-10-18 23:13:39 +08:00
TXyy2023
7873984f9f fix(manager-api): preserve registered model type casing 2026-10-18 17:10:47 +08:00
hrz
6840210ea8 check_huoshan_3439 改 FIRST 分支行为断言
原 test 用正则 grep 源码验存在性,pr02 复评指出这样测不到实际调用。
改成起后台线程跑真 tts_text_priority_thread、构造 FIRST 消息入队、
run_coroutine_threadsafe patch 成立即完成的 future,最后断言
reset_stream_state 与 opus_encoder.reset_state 各被调一次。
2026-10-17 07:57:30 +08:00
hrz
0a54124d0d huoshan_double_stream 修 3 处复评反馈
init 漏写 _pending_prefix 字段、start_session 用已弃用的
get_event_loop、finish_session 留着多余的 getattr 兜底。补字段、
换 get_running_loop、去兜底,3 处都修了。
2026-10-17 07:57:26 +08:00
hrz
ddc441bc59 补 huoshan_double_stream 4 bug 复现脚本
四个独立脚本各覆盖一个 issue:start_session 等 future 确认、句尾残留与编码器
冲刷、monitor snapshot 隔离、parser_response 四处协议解析。共享 _huoshan_mock
构造一个绕开父类 init 的假 provider 实例。
2026-10-17 07:39:51 +08:00
hrz
9b7fb3e826 parser_response 四处二进制协议解析修正
serialization_method 错用掩码当移位数恒 0,改成 >>4;message_type 写
== FULL or AUDIO_ONLY_RESPONSE 优先级下恒真,改 in (...);offset 硬编码 4 在
header_size>1 全错位,改成 header_size * 4;SessionCanceled 漏进协议分支被
else 误读,补进统一解析。
2026-10-17 07:39:51 +08:00
hrz
a6cdbf9410 监听任务用 snapshot 隔离跨连接
旧 monitor 循环直接 self.ws.recv(),连接重建后旧任务读新下行;finally 无条件
关 self.ws 误关新连接。改成入口绑 monitor_ws / monitor_task,recv 用 snapshot;
旧 session 事件 continue 不再 reset 当前;finally 判 id 相同才关 ws / 清引用。
2026-10-17 07:39:51 +08:00
hrz
75fd5d8cc3 句尾替换词残留先发 + 会话结束冲刷编码器
旧 finish_session 不发 _pending_prefix 残留,句尾替换词被扣时整段丢;monitor / to_tts
收 SessionFinished 不调 is_end=True 冲刷 opus 编码器,每句固定丢尾。改成
finish_session 开头先发残留,monitor / to_tts 调 is_end=True 冲刷,FIRST 同步重置。
2026-10-17 07:39:51 +08:00
hrz
6fe5630346 TTS 会话等 SessionStarted 确认
旧逻辑 start_session 发完 StartSession 即返回;服务端鉴权失败或 14s 内 26005 时
文本线程继续给死会话发文本,整轮无声。改成末尾 await 一个 future:monitor 读到
SessionStarted set True、读到 SessionFailed set False,超时报错让文本线程感知。
2026-10-17 07:39:50 +08:00
hrz
eb9dc8ca0f
把 pydub 探针绑到当前解释器同目录的完整版 ffmpeg (#3444)
edge_tts 升 7.3.1;edge.py 撤 WSS_URL patch 改默认
(4.36 跑默认 URL 稳定)。util.py 加 PATH 临时注入,
绕开 Mac 上 Trae CN 注入的精简版 ffmpeg/ffprobe,
让 pydub 拿 conda env 完整版。引用计数加锁防多线
程串。
2026-10-15 15:43:39 +08:00
hrz
4ed3197a6f pr02 P2 注释预热和百分位
首段缓冲帧数注释改成说人话版本;唤醒词预热按常见音色列表走并把吞掉的失败改成日志提示;基准脚本百分位改成线性插值与 numpy 一致;requirements 补上基准测试用到的 websocket-client。
2026-10-14 23:19:37 +08:00
hrz
4dd194ef8b pr02 P1 三条全部兜底
device_prompt 缓存跨日不失效导致今天日期/天气被烤死,改成独立 key 并带 5 分钟 ttl;mcp 工具列表在收到初始化响应后补回并发发送,helloHandle 预发万一丢帧时也能兜住;启服脚本去硬编码路径与全机 pkill,改用相对路径与 PID 文件。
2026-10-14 23:19:33 +08:00
hrz
8c41faac8b 握手基准脚本后台取帧贴近真实客户端
原版 recv 在二进制语音帧期间必须按顺序 drain 才能拿到 mcp 文本帧,测出来偏慢。改成后台线程持续把帧按到达时间入队、主循环按队列处理,模拟 digital-human 的异步 onmessage 行为。附 handshake_summary_real.txt 是方案 C 后 10 次跑出的数据。
2026-10-14 23:05:20 +08:00
hrz
597ab5f415 每连接冗余计算与日志降级
提示词模板结果按设备 id 缓存复用、声纹未配置和 mcp 配置文件缺失两条提示从警告降到调试,让每条新连接少跑几百毫秒的模板渲染、少两次同步日志。
2026-10-14 23:05:15 +08:00
hrz
4f1cb98503 hello 握手并发与缓存
唤醒词音频改为带缓存且进程启动时预热、首段流控缓冲帧数从 5 调到 2、hello 阶段并发发出 mcp 工具列表帧让客户端在听到声音前就准备好、删掉 mcp 初始化后的固定 sleep。砍幅 t_hello_to_tools_ready p50 从 4019ms 降到 219ms。
2026-10-14 23:05:12 +08:00
wengzh
27399a2fb6
Merge pull request #3430 from xinnan-tech/py-text-test
Py text test
2026-10-14 14:11:53 +08:00
wengzh
7c43ecfcb5
Merge pull request #3434 from xinnan-tech/py-test-asr
fix: SenseVoice 日语识别结果按词带空格 (#3412)
2026-10-14 11:54:39 +08:00
korexil
0be634c627
fix: SenseVoice 日语识别结果按词带空格 (#3412)
SenseVoice 识别日语时偶尔按词输出空格(如「今日 の こと を 少し 長め に」),
这些空格会原样进入对话历史并交给 LLM。lang_tag_filter 现在去掉两个
中日文字符之间的空格,韩文、英文的词间空格保持不变。
2026-10-14 10:32:56 +08:00
Sakura-RanChen
932962e8d3 补充注释说明,调整测试样例 2026-10-14 10:10:28 +08:00
wengzh
60c2a7ee17
Merge pull request #3431 from xinnan-tech/py-content-text
Py content text
2026-10-13 17:13:42 +08:00
Sakura-RanChen
a01f0aa29b 去除没必要的测试,上游为str不需要防御性增加 2026-10-13 16:54:42 +08:00
korexil
4445aa7510
fix: FunASR 识别结果以 JSON 原样进入对话历史 (#3411)
FunASR 返回 {"content","language","emotion"} 时,startToChat 只在含 speaker
字段时才解包,否则整段 JSON 字符串会作为用户消息交给 LLM 并写入对话历史。
现在没有 speaker 时只取 content。
2026-10-13 16:44:13 +08:00
wengzh
dc86a780a2
Merge pull request #3418 from xinnan-tech/py-test
Py test
2026-10-13 15:47:30 +08:00
Sakura-RanChen
a5e47f2c4e 补充字符,调整字符判断 2026-10-13 15:29:28 +08:00
Sakura-RanChen
2057b99aeb 迁移测试用例,优化相关注释 2026-10-13 14:31:21 +08:00
wengzh
7957817a72
Merge pull request #3425 from xinnan-tech/chore/dependabot-monthly-groups
Dependabot 改月度更新并按用途分组
2026-10-13 11:41:15 +08:00
hrz
a6eeb107f4 fix(deps): 补 dependabot ignore portalocker
requirements.txt 把 portalocker 锁在 3.x,4.x 与 qdrant-client<1.20 的
portalocker<4.0 冲突 (PR #3360)。Dependabot 默认推 4.x 升级会破约束。
依 openrz 评审 P1 在 ignore 列表追加 portalocker 一项。
2026-10-13 11:28:37 +08:00
wengzh
847337cabb
Merge pull request #3419 from xinnan-tech/fix/3391-route-guard-whiteList
fix(router): 路由守卫改 anon 白名单反向匹配
2026-10-13 11:15:15 +08:00
Sakura-RanChen
b8f23ffa66 调整相关代码 2026-10-13 10:40:47 +08:00
lww9029
dc581d7185 fix: 修复登录状态下还能访问白名单路由问题 2026-10-13 10:36:25 +08:00
hrz
741ec299c0
fix(tts): edge-tts 失声改走 msedgeservices (#3420)
* fix(tts): edge-tts 失声改走 msedgeservices

微软 2026-10 起对 legacy 消费者接口返回 403,
edge-tts 7.2.8 仍走 speech.platform.bing.com 走不通。
上游 PR rany2/edge-tts#491 切到 api.msedgeservices.com 修好,
但 7.2.8 仍是 PyPI 最新版本。

仓库在 edge.py 顶部临时把 WSS_URL 顶住,等 7.2.9 出了删掉。

* fix(tts): patch 还要写 communicate.WSS_URL

edge-tts 7.2.8 仍指 legacy bing 接口,10 月起微软 403。
上游 PR #491 已切到 msedgeservices.com,7.2.9 才进 PyPI,先顶住。
上次只改 constants.WSS_URL 不够,communicate 用 from import 是模块局部名,
LEGB 找不到新值。这次同时改 communicate.WSS_URL 才生效。
2026-10-13 09:58:30 +08:00
hrz
505925fb21 Dependabot 改月度更新并按用途分组
原本每周跑一次会刷很多零碎 PR,看着烦。改成每月一次,并把第三方 AI 服务、本地模型、网络栈拆成几组聚一起,每组出一个 PR 就行。被锁住的 torch/numpy/websockets 几个直接忽略掉,免得它推升级 PR 进来。
2026-10-13 09:34:02 +08:00
hrz
4aa63baf75 fix(router): 路由守卫改 anon 白名单反向匹配
业务路由越加越多,原来硬编码的 8 项守卫名单跟不上了,
未登录直接进十来个业务页看到骨架再被踢,体感抖。

守卫改成只对登录、注册、找回密码、根路径这四页放行,其余一律查 token。
顺手把 9 处没人读的 meta.requiresAuth 和 meta.title 死字段删了。
2026-10-12 18:02:36 +08:00
korexil
70ab19d23f
fix: TTS 分句在引号内切开句子 (#3413)
_get_segment_text 会在引号内的标点处切分(如「わぁ!」って、“好!”然后),
把引号拆到两段里,或留下只有「。」的片段。新增 _quote_safe_cut:切分点后的
右引号与句末标点一并带走;位于未闭合引号内或右引号后句子仍在继续时,顺延到
下一个标点。不含引号的文本切分结果不变。
2026-10-12 16:26:40 +08:00
Sakura-RanChen
e5f326285e update: 优化client 生命周期对齐业务请求——重试内连接复用、锁外构造、safe_close 可打断重试 2026-10-12 15:42:51 +08:00
hrz
4576e391bb
fix(ci): 阿里云 PyPI 镜像 metadata 缺失回退官方源 (#3417)
基镜像构建挂了——日志显示 pip 在装 requirements.txt 阶段退出码 1,
罪魁是阿里云 pypi 镜像对 mcp==1.22.0 的元数据文件 404。

装包那行加 --extra-index-url https://pypi.org/simple,
主源没货时自动去官方源捞。
2026-10-12 10:28:35 +08:00
Yanhan Ruan
ef1d24e40d
fix(server): 修复临时事件循环结束后 HTTP 客户端未释放的问题 (#3416) 2026-10-12 10:00:28 +08:00
wengzh
c30c40bf56
Merge pull request #3415 from xinnan-tech/chore/bump-deps-20261010065106-1659
chore(deps): 批量升级 4 个允许的依赖
2026-10-10 15:24:17 +08:00
Sakura-RanChen
199c4ce365 chore(deps): batch bump 允许升级的依赖 2026-10-10 14:53:30 +08:00
hrz
a6cd755cf2
聊天记录弹框底部不再留大量空白 (#3410)
弹框本身和 body 用 !important 撑到视口(body 顶开 size="large" 默认多扣的 56px footer 高度)。body 的高度由 flex: 1 自动撑满,max-height 只用来顶开原来的 950px 上限。
2026-10-09 17:24:39 +08:00
hrz
23d0e64d9d
召回测试弹框与切片弹框样式对齐 (#3409)
召回测试弹框宽度从 900px 调到 1200px 并启用大弹框样式,高度、上下间距与切片弹框保持一致。结果区域改用 flex 填充而不是写死的 400px 高度。
2026-10-09 17:18:06 +08:00
hrz
96c224c4e4
切片和聊天记录弹框统一为大弹框样式 (#3407)
知识库查看切片弹框加 size="large",聊天记录弹框去掉旧样式覆盖并把 body 改成 flex 列布局,底部下载按钮不再绝对定位,两个弹框跟历史版本对齐。
2026-10-09 17:02:49 +08:00
hrz
2b6483662a
召回测试弹框回车不再刷新页面 (#3408)
给 el-form 加阻止默认提交的处理,按回车时不再触发浏览器刷新。
2026-10-09 17:01:52 +08:00
hrz
aef973e6b9
7 处 el-select 加 filterable 支持输入筛选 #3405 (#3406)
主诉:手动添加设备下拉无搜索(FIRMWARE_TYPE 字典 54 项)。统一修同类位置:替换词多选加 collapse-tags;登录/注册/找回密码的区号下拉加 filterable(海外 200+ 项)。无新依赖、纯 element-ui 原生属性。
2026-10-08 15:39:46 +08:00
hrz
7a260ee143
弹框关掉后再点不开以及宽度高度统一收口 (#3388)
* 统一管理后台弹框更舒展

把 CustomDialog 默认宽度从 600 加到 720,正文给到至少 360 的高度,
默认弹框就不再显得局促。参数编辑弹框也跟着加宽。智能体历史版
本那条列表、对比和恢复预览都给到至少 420 的最小高度,避免内容
少时框太矮看起来小气。其他像添加智能体、绑定设备这些原本就合适
的弹框没动。

* 弹框外观统一收口

原本几个弹框长得参差不齐:标题字号、按钮文案、留白高度各管各的。这次把新建智能体、新建设备、改模型、改参数这几个弹框接到同一个底座上,按钮统一成「确定」「取消」,输入框字号高度对齐,遮罩背景加了模糊,弹框太高就内部滚动,四个弹框看起来一个模子

* 修复弹框关掉后再点不开

之前几个弹框改用新底座的时候,关闭那一路少了一段转发:父页面用双向绑定来收弹框关闭的信号,子页面应该再把关闭事件抛上去告诉父页面。这一段被删了,下次再点添加按钮时父页面那边状态没复位,弹框就拉不开来。现在把这段补回去。

* 弹框宽度和高度统一收口

同一批弹框的尺寸还是各管各的:模型配置里改参数那个是跟着窗口大小按比例伸缩,历史提示词的源编辑弹框是 900 像素,参数管理里又是 720 像素,智能体变更详情那个上下还留了一大块空白。这次收到同一个共用底子上:宽度都对齐到 720 像素,弹框默认上下贴齐屏幕边、内容多时中间滚动,变更详情那个高度撑到接近屏幕顶到底。

* 管理后台弹框按大小分类统一外观

管理后台里的弹框按大小分成两类来收口。占整页的大弹框(历史版本、变更详情、模型修改、模型参数修正等)撑满整个浏览器高度,下面不再留白;小弹框(添加智能体、添加设备、知识库、字典、角色模板等)改成对齐屏幕正中,不再顶在屏幕上沿。修改模型那条弹框也加宽到 960,左右留白加大到 40,跟历史版本对齐,看起来更舒展。

* 大弹框上下留白收口到十像素并按三档统一宽度

大弹框上下各留十像素让边框和圆角清晰可见。宽度按用途分三档:表单 960、含代码 1080、表格 80% 加宽度上限。供应器、上下文供应器、音色克隆都改 960;TTS 从 90% 改 80%;角色模板从 1200 改 1080;缓存查看从 70% 改 80%。新增模板的大文本框改成自适应高度。

* 弹框样式与文案收口处理

AddDeviceDialog 确认后关闭弹框;CustomDialog 去掉 :global 与紧邻选择器,合并 el-dialog__body 样式块;删除未使用的 --dialog-form/--dialog-code;AddWisdomBodyDialog 的 cancel/handleClose 委托到同一个实现;多语言文案同步去冒号与双点。

* 弹框遮罩样式移到全局作用域

scoped 块里的 ::v-deep .v-modal 打不到 body 层的遮罩,改在 global.scss 用全局选择器。

* 弹框 wrapper 居中样式移到全局作用域

scoped 块里的 ::v-deep .el-dialog__wrapper 同样打不到 element-ui 自渲染的 wrapper,跟 .v-modal 一起挪到 global.scss。

* 弹框提交状态异常收口

设备激活码错误路径不再卡 loading;Provider 与固件弹框补 loading 兜底。

* 弹框视觉异常收口

首页删除确认弹框 wrapper 居中;历史版本弹框去掉内层多余滚动条。

* 设备 API 链式返回修复

bindDevice 等方法补上 return,让 .fail() 兜底回调能正常注册到请求对象上。

* 设备 API 错误回调参数补全

device.js 六个方法加 failCallback 参数;user.js login 网络重试补 failCallback;AddDeviceDialog 改四参数签名。

* 设备状态 API 失败回调引用修复

getDeviceStatus 的 .fail() 块把函数体内 callback(res) 改成与签名一致的 if (failCallback) failCallback(err),避免业务错误时抛 ReferenceError。
2026-10-07 08:03:25 +08:00
176 changed files with 6899 additions and 1368 deletions

View file

@ -3,4 +3,40 @@ updates:
- package-ecosystem: pip
directory: /main/xiaozhi-server
schedule:
interval: weekly
interval: monthly
open-pull-requests-limit: 5
groups:
ai-services:
patterns:
- "openai*"
- "google-generativeai"
- "dashscope"
- "baidu-aip"
- "cozepy"
- "markitdown"
- "mem0ai"
- "powermem"
ai-models:
patterns:
- "funasr"
- "vosk"
- "silero_vad"
- "opuslib_next"
- "sherpa_onnx"
- "modelscope"
web-stack:
patterns:
- "httpx"
- "aiohttp"
- "aiohttp_cors"
- "requests"
- "pysocks"
everything-else:
patterns:
- "*"
ignore:
- dependency-name: "torch"
- dependency-name: "torchaudio"
- dependency-name: "numpy"
- dependency-name: "portalocker"
- dependency-name: "websockets"

View file

@ -20,24 +20,58 @@ jobs:
python-version: '3.10'
cache: 'pip'
cache-dependency-path: 'main/xiaozhi-server/requirements.txt'
- name: Install system dependencies
run: |
# opuslib_next 是 ctypes 绑定,pip 装上的是纯 Python 包,真正的编解码
# 靠系统里的 libopus.so。runner 上默认没有,import 会失败,音频相关的
# 用例直接报错。正式镜像 Dockerfile-server-base 里也是装 libopus0 的
sudo apt-get update
sudo apt-get install -y --no-install-recommends libopus0
- name: Install dependencies
working-directory: main/xiaozhi-server
run: |
pip install -r requirements.txt
pip install pytest pytest-asyncio freezegun
- name: Run smoke test
- name: Prepare test config
working-directory: main/xiaozhi-server
run: |
if [ -f tests/test_smoke.py ]; then
pytest tests/test_smoke.py -x -q
else
echo "::warning::Slice 2 not done yet — tests/test_smoke.py missing"
exit 0
fi
# config/settings.py 在 import 期就要这个文件,缺了整套用例连收集都过不去。
# data/ 在 .gitignore 里,只能由这一步现造
mkdir -p data
printf '{}\n' > data/.config.yaml
- name: Run tests
working-directory: main/xiaozhi-server
run: |
# Edge TTS 那条要连微软公网,runner 的出口 IP 会被风控挡掉,先排除。
# 根治办法是给它打 live 标记,让 mock 模式下自动不收(另开一条改)
pytest tests/ -v -k "not test_tts_text_to_speak_writes_file"
java:
name: Java (manager-api)
runs-on: ubuntu-latest
# 三个 @SpringBootTest 要真连 MySQL 和 Redis,空库即可,Liquibase 会自己建表
services:
mysql:
image: mysql:8.0
env:
MYSQL_ROOT_PASSWORD: 123456
MYSQL_DATABASE: xiaozhi_esp32_server
ports:
- 3306:3306
options: >-
--health-cmd="mysqladmin ping -h 127.0.0.1 -uroot -p123456"
--health-interval=10s
--health-timeout=5s
--health-retries=20
redis:
image: redis:8.0
ports:
- 6379:6379
options: >-
--health-cmd="redis-cli ping"
--health-interval=10s
--health-timeout=5s
--health-retries=20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
@ -47,7 +81,12 @@ jobs:
cache: 'maven'
- name: Run tests
working-directory: main/manager-api
run: mvn -B -q test -DfailIfNoTests=false
run: mvn -B test -DskipTests=false -DfailIfNoTests=false
- name: Check the integration tests really ran
working-directory: main/manager-api
# 守卫在依赖不齐时会把整类集成测试跳过,这里盯一下它们有没有真跑,
# 免得门禁被悄悄掏空
run: bash scripts/check-integration-tests.sh
web:
name: Vue (manager-web)
@ -63,4 +102,6 @@ jobs:
working-directory: main/manager-web
run: |
npm ci --no-audit --no-fund
npm run test:contract
npm run test:unit
npm run build

View file

@ -29,4 +29,5 @@ COPY main/xiaozhi-server/requirements.txt .
# 安装Python依赖
RUN pip install --no-cache-dir --upgrade pip setuptools wheel && \
pip install --no-cache-dir -r requirements.txt --default-timeout=120 --retries 5
# 阿里云 PyPI 镜像偶有元数据 404,加官方源作 fallback
pip install --no-cache-dir -r requirements.txt --default-timeout=120 --retries 5 --extra-index-url https://pypi.org/simple

View file

@ -22,6 +22,7 @@
<a href="./docs/readme/README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
<a href="./docs/readme/README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
<a href="./docs/readme/README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
<a href="./docs/readme/README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a>
@ -169,12 +170,12 @@ Spearheaded by Professor Siyuan Liu's Team (South China University of Technology
#### 🚀 部署方式选择
| 部署方式 | 特点 | 适用场景 | 部署文档 | 配置要求 | 视频教程 |
|---------|------|---------|---------|---------|---------|
| **最简化安装** | 智能对话、单智能体管理 | 低配置环境,数据存储在配置文件,无需数据库 | [①Docker版](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②源码部署](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 如果使用`FunASR`要2核4G,如果全API,要2核2G | - |
| **全模块安装** | 智能对话、多用户管理、多智能体管理、智控台界面操作 | 完整功能体验,数据存储在数据库 |[①Docker版](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②源码部署](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③源码部署自动更新教程](./docs/dev-ops-integration.md) | 如果使用`FunASR`要4核8G,如果全API,要2核4G| [本地源码启动视频教程](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
| **最简化安装** | 智能对话、单智能体管理 | 低配置环境,数据存储在配置文件,无需数据库 | [①Docker版](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②源码部署](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 本地跑 `FunASR` 较耗内存,全部走 API 时资源占用低 | - |
| **全模块安装** | 智能对话、多用户管理、多智能体管理、智控台界面操作 | 完整功能体验,数据存储在数据库 |[①Docker版](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②源码部署](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③源码部署自动更新教程](./docs/dev-ops-integration.md) | 本地跑 `FunASR` 较耗内存,另需数据库资源,全部走 API 时资源占用低| [本地源码启动视频教程](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
常见问题及相关教程,可参考[这个链接](./docs/FAQ.md)
> 💡 提示:以下是按最新代码部署后的测试平台,有需要可烧录测试,并发为6个,每天会清空数据,
> 💡 提示:以下是按最新代码部署后的测试平台,有需要可烧录测试,并发为6个,每天会清空数据。
```
智控台地址: https://2662r3426b.vicp.fun
@ -202,7 +203,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| VLLM(视觉大模型) | glm-4v-flash(智谱) | 👍qwen3.5-flash(阿里百炼) |
| TTS(语音合成) | EdgeTTS(微软) | 👍HuoshanDoubleStreamTTS(火山流式) |
| Intent(意图识别) | function_call(函数调用) | function_call(函数调用) |
| Memory(记忆功能) | mem_local_short(本地短期记忆) | mem_local_short(本地短期记忆) |
| Memory(记忆功能) | mem_local_short(本地短期记忆) | mem_local_short(本地短期记忆) |
如果您关心各组件的耗时,请查阅[小智各组件性能测试报告](https://github.com/xinnan-tech/xiaozhi-performance-research),可按报告中的测试方法在您的环境中实际测试。
@ -211,8 +212,8 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 工具名称 | 位置 | 使用方法 | 功能说明 |
|:---:|:---|:---:|:---:|
| 音频交互测试工具 | main》digital-human》index.html | 在 `main/digital-human` 执行 `python start.py` 后访问 `http://127.0.0.1:8006/index.html` | 测试音频播放和接收功能,验证Python端音频处理是否正常 |
| 模型响应测试工具 | main》xiaozhi-server》performance_tester.py | 执行 `python performance_tester.py` | 测试ASR(语音识别)、LLM(大模型)、VLLM(视觉模型)、TTS(语音合成)三个核心模块的响应速度 |
| 音频交互测试工具 | main》digital-human》index.html | 在 `main/digital-human` 按其 README 装好依赖后执行 `python start.py`,然后访问 `http://127.0.0.1:8006/index.html` | 测试音频播放和接收功能,验证Python端音频处理是否正常 |
| 模型响应测试工具 | main》xiaozhi-server》performance_tester.py | 执行 `python performance_tester.py` | 测试ASR(语音识别)、LLM(大模型)、VLLM(视觉模型)、TTS(语音合成)等核心模块的响应速度 |
> 💡 提示:测试模型速度时,只会测试配置了密钥的模型。
@ -230,12 +231,12 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 意图识别 | 支持外挂的大模型意图识别、大模型自主函数调用,提供插件化意图处理机制 |
| 记忆系统 | 支持本地短期记忆、mem0ai接口记忆、PowerMem智能记忆,具备记忆总结功能 |
| 知识库 | 支持RAGFlow知识库,让大模型判断需要调度知识库后再回答 |
| 工具调用 | 支持客户端IOT协议、客户MCP协议、服务端MCP协议、MCP接入点协议、自定义工具函数 |
| 工具调用 | 支持客户端IOT协议、客户端MCP协议、服务端MCP协议、MCP接入点协议、自定义工具函数 |
| 指令下发 | 依托MQTT协议,支持从智控台将MCP指令下发到ESP32设备 |
| 管理后台 | 提供Web管理界面,支持用户管理、系统配置和设备管理;界面支持中文简体、中文繁体、英文显示 |
| 测试工具 | 提供性能测试工具、视觉模型测试工具和音频交互测试工具 |
| 管理后台 | 提供Web管理界面,支持用户管理、系统配置和设备管理;界面支持中文简体、中文繁体、英文、德语、越南语、巴西葡萄牙语显示 |
| 测试工具 | 提供模型响应性能测试工具和音频交互测试工具 |
| 部署支持 | 支持Docker部署和本地部署,提供完整的配置文件管理 |
| 插件系统 | 支持功能插件扩展、自定义插件开发和插件热加载 |
| 插件系统 | 支持功能插件扩展、自定义插件开发;新增插件文件在下次设备连接时自动加载,改动已加载插件的代码需重启服务 |
### 正在开发 🚧
@ -255,7 +256,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 使用方式 | 支持平台 | 免费平台 |
|:---:|:---:|:---:|
| openai 接口调用 | 阿里百炼、火山引擎、DeepSeek、智谱、Gemini、科大讯飞 | 智谱、Gemini |
| OpenAI 接口调用 | 阿里百炼、火山引擎、DeepSeek、智谱、Gemini、科大讯飞、LM Studio | 智谱、Gemini |
| ollama 接口调用 | Ollama | - |
| dify 接口调用 | Dify | - |
| fastgpt 接口调用 | Fastgpt | - |
@ -263,7 +264,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| xinference 接口调用 | Xinference | - |
| homeassistant 接口调用 | HomeAssistant | - |
实际上,任何支持 openai 接口调用的 LLM 均可接入使用。
实际上,任何支持 OpenAI 接口调用的 LLM 均可接入使用。
---
@ -271,9 +272,9 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 使用方式 | 支持平台 | 免费平台 |
|:---:|:---:|:---:|
| openai 接口调用 | 阿里百炼、智谱ChatGLMVLLM | 智谱ChatGLMVLLM |
| OpenAI 接口调用 | 阿里百炼、智谱ChatGLMVLLM、科大讯飞 | 智谱ChatGLMVLLM |
实际上,任何支持 openai 接口调用的 VLLM 均可接入使用。
实际上,任何支持 OpenAI 接口调用的 VLLM 均可接入使用。
---
@ -281,8 +282,8 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 使用方式 | 支持平台 | 免费平台 |
|:---:|:---:|:---:|
| 接口调用 | EdgeTTS、科大讯飞、火山引擎、腾讯云、阿里云及百炼、CosyVoiceSiliconflow、TTS302AI、CozeCnTTS、GizwitsTTS、ACGNTTS、OpenAITTS、灵犀流式TTS、MinimaxTTS | 灵犀流式TTS、EdgeTTS、CosyVoiceSiliconflow(部分) |
| 本地服务 | FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3、Index-TTS、PaddleSpeech | Index-TTS、PaddleSpeech、FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3 |
| 接口调用 | EdgeTTS、科大讯飞、火山引擎、腾讯云、阿里云及百炼、CosyVoiceSiliconflow、TTS302AI、CozeCnTTS、CustomTTS、OpenAITTS、MinimaxTTS | EdgeTTS、CosyVoiceSiliconflow(部分) |
| 本地服务 | FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3、IndexStreamTTS、PaddleSpeechTTS | IndexStreamTTS、PaddleSpeechTTS、FishSpeech、GPT_SOVITS_V2、GPT_SOVITS_V3 |
---
@ -298,8 +299,8 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 使用方式 | 支持平台 | 免费平台 |
|:---:|:---:|:---:|
| 本地使用 | FunASR、SherpaASR | FunASR、SherpaASR |
| 接口调用 | FunASRServer、火山引擎、科大讯飞、腾讯云、阿里云、百度云、OpenAI ASR | FunASRServer |
| 本地使用 | FunASR、SherpaASR、SherpaParaformerASR、VoskASR | FunASR、SherpaASR、SherpaParaformerASR、VoskASR |
| 接口调用 | FunASRServer、火山引擎、科大讯飞、腾讯云、阿里云及百炼、百度云、OpenAI ASR、GroqASR、Qwen3ASRFlash | FunASRServer |
---
@ -307,7 +308,9 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 使用方式 | 支持平台 | 免费平台 |
|:---:|:---:|:---:|
| 本地使用 | 3D-Speaker | 3D-Speaker |
| 接口调用 | 声纹识别服务(voiceprint-api) | - |
声纹识别需要单独部署 [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) 服务(基于 3D-Speaker),并依赖 MySQL,详见[声纹识别启用指南](./docs/voiceprint-integration.md)
---
@ -319,6 +322,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| Memory | [powermem](./docs/powermem-integration.md) | 本地总结 | 取决于LLM和DB | OceanBase开源,支持智能检索 |
| Memory | mem_local_short | 本地总结 | 免费 | |
| Memory | nomem | 无记忆模式 | 免费 | |
| Memory | mem_report_only | 仅上报 | 免费 | 只上报聊天记录,不做记忆总结 |
---

View file

@ -2,7 +2,7 @@
![请参考-最简化架构图](../docs/images/deploy1.png)
# 方式一:Docker只运行Server
`0.8.2`版本开始,本项目发行的docker镜像只支持`x86架构`,如果需要在`arm64架构`的CPU上部署,可按照[这个教程](docker-build.md)在本机编译`arm64的镜像`。
本项目发行的docker镜像同时提供`amd64`和`arm64`两种架构,可以直接拉取使用;如需自定义镜像,可按照[这个教程](docker-build.md)在本机编译。
## 1. 安装docker
@ -36,9 +36,9 @@ xiaozhi-server
#### 1.1.3 下载配置文件
你需要下载两个配置文件:`docker-compose.yaml` 和 `config.yaml`。需要从项目仓库下载这两个文件。
你需要下载两个配置文件:`docker-compose.yml` 和 `config.yaml`。需要从项目仓库下载这两个文件。
##### 1.1.3.1 下载 docker-compose.yaml
##### 1.1.3.1 下载 docker-compose.yml
用浏览器打开[这个链接](../main/xiaozhi-server/docker-compose.yml)。
@ -91,25 +91,22 @@ docker logs -f xiaozhi-esp32-server
这时,你就要留意日志信息,可以根据这个教程,判断是否成功了。[跳转到运行状态确认](#运行状态确认)
## 5. 版本升级操作
## 4. 版本升级操作
如果后期想升级版本,可以这么操作
5.1、备份好`data`文件夹中的`.config.yaml`文件,一些关键的配置到时复制到新的`.config.yaml`文件里。
4.1、备份好`data`文件夹中的`.config.yaml`文件,一些关键的配置到时复制到新的`.config.yaml`文件里。
请注意是对关键密钥逐个复制,不要直接覆盖。因为新的`.config.yaml`文件可能有一些新的配置项,旧的`.config.yaml`文件不一定有。
5.2、执行以下命令
4.2、执行以下命令
```
docker stop xiaozhi-esp32-server
docker rm xiaozhi-esp32-server
docker stop xiaozhi-esp32-server-web
docker rm xiaozhi-esp32-server-web
docker rmi ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:server_latest
docker rmi ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest
```
5.3、重新按docker方式部署
4.3、重新按docker方式部署
# 方式二:本地源码只运行Server
@ -213,14 +210,14 @@ prompt: |
请你像一个人一样说话,请勿返回配置xml及其他特殊字符。
selected_module:
LLM: DoubaoLLM
LLM: ChatGLMLLM
LLM:
ChatGLMLLM:
api_key: xxxxxxxxxxxxxxx.xxxxxx
```
建议先将最简单的配置运行起来,然后再去`xiaozhi/config.yaml`阅读配置的使用说明。
建议先将最简单的配置运行起来,然后再去[`../main/xiaozhi-server/config.yaml`](../main/xiaozhi-server/config.yaml)阅读配置的使用说明。
比如你要换更换模型,修改`selected_module`下的配置就行。
## 模型文件
@ -238,11 +235,12 @@ LLM:
如果你能看到,类似以下日志,则是本项目服务启动成功的标志。
```
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-OTA接口是 http://192.168.4.123:8003/xiaozhi/ota/
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-Websocket地址是 ws://192.168.4.123:8000/xiaozhi/v1/
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-=======上面的地址是websocket协议地址,请勿用浏览器访问=======
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-如想测试websocket请启动digital-human模块,打开浏览器交互测试
250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-=======================================================
250427 13:04:20[0.9.8_00000000000000][__main__]-INFO-OTA接口是 http://192.168.4.123:8003/xiaozhi/ota/
250427 13:04:20[0.9.8_00000000000000][__main__]-INFO-视觉分析接口是 http://192.168.4.123:8003/mcp/vision/explain
250427 13:04:20[0.9.8_00000000000000][__main__]-INFO-Websocket地址是 ws://192.168.4.123:8000/xiaozhi/v1/
250427 13:04:20[0.9.8_00000000000000][__main__]-INFO-=======上面的地址是websocket协议地址,请勿用浏览器访问=======
250427 13:04:20[0.9.8_00000000000000][__main__]-INFO-如想测试websocket请启动digital-human模块,打开浏览器交互测试
250427 13:04:20[0.9.8_00000000000000][__main__]-INFO-=============================================================
```
正常来说,如果您是通过源码运行本项目,日志会有你的接口地址信息。

View file

@ -144,5 +144,7 @@
### Q: 我叫他呼叫"张山",但是他老是识别成"张三",怎么办?
- 可以查阅你使用的asr服务的文档,确认是否支持热词识别。
- 如果你用的是`FunASRServer`,可以在容器里的`热词文件`里添加"张山",然后重启容器。
- 如果你用的是`火山引擎`的服务,可以在`火山引擎的控制台`里添加`热词文件`,然后回到智控台的`模型配置页面`,把`热词文件名称`配置在`火山引擎的tts`上去。
- 如果你用的是`火山引擎`的服务,可以在`火山引擎的控制台`里添加`热词文件`,然后回到智控台的`模型配置`页面,在`语音识别`里找到模型名称为`豆包语音识别(流式)`的那一条,点`修改`,弹窗里的`供应器`是`火山引擎语音识别(流式)`,在弹窗的`调用信息`区域把`热词文件名称`填到对应的输入框,点`确认保存`。
- `豆包语音识别2.0(流式)`(供应器是`火山引擎语音识别(流式)`)和`豆包语音识别`(供应器是`火山引擎语音识别`)这两条也都有`热词文件名称`这个字段,用法一样,配置时注意别选错行。
- 改完要让设备重新连接才会生效:设备连上时才会把最新的私有配置拉下来,一直连着的设备不会自动变。

View file

@ -50,10 +50,11 @@ paddlespeech tts --input "你好,这是一次测试"
### 7.修改tts_online_application.yaml配置
参考目录 ```"PaddleSpeech\demos\streaming_tts_server\conf\tts_online_application.yaml"```
Linux / WSL 2 用正斜杠写法:```"PaddleSpeech/demos/streaming_tts_server/conf/tts_online_application.yaml"```
选择```tts_online_application.yaml```文件用编辑器打开,设置```protocol```为```websocket```
### 8.启动服务
```yaml
```bash
paddlespeech_server start --config_file ./demos/streaming_tts_server/conf/tts_online_application.yaml
#官方默认启动命令:
paddlespeech_server start --config_file ./conf/tts_online_application.yaml
@ -68,10 +69,19 @@ INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8092 (Press CTRL+C to quit)
```
## 三、修改小智的配置文件
### 1.```main/xiaozhi-server/core/providers/tts/paddle_speech.py```
## 三、配置小智服务
### 1. 无需修改代码(provider 已内置于 main/xiaozhi-server/core/providers/tts/paddle_speech.py)
### 2.新建 `main/xiaozhi-server/data/.config.yaml`
`main/xiaozhi-server/data/` 目录不在仓库里,是被 `.gitignore` 忽略掉的,所以第一次用要先把它建出来,再在里面新建 `.config.yaml` 文件(在仓库根目录执行,上面的 `cd PaddleSpeech` 之后当前目录还停在 PaddleSpeech 源码目录里):
```bash
mkdir -p main/xiaozhi-server/data
```
这个文件是必需的,少了它小智服务起不来,会直接报错退出。
### 2.```main/xiaozhi-server/data/.config.yaml```
使用单模块部署
```yaml
selected_module:
@ -79,19 +89,41 @@ selected_module:
TTS:
PaddleSpeechTTS:
type: paddle_speech
protocol: websocket
protocol: websocket # 当前仅支持 websocket
url: ws://127.0.0.1:8092/paddlespeech/tts/streaming # TTS 服务的 URL 地址,指向本地服务器 [websocket默认ws://127.0.0.1:8092/paddlespeech/tts/streaming]
spk_id: 0 # 发音人 ID,0 通常表示默认的发音人
sample_rate: 24000 # 采样率 [websocket默认24000,http默认0 自动选择]
speed: 1.0 # 语速,1.0 表示正常语速,>1 表示加快,<1 表示减慢
volume: 1.0 # 音量,1.0 表示正常音量,>1 表示增大,<1 表示减小
save_path: # 保存路径
```
采样率固定 24000,provider 内部写死,配置里不用写这一项。
### 3.启动xiaozhi服务
```py
小智服务用**另一个** Python 环境,不要用前面给 PaddleSpeech 建的 `paddle_env` —— 那个环境里装的是 PaddleSpeech 自己那套依赖,版本由它决定,跟本项目锁定的版本不一定一致(`paddlespeech` 对 numpy 没写版本上限,装进去的 numpy 未必是本项目要的那个)。本项目推荐的 Python 版本和依赖版本写在 `main/xiaozhi-server/requirements.txt` 里(文件开头写着推荐 python3.10,另外锁了 torch 2.2.2、numpy 1.26.4)。
先建环境、装依赖(在仓库根目录执行):
```bash
conda create -n xiaozhi-esp32-server python=3.10 -y
conda activate xiaozhi-esp32-server
cd main/xiaozhi-server
pip install -r requirements.txt
```
然后在 `main/xiaozhi-server` 目录下启动(目录不能换:provider 是按相对路径 `core/providers/tts/` 找的,见 `core/utils/tts.py:35`):
```bash
# 上一段已经 cd 到 main/xiaozhi-server 了,这段不用再 cd
# 如果是另开的新终端,先 cd main/xiaozhi-server 再执行
python app.py
```
启动`main/digital-human`下的`python start.py`后,打开`http://127.0.0.1:8006/index.html`,测试连接和发送消息时paddlespeech端是否有输出日志
要验证语音合成的实际输出,另开一个终端,在仓库根目录下跑数字人页面(这套代码另有一份依赖清单,在 `main/digital-human/wakeword_runtime/requirements.txt` 里,缺了会报缺包;唤醒词那部分还要 numpy —— `core/detector.py:7` 和 `core/microphone.py:4` 在模块顶层就 import numpy,用上面建的 `xiaozhi-esp32-server` 跑的话 numpy 已经在里面,不会有这个问题):
```bash
cd main/digital-human
python start.py
```
打开`http://127.0.0.1:8006/index.html`,测试连接和发送消息时paddlespeech端是否有输出日志
输出日志参考:
```

View file

@ -1,8 +1,15 @@
# 语音识别、大语言模型、非流式语音合成、流式语音合成、视觉模型的性能测试工具使用指南
# 语音识别、流式语音识别、大语言模型、非流式语音合成、流式语音合成、视觉模型的性能测试工具使用指南
0.先装依赖(在仓库根目录执行)
```
cd main/xiaozhi-server
pip install -r requirements.txt
```
测试脚本要 import `yaml`、`aiohttp`、`tabulate`,少一个都起不来。`tabulate` 不在 requirements.txt 里,是 `edge-tts` 间接带进来的。
1.在main/xiaozhi-server目录下创建data目录
2.在data目录下创建.config.yaml文件
3.在.data/config.yaml中,写入你的语音识别、大语言模型、流式语音合成、视觉模型的参数
3.在data/.config.yaml中,写入你的语音识别、流式语音识别、大语言模型、非流式语音合成、流式语音合成、视觉模型的参数
例如:
```
LLM:
@ -16,12 +23,50 @@ LLM:
api_key: 你的chat-glm web key
TTS:
EdgeTTS:
# 定义TTS API类型
type: edge
voice: zh-CN-XiaoxiaoNeural
VLLM:
ChatGLMVLLM:
# 定义视觉模型API类型
type: openai
# glm-4v-flash 是智谱的视觉模型,需要在智谱平台申请api_key
model_name: glm-4v-flash
url: https://open.bigmodel.cn/api/paas/v4/
api_key: 你的api_key
ASR:
FunASR:
type: fun_local
model_dir: models/SenseVoiceSmall
language: auto
```
4.在main/xiaozhi-server目录下运行performance_tester.py:
```
python performance_tester.py
```
```
## 几点说明
- 脚本第一行提示的 `docs/performance_tester.md` 就是本文档,它在仓库根目录的 `docs/` 下;脚本本身在 `main/xiaozhi-server/` 目录里跑,两处不是一个目录。
- LLM、VLLM、非流式语音合成这三项会把 `config.yaml` 和 `data/.config.yaml` 两份配置合并起来再遍历,所以实际会测**所有配好 api_key 的供应器**,不只是你在 `.config.yaml` 里写的那一个;api_key 还是占位符的会被跳过。
- 非流式的语音识别这一项读配置的方式和别的不一样:它自己扫 `data/` 目录下的 `*.config.yaml`,只取其中的 `ASR` 段,**不会**用 `config.yaml` 里的默认值。想测语音识别,就得把供应器写进 `data/.config.yaml`。
- 流式语音识别读的是合并后的配置,固定测 `DoubaoStreamASR`、`Qwen3ASRFlash`、`XunfeiStreamASR` 这三家。`config.yaml` 里这三项带的 key 是占位符,要在 `data/.config.yaml` 的 `ASR` 段里填上自己的 key 才会测出延迟。
- 视觉模型的配置写在 `data/.config.yaml` 的 `VLLM:` 段里,这段**不能只写一个空键**:写空的话合并后整段是空的,这项测试会直接跳过、什么都不测。
- 流式语音合成一次会跑这些供应器:
| 供应器 | 说明 |
|---|---|
| `AliyunStreamTTS` | 阿里云流式 TTS,无条件调用 |
| `HuoshanDoubleStreamTTS` | 火山引擎流式 TTS,无条件调用 |
| `PaddleSpeechTTS` | PaddleSpeech 流式 TTS,无条件调用 |
| `IndexStreamTTS` | IndexStream 流式 TTS,无条件调用 |
| `LinkeraiTTS` | `config.yaml` 的 TTS 段里没有这个供应器,默认不测、整项跳过;要测得自己在 `.config.yaml` 里补上 |
| `AliBLTTS` | 阿里百炼流式 TTS,默认就会测:判断读的是合并后的配置,`config.yaml` 里本来就带着这一项 |
| `XunFeiTTS` | 讯飞流式 TTS,同上,默认就会测 |
`AliBLTTS` 和 `XunFeiTTS` 这两项默认带的 key 是占位符,不在 `.config.yaml` 里换成自己的 key 就会报失败;想直接跳过,把这两项在 `.config.yaml` 里写成空的(键名下面不填内容)就行。
标了「无条件调用」的这几个(`AliyunStreamTTS`、`HuoshanDoubleStreamTTS`、`PaddleSpeechTTS`、`IndexStreamTTS`),供应器缺失或被清空时,那一项会报错,错误被测试方法内部的异常处理吃掉,这一项被记成失败 —— 结果表里会多出一行失败记录,但不影响其它项。带守卫的那几家(`AliBLTTS`、`XunFeiTTS`、`LinkeraiTTS`)是整项跳过:没配就不报错、结果表里也不会有这一行。

View file

@ -6,7 +6,7 @@
Dieses Projekt basiert auf der Theorie und Technologie der Mensch-Maschine-symbiotischen Intelligenz zur Entwicklung intelligenter Terminal-Hardware- und Software-Systeme<br/>und bietet Backend-Dienste für das Open-Source-Hardware-Projekt
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
Implementiert mit Python, Java und Vue gemäß dem <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">Xiaozhi-Kommunikationsprotokoll</a><br/>
Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Endpunkte und Stimmabdruckerkennung
Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Zugriffspunkte, Stimmabdruckerkennung und Wissensdatenbank
</p>
<p align="center">
@ -22,6 +22,7 @@ Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Endpunkte und Stimmabd
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DBEDFA"></a>
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a>
@ -54,31 +55,31 @@ Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
<td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture>
<img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
<img alt="Das Gefühl der Reaktionsgeschwindigkeit" src="../images/demo9.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
<picture>
<img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
<img alt="Das Geheimnis der Geschwindigkeitsoptimierung" src="../images/demo6.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
<picture>
<img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
<img alt="Xiaozhi-Digitalmensch mit Sprachaktivierung" src="../images/demo8.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
<picture>
<img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
<img alt="Anruf von Gerät zu Gerät" src="../images/demo0.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture>
<img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
<img alt="Komplexes medizinisches Szenario" src="../images/demo1.png" /></picture>
</a>
</td>
</tr>
@ -86,31 +87,31 @@ Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
<td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture>
<img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
<img alt="Musik abspielen, Wetter abfragen und Nachrichten vorlesen" src="../images/demo7.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture>
<img alt="实时打断" src="docs/images/demo10.png" /></picture>
<img alt="Unterbrechung in Echtzeit" src="../images/demo10.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
<picture>
<img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
<img alt="Objekte per Foto erkennen" src="../images/demo12.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture>
<img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
<img alt="Haushaltsgeräte ein- und ausschalten" src="../images/demo5.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture>
<img alt="多指令任务" src="docs/images/demo11.png" /></picture>
<img alt="Aufgaben mit mehreren Befehlen" src="../images/demo11.png" /></picture>
</a>
</td>
</tr>
@ -118,31 +119,31 @@ Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
<td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture>
<img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
<img alt="MCP-Zugriffspunkt" src="../images/demo13.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
<picture>
<img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
<img alt="MQTT-Befehlsübermittlung" src="../images/demo4.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture>
<img alt="声纹识别" src="docs/images/demo14.png" /></picture>
<img alt="Stimmabdruckerkennung" src="../images/demo14.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture>
<img alt="自定义音色" src="docs/images/demo2.png" /></picture>
<img alt="Eigene Stimmfarbe" src="../images/demo2.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
<picture>
<img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
<img alt="Gespräch auf Kantonesisch" src="../images/demo3.png" /></picture>
</a>
</td>
</tr>
@ -167,8 +168,8 @@ Dieses Projekt bietet zwei Bereitstellungsmethoden. Bitte wählen Sie basierend
#### 🚀 Auswahl der Bereitstellungsmethode
| Bereitstellungsmethode | Funktionen | Anwendungsszenarien | Deployment-Dokumente | Konfigurationsanforderungen | Video-Tutorials |
|---------|------|---------|---------|---------|---------|
| **Vereinfachte Installation** | Intelligenter Dialog, Einzel-Agenten-Verwaltung | Umgebungen mit geringer Konfiguration, Daten in Konfigurationsdateien gespeichert, keine Datenbank erforderlich | [①Docker-Version](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Quellcode-Deployment](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 Kerne 4GB bei Verwendung von `FunASR`, 2 Kerne 2GB bei allen APIs | - |
| **Vollständige Modulinstallation** | Intelligenter Dialog, Mehrbenutzerverwaltung, Mehr-Agenten-Verwaltung, Intelligente Steuerkonsole-Bedienung | Vollständige Funktionserfahrung, Daten in Datenbank gespeichert |[①Docker-Version](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Quellcode-Deployment](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Quellcode-Deployment Auto-Update-Tutorial](../dev-ops-integration.md) | 4 Kerne 8GB bei Verwendung von `FunASR`, 2 Kerne 4GB bei allen APIs| [Video-Tutorial für lokalen Quellcode-Start](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
| **Vereinfachte Installation** | Intelligenter Dialog, Einzel-Agenten-Verwaltung | Umgebungen mit geringer Konfiguration, Daten in Konfigurationsdateien gespeichert, keine Datenbank erforderlich | [①Docker-Version](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Quellcode-Deployment](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| Lokales `FunASR` benötigt mehr Arbeitsspeicher; bei durchgängiger API-Nutzung ist der Ressourcenverbrauch gering | - |
| **Vollständige Modulinstallation** | Intelligenter Dialog, Mehrbenutzerverwaltung, Mehr-Agenten-Verwaltung, Intelligente Steuerkonsole-Bedienung | Vollständige Funktionserfahrung, Daten in Datenbank gespeichert |[①Docker-Version](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Quellcode-Deployment](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Quellcode-Deployment Auto-Update-Tutorial](../dev-ops-integration.md) | Lokales `FunASR` benötigt mehr Arbeitsspeicher, zusätzlich werden Datenbankressourcen benötigt; bei durchgängiger API-Nutzung ist der Ressourcenverbrauch gering| [Video-Tutorial für lokalen Quellcode-Start](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
Häufige Fragen und entsprechende Tutorials finden Sie unter [diesem Link](../FAQ.md)
@ -209,15 +210,15 @@ Dieses Projekt bietet die folgenden Testwerkzeuge, um Ihnen bei der Überprüfun
| Werkzeugname | Standort | Verwendungsmethode | Funktionsbeschreibung |
|:---:|:---|:---:|:---:|
| Audio-Interaktionstesttool | main》digital-human》index.html | In `main/digital-human` `python start.py` ausführen und dann `http://127.0.0.1:8006/index.html` öffnen | Testet Audio-Wiedergabe- und Empfangsfunktionen, überprüft, ob die Python-seitige Audioverarbeitung normal ist |
| Modell-Reaktionstesttool | main》xiaozhi-server》performance_tester.py | Ausführen `python performance_tester.py` | Testet die Reaktionsgeschwindigkeit von ASR (Spracherkennung), LLM (großes Modell), VLLM (Vision-Modell), TTS (Sprachsynthese) drei Kernmodulen |
| Audio-Interaktionstesttool | main》digital-human》index.html | In `main/digital-human` zuerst die Abhängigkeiten wie in der README installieren, dann `python start.py` ausführen und `http://127.0.0.1:8006/index.html` öffnen | Testet Audio-Wiedergabe- und Empfangsfunktionen, überprüft, ob die Python-seitige Audioverarbeitung normal ist |
| Modell-Reaktionstesttool | main》xiaozhi-server》performance_tester.py | Ausführen `python performance_tester.py` | Testet die Reaktionsgeschwindigkeit von Kernmodulen wie ASR (Spracherkennung), LLM (großes Modell), VLLM (Vision-Modell), TTS (Sprachsynthese) |
> 💡 Hinweis: Beim Testen der Modellgeschwindigkeit werden nur Modelle mit konfigurierten Schlüsseln getestet.
---
## Funktionsliste ✨
### Implementiert ✅
![请参考-全模块安装架构图](../images/deploy2.png)
![Architekturdiagramm der Installation aller Module](../images/deploy2.png)
| Funktionsmodul | Beschreibung |
|:---:|:---|
| Kernarchitektur | Basierend auf [MQTT+UDP-Gateway](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket und HTTP-Servern, bietet vollständiges Konsolenverwaltungs- und Authentifizierungssystem |
@ -225,15 +226,15 @@ Dieses Projekt bietet die folgenden Testwerkzeuge, um Ihnen bei der Überprüfun
| Stimmabdruckerkennung | Unterstützt Mehrbenutzer-Stimmabdruckregistrierung, -verwaltung und -erkennung, verarbeitet parallel mit ASR, Echtzeit-Sprecheridentitätserkennung und Weitergabe an LLM für personalisierte Antworten |
| Intelligenter Dialog | Unterstützt mehrere LLM (große Sprachmodelle), implementiert intelligenten Dialog |
| Visuelle Wahrnehmung | Unterstützt mehrere VLLM (Vision Large Models), implementiert multimodale Interaktion |
| Absichtserkennung | Unterstützt LLM-Absichtserkennung, Function Call-Funktionsaufruf, bietet plugin-basierten Absichtsverarbeitungsmechanismus |
| Absichtserkennung | Unterstützt externe LLM-Absichtserkennung, autonome Funktionsaufrufe durch große Modelle, bietet plugin-basierten Absichtsverarbeitungsmechanismus |
| Gedächtnissystem | Unterstützt lokales Kurzzeitgedächtnis, mem0ai-Schnittstellengedächtnis, PowerMem intelligentes Gedächtnis, mit Gedächtniszusammenfassungsfunktion |
| Wissensdatenbank | Unterstützt RAGFlow-Wissensdatenbank, ermöglicht großem Modell die Bewertung, ob Wissensdatenbank benötigt wird, bevor geantwortet wird |
| Werkzeugaufruf | Unterstützt Client-IOT-Protokoll, Client-MCP-Protokoll, Server-MCP-Protokoll, MCP-Endpunktprotokoll, benutzerdefinierte Werkzeugfunktionen |
| Werkzeugaufruf | Unterstützt Client-IOT-Protokoll, Client-MCP-Protokoll, Server-MCP-Protokoll, MCP-Zugriffspunktprotokoll, benutzerdefinierte Werkzeugfunktionen |
| Befehlsübermittlung | Basierend auf MQTT-Protokoll, unterstützt die Übermittlung von MCP-Befehlen von der intelligenten Steuerkonsole an ESP32-Geräte |
| Verwaltungs-Backend | Bietet Web-Verwaltungsoberfläche, unterstützt Benutzerverwaltung, Systemkonfiguration und Geräteverwaltung; Oberfläche unterstützt vereinfachtes Chinesisch, traditionelles Chinesisch und englische Anzeige |
| Testwerkzeuge | Bietet Leistungstestwerkzeuge, Vision-Modell-Testwerkzeuge und Audio-Interaktionstestwerkzeuge |
| Verwaltungs-Backend | Bietet Web-Verwaltungsoberfläche, unterstützt Benutzerverwaltung, Systemkonfiguration und Geräteverwaltung; Oberfläche unterstützt vereinfachtes Chinesisch, traditionelles Chinesisch, Englisch, Deutsch, Vietnamesisch und brasilianisches Portugiesisch an |
| Testwerkzeuge | Bietet Leistungstestwerkzeuge für Modellantworten und Audio-Interaktionstestwerkzeuge |
| Deployment-Unterstützung | Unterstützt Docker-Deployment und lokales Deployment, bietet vollständige Konfigurationsdateiverwaltung |
| Plugin-System | Unterstützt funktionale Plugin-Erweiterungen, benutzerdefinierte Plugin-Entwicklung und Plugin-Hot-Loading |
| Plugin-System | Unterstützt funktionale Plugin-Erweiterungen und benutzerdefinierte Plugin-Entwicklung; neu hinzugefügte Plugin-Dateien werden bei der nächsten Geräteverbindung geladen, Änderungen an bereits geladenen Plugins erfordern einen Neustart des Dienstes |
### In Entwicklung 🚧
@ -253,7 +254,7 @@ Xiaozhi ist ein Ökosystem. Wenn Sie dieses Produkt verwenden, können Sie sich
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:|
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Volcano Engine Doubao, DeepSeek, Zhipu ChatGLM, Gemini | Zhipu ChatGLM, Gemini |
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Volcano Engine Doubao, Volcano Engine AI Gateway, DeepSeek, Zhipu ChatGLM, Gemini, iFLYTEK, LM Studio | Zhipu ChatGLM, Gemini |
| Ollama-Schnittstellenaufrufe | Ollama | - |
| Dify-Schnittstellenaufrufe | Dify | - |
| FastGPT-Schnittstellenaufrufe | FastGPT | - |
@ -269,7 +270,7 @@ Tatsächlich kann jedes LLM, das OpenAI-Schnittstellenaufrufe unterstützt, inte
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:|
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, integriert und verwendet werden.
@ -279,8 +280,8 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:|
| Schnittstellenaufrufe | EdgeTTS, Volcano Engine Doubao TTS, Tencent Cloud, Alibaba Cloud TTS, AliYun Stream TTS, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS, Volcano Dual-Stream TTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow (teilweise) |
| Lokale Dienste | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
| Schnittstellenaufrufe | EdgeTTS, iFLYTEK, Volcano Engine Doubao TTS, Volcano Engine AI Gateway TTS, Tencent Cloud, Alibaba Cloud TTS, AliYun Stream TTS, Alibaba Bailian CosyVoice TTS, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS, Volcano Dual-Stream TTS | EdgeTTS, CosyVoiceSiliconflow (teilweise) |
| Lokale Dienste | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
---
@ -296,8 +297,8 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:|
| Lokale Verwendung | FunASR, SherpaASR | FunASR, SherpaASR |
| Schnittstellenaufrufe | DoubaoASR, Doubao Streaming ASR, FunASRServer, TencentASR, AliyunASR, Aliyun Streaming ASR, Baidu ASR, OpenAI ASR | FunASRServer |
| Lokale Verwendung | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
| Schnittstellenaufrufe | DoubaoASR, Doubao Streaming ASR, Doubao Streaming ASR V2, FunASRServer, iFLYTEK, TencentASR, AliyunASR, Aliyun Streaming ASR, Alibaba Bailian Streaming ASR, Baidu ASR, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
---
@ -305,7 +306,9 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:|
| Lokale Verwendung | 3D-Speaker | 3D-Speaker |
| Schnittstellenaufrufe | Voiceprint-Dienst (voiceprint-api) | - |
Die Stimmabdruckerkennung erfordert einen separat bereitgestellten [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api)-Dienst (auf Basis von 3D-Speaker) sowie MySQL. Siehe [Anleitung zur Stimmabdruckerkennung](../voiceprint-integration.md).
---
@ -317,6 +320,7 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
| Memory | [powermem](../powermem-integration.md) | Lokale Zusammenfassung | Abhängig von LLM und DB | OceanBase Open Source, unterstützt intelligente Abfrage |
| Memory | mem_local_short | Lokale Zusammenfassung | Kostenlos | |
| Memory | nomem | Kein Gedächtnismodus | Kostenlos | |
| Memory | mem_report_only | Nur Meldung | Kostenlos | Meldet nur Chat-Verläufe, keine Gedächtniszusammenfassung |
---
@ -351,11 +355,10 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
| <img src="../images/logo_contributors.png" width="160"> | [Code-Mitwirkende](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Dank an [alle Code-Mitwirkenden](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), Ihre Bemühungen haben das Projekt robuster und leistungsfähiger gemacht. |
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
</picture>
</a>

View file

@ -22,6 +22,7 @@ Support for MQTT+UDP protocol, Websocket protocol, MCP access point, voiceprint
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a>
@ -54,31 +55,31 @@ Want to see the usage effects? Click the videos below 🎥
<td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture>
<img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
<img alt="The feel of the response speed" src="../images/demo9.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
<picture>
<img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
<img alt="The secret to speeding things up" src="../images/demo6.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
<picture>
<img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
<img alt="Xiaozhi digital human with voice wake-up" src="../images/demo8.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
<picture>
<img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
<img alt="Device-to-device calling" src="../images/demo0.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture>
<img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
<img alt="A complex medical scenario" src="../images/demo1.png" /></picture>
</a>
</td>
</tr>
@ -86,31 +87,31 @@ Want to see the usage effects? Click the videos below 🎥
<td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture>
<img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
<img alt="Play music, check the weather, and read the news" src="../images/demo7.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture>
<img alt="实时打断" src="docs/images/demo10.png" /></picture>
<img alt="Real-time interruption" src="../images/demo10.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
<picture>
<img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
<img alt="Take a photo to identify objects" src="../images/demo12.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture>
<img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
<img alt="Turn home appliances on and off" src="../images/demo5.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture>
<img alt="多指令任务" src="docs/images/demo11.png" /></picture>
<img alt="Multi-command tasks" src="../images/demo11.png" /></picture>
</a>
</td>
</tr>
@ -118,31 +119,31 @@ Want to see the usage effects? Click the videos below 🎥
<td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture>
<img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
<img alt="MCP access point" src="../images/demo13.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
<picture>
<img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
<img alt="MQTT command delivery" src="../images/demo4.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture>
<img alt="声纹识别" src="docs/images/demo14.png" /></picture>
<img alt="Voiceprint recognition" src="../images/demo14.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture>
<img alt="自定义音色" src="docs/images/demo2.png" /></picture>
<img alt="Custom voice timbre" src="../images/demo2.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
<picture>
<img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
<img alt="Talking in Cantonese" src="../images/demo3.png" /></picture>
</a>
</td>
</tr>
@ -167,8 +168,8 @@ This project provides two deployment methods. Please choose based on your specif
#### 🚀 Deployment Method Selection
| Deployment Method | Features | Applicable Scenarios | Deployment Docs | Configuration Requirements | Video Tutorials |
|---------|------|---------|---------|---------|---------|
| **Simplified Installation** | Intelligent dialogue, single agent management | Low-configuration environments, data stored in config files, no database required | [①Docker Version](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Source Code Deployment](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 cores 4GB if using `FunASR`, 2 cores 2GB if all APIs | - |
| **Full Module Installation** | Intelligent dialogue, multi-user management, multi-agent management, intelligent console interface operation | Complete functionality experience, data stored in database |[①Docker Version](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Source Code Deployment](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Source Code Deployment Auto-Update Tutorial](../dev-ops-integration.md) | 4 cores 8GB if using `FunASR`, 2 cores 4GB if all APIs| [Local Source Code Startup Video Tutorial](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
| **Simplified Installation** | Intelligent dialogue, single agent management | Low-configuration environments, data stored in config files, no database required | [①Docker Version](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Source Code Deployment](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| Local `FunASR` needs more memory; using APIs for everything keeps resource usage low | - |
| **Full Module Installation** | Intelligent dialogue, multi-user management, multi-agent management, intelligent console interface operation | Complete functionality experience, data stored in database |[①Docker Version](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Source Code Deployment](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Source Code Deployment Auto-Update Tutorial](../dev-ops-integration.md) | Local `FunASR` needs more memory plus database resources; using APIs for everything keeps resource usage low| [Local Source Code Startup Video Tutorial](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
For frequently asked questions and related tutorials, please refer to [this link](../FAQ.md)
@ -209,15 +210,15 @@ This project provides the following testing tools to help you verify the system
| Tool Name | Location | Usage Method | Function Description |
|:---:|:---|:---:|:---:|
| Audio Interaction Test Tool | main》digital-human》index.html | Run `python start.py` in `main/digital-human`, then open `http://127.0.0.1:8006/index.html` | Tests audio playback and reception functions, verifies if Python-side audio processing is normal |
| Model Response Test Tool | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Tests response speed of three core modules: ASR(speech recognition), LLM(large model), VLLM(vision model), TTS(speech synthesis) |
| Audio Interaction Test Tool | main》digital-human》index.html | In `main/digital-human`, install dependencies as its README says, then run `python start.py` and open `http://127.0.0.1:8006/index.html` | Tests audio playback and reception functions, verifies if Python-side audio processing is normal |
| Model Response Test Tool | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Tests response speed of core modules such as ASR(speech recognition), LLM(large model), VLLM(vision model), TTS(speech synthesis) |
> 💡 Note: When testing model speed, only models with configured keys will be tested.
---
## Feature List ✨
### Implemented ✅
![请参考-全模块安装架构图](../images/deploy2.png)
![Full-module installation architecture diagram](../images/deploy2.png)
| Feature Module | Description |
|:---:|:---|
| Core Architecture | Based on [MQTT+UDP gateway](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket and HTTP servers, provides complete console management and authentication system |
@ -225,15 +226,15 @@ This project provides the following testing tools to help you verify the system
| Voiceprint Recognition | Supports multi-user voiceprint registration, management, and recognition, processes in parallel with ASR, real-time speaker identity recognition and passes to LLM for personalized responses |
| Intelligent Dialogue | Supports multiple LLM(large language models), implements intelligent dialogue |
| Visual Perception | Supports multiple VLLM(vision large models), implements multimodal interaction |
| Intent Recognition | Supports LLM intent recognition, Function Call function calling, provides plugin-based intent processing mechanism |
| Intent Recognition | Supports pluggable external LLM intent recognition and autonomous LLM function calling, provides plugin-based intent processing mechanism |
| Memory System | Supports local short-term memory, mem0ai interface memory, PowerMem intelligent memory, with memory summarization functionality |
| Knowledge Base | Supports RAGFlow knowledge base, enabling LLM to judge whether to schedule the knowledge base after receiving the user's question, and then answer the question |
| Tool Calling | Supports client IOT protocol, client MCP protocol, server MCP protocol, MCP endpoint protocol, custom tool functions |
| Tool Calling | Supports client IOT protocol, client MCP protocol, server MCP protocol, MCP access point protocol, custom tool functions |
| Command Delivery | Supports MCP command delivery to ESP32 devices via MQTT protocol from Smart Console |
| Management Backend | Provides Web management interface, supports user management, system configuration and device management; Supports Simplified Chinese, Traditional Chinese and English display |
| Testing Tools | Provides performance testing tools, vision model testing tools, and audio interaction testing tools |
| Management Backend | Provides Web management interface, supports user management, system configuration and device management; Supports Simplified Chinese, Traditional Chinese, English, German, Vietnamese and Brazilian Portuguese display |
| Testing Tools | Provides model response performance testing tools and audio interaction testing tools |
| Deployment Support | Supports Docker deployment and local deployment, provides complete configuration file management |
| Plugin System | Supports functional plugin extensions, custom plugin development, and plugin hot-loading |
| Plugin System | Supports functional plugin extensions and custom plugin development; newly added plugin files are loaded on the next device connection, code changes to already loaded plugins require a service restart |
### Under Development 🚧
@ -253,7 +254,7 @@ Xiaozhi is an ecosystem. When using this product, you can also check out other [
| Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:|
| OpenAI interface calls | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK | Zhipu, Gemini |
| OpenAI interface calls | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini |
| Ollama interface calls | Ollama | - |
| Dify interface calls | Dify | - |
| FastGPT interface calls | FastGPT | - |
@ -269,7 +270,7 @@ In fact, any LLM that supports OpenAI interface calls can be integrated and used
| Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:|
| OpenAI interface calls | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
| OpenAI interface calls | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
In fact, any VLLM that supports OpenAI interface calls can be integrated and used.
@ -279,8 +280,8 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
| Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:|
| Interface calls | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud and Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow(partial) |
| Local services | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
| Interface calls | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud and Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow(partial) |
| Local services | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
---
@ -296,8 +297,8 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
| Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:|
| Local use | FunASR, SherpaASR | FunASR, SherpaASR |
| Interface calls | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
| Local use | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
| Interface calls | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud and Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
---
@ -305,7 +306,9 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
| Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:|
| Local use | 3D-Speaker | 3D-Speaker |
| Interface calls | Voiceprint service (voiceprint-api) | - |
Voiceprint recognition requires a separately deployed [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) service (based on 3D-Speaker) and MySQL. See the [voiceprint integration guide](../voiceprint-integration.md).
---
@ -317,6 +320,7 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
| Memory | [powermem](../powermem-integration.md) | Local summarization | Depends on LLM and DB | OceanBase open source, supports intelligent retrieval |
| Memory | mem_local_short | Local summarization | Free | |
| Memory | nomem | No memory mode | Free | |
| Memory | mem_report_only | Report only | Free | Only reports chat records, no memory summarization |
---
@ -351,11 +355,10 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
| <img src="../images/logo_contributors.png" width="160"> | [Code Contributors](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Thanks to [all code contributors](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), your efforts have made the project more robust and powerful. |
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
</picture>
</a>

364
docs/readme/README_es.md Normal file
View file

@ -0,0 +1,364 @@
[![Banners](../images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server)
<h1 align="center">Servicio backend Xiaozhi xiaozhi-esp32-server</h1>
<p align="center">
Este proyecto desarrolla sistemas de hardware y software para terminales inteligentes a partir de la teoría y la tecnología de la inteligencia simbiótica humano-máquina<br/>y ofrece el servicio backend del proyecto de hardware inteligente de código abierto
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
Implementado en Python, Java y Vue según el <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">protocolo de comunicación Xiaozhi</a><br/>
Compatible con el protocolo MQTT+UDP, el protocolo WebSocket, puntos de acceso MCP, reconocimiento de huella de voz y bases de conocimiento
</p>
<p align="center">
<a href="../FAQ.md">Preguntas frecuentes</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">Informar de problemas</a>
· <a href="../../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3">Documentación de despliegue</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">Notas de la versión</a>
</p>
<p align="center">
<a href="../../README.md"><img alt="简体中文版自述文件" src="https://img.shields.io/badge/简体中文-DFE0E5"></a>
<a href="./README_en.md"><img alt="README in English" src="https://img.shields.io/badge/English-DFE0E5"></a>
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DBEDFA"></a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/LICENSE">
<img alt="GitHub pull requests" src="https://img.shields.io/badge/license-MIT-white?labelColor=black" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server">
<img alt="stars" src="https://img.shields.io/github/stars/xinnan-tech/xiaozhi-esp32-server?color=ffcb47&labelColor=black" />
</a>
</p>
<p align="center">
Liderado por el equipo del profesor Siyuan Liu (Universidad Tecnológica del Sur de China)
</br>
刘思源教授团队主导研发(华南理工大学)
</br>
<img src="../images/hnlg.jpg" alt="Universidad Tecnológica del Sur de China (华南理工大学)" width="50%">
</p>
---
## A quién va dirigido 👥
Este proyecto debe usarse junto con hardware ESP32. Si ya ha comprado hardware relacionado con ESP32, se ha conectado con éxito al servicio backend desplegado por Brother Xia (虾哥) y quiere montar por su cuenta su propio servicio backend `xiaozhi-esp32`, este proyecto encaja con lo que busca.
¿Quiere ver cómo se usa? Pulse los vídeos 🎥
<table>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture>
<img alt="Sensación de la velocidad de respuesta" src="../images/demo9.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
<picture>
<img alt="El secreto para optimizar la velocidad" src="../images/demo6.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
<picture>
<img alt="Humano digital Xiaozhi con activación por voz" src="../images/demo8.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
<picture>
<img alt="Llamadas de dispositivo a dispositivo" src="../images/demo0.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture>
<img alt="Escenario médico complejo" src="../images/demo1.png" /></picture>
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture>
<img alt="Reproducir música, consultar el tiempo y leer noticias" src="../images/demo7.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture>
<img alt="Interrupción en tiempo real" src="../images/demo10.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
<picture>
<img alt="Reconocer objetos con una foto" src="../images/demo12.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture>
<img alt="Controlar el encendido de electrodomésticos" src="../images/demo5.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture>
<img alt="Tareas con varias instrucciones" src="../images/demo11.png" /></picture>
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture>
<img alt="Punto de acceso MCP" src="../images/demo13.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
<picture>
<img alt="Envío de instrucciones MQTT" src="../images/demo4.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture>
<img alt="Reconocimiento de huella de voz" src="../images/demo14.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture>
<img alt="Tono de voz personalizado" src="../images/demo2.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
<picture>
<img alt="Conversación en cantonés" src="../images/demo3.png" /></picture>
</a>
</td>
</tr>
</table>
---
## Advertencias ⚠️
1. Este proyecto es software de código abierto. Este software no mantiene relación comercial alguna con los proveedores de API de terceros a los que se conecta (incluidos, entre otros, plataformas de reconocimiento de voz, modelos de lenguaje y síntesis de voz), y no ofrece ninguna garantía sobre la calidad del servicio de dichos proveedores ni sobre la seguridad de sus fondos. Se recomienda elegir de forma preferente proveedores que cuenten con las licencias de actividad correspondientes y leer con atención sus condiciones de servicio y su política de privacidad. Este software no custodia ninguna clave de cuenta, no interviene en el movimiento de fondos y no asume el riesgo de pérdida del saldo recargado.
2. Las funciones de este proyecto no están completas y no ha superado una evaluación de seguridad de red. No lo utilice en entornos de producción. Si despliega este proyecto en una red pública con fines de aprendizaje, aplique las protecciones necesarias.
---
## Documentación de despliegue
![Banners](../images/banner2.png)
Este proyecto ofrece dos formas de despliegue. Elija según lo que necesite:
#### 🚀 Elección del método de despliegue
| Método de despliegue | Características | Escenarios | Documentación de despliegue | Requisitos | Tutoriales en vídeo |
|---------|------|---------|---------|---------|---------|
| **Instalación simplificada** | Diálogo inteligente, gestión de un solo agente | Entornos con pocos recursos; los datos se guardan en archivos de configuración y no hace falta base de datos | [①Versión Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Despliegue desde el código fuente](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| Ejecutar `FunASR` en local consume bastante memoria; si todo va por API, el consumo de recursos es bajo | - |
| **Instalación de todos los módulos** | Diálogo inteligente, gestión multiusuario, gestión de varios agentes, uso de la interfaz de la consola inteligente | Experiencia con todas las funciones; los datos se guardan en una base de datos |[①Versión Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Despliegue desde el código fuente](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Tutorial de actualización automática desde el código fuente](../dev-ops-integration.md) | Ejecutar `FunASR` en local consume bastante memoria, y además requiere recursos de base de datos; si todo va por API, el consumo de recursos es bajo | [Tutorial en vídeo para arrancar el código fuente en local](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
Las preguntas frecuentes y los tutoriales relacionados están en [este enlace](../FAQ.md)
> 💡 Nota: a continuación hay una plataforma de prueba desplegada con el código más reciente. Si lo necesita, puede grabar el firmware y probarla. La concurrencia es de 6 usuarios y los datos se borran cada día.
```
Dirección de la consola inteligente: https://2662r3426b.vicp.fun
Consola inteligente (versión H5): https://2662r3426b.vicp.fun/h5/index.html
Herramienta de prueba del servicio: https://2662r3426b.vicp.fun/test/
Dirección de la interfaz OTA: https://2662r3426b.vicp.fun/xiaozhi/ota/
Dirección de la interfaz WebSocket: wss://2662r3426b.vicp.fun/xiaozhi/v1/
```
#### 🚩 Descripción y recomendaciones de configuración
> [!Note]
> Este proyecto ofrece dos esquemas de configuración:
>
> 1. `Configuración básica y totalmente gratuita`: adecuada para uso personal y doméstico. Todos los componentes usan opciones gratuitas y no hay que pagar nada más.
>
> 2. `Configuración en streaming`: adecuada para demostraciones, formación y escenarios con más de 2 usuarios concurrentes. Usa procesamiento en streaming, responde antes y se siente mejor.
>
> Desde la versión `0.5.2`, el proyecto admite la configuración en streaming. Frente a las versiones anteriores, el tiempo de respuesta mejora unos `2,5 segundos` y la experiencia de uso mejora de forma notable.
| Módulo | Configuración básica y totalmente gratuita | Configuración en streaming |
|:---:|:---:|:---:|
| ASR (reconocimiento de voz) | FunASR (local) | 👍XunfeiStreamASR (iFLYTEK en streaming) |
| LLM (modelo de lenguaje) | glm-4-flash (Zhipu) | 👍qwen-flash (Alibaba Bailian) |
| VLLM (modelo de visión) | glm-4v-flash (Zhipu) | 👍qwen3.5-flash (Alibaba Bailian) |
| TTS (síntesis de voz) | EdgeTTS (Microsoft) | 👍HuoshanDoubleStreamTTS (Volcano en streaming) |
| Intent (reconocimiento de intención) | function_call (llamada a funciones) | function_call (llamada a funciones) |
| Memory (memoria) | mem_local_short (memoria local a corto plazo) | mem_local_short (memoria local a corto plazo) |
Si le importa el tiempo que tarda cada componente, consulte el [informe de rendimiento de los componentes de Xiaozhi](https://github.com/xinnan-tech/xiaozhi-performance-research) y pruebe en su propio entorno con el método que describe el informe.
#### 🔧 Herramientas de prueba
Este proyecto incluye las siguientes herramientas para comprobar el sistema y elegir un modelo adecuado:
| Herramienta | Ubicación | Uso | Qué hace |
|:---:|:---|:---:|:---:|
| Prueba de interacción de audio | main》digital-human》index.html | En `main/digital-human`, instale las dependencias como indica su README, después ejecute `python start.py` y abra `http://127.0.0.1:8006/index.html` | Prueba la reproducción y la recepción de audio, y comprueba que el procesamiento de audio en Python funciona |
| Prueba de respuesta de los modelos | main》xiaozhi-server》performance_tester.py | Ejecute `python performance_tester.py` | Mide la velocidad de respuesta de los principales módulos: ASR (reconocimiento de voz), LLM (modelo de lenguaje), VLLM (modelo de visión) y TTS (síntesis de voz) |
> 💡 Nota: al medir la velocidad de los modelos, solo se prueban los modelos que tienen una clave configurada.
---
## Lista de funciones ✨
### Implementado ✅
![Diagrama de arquitectura de la instalación de todos los módulos](../images/deploy2.png)
| Módulo | Descripción |
|:---:|:---|
| Arquitectura principal | Basada en la [pasarela MQTT+UDP](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md) y en servidores WebSocket y HTTP; ofrece un sistema completo de gestión de consola y de autenticación |
| Interacción por voz | Admite ASR en streaming (reconocimiento de voz), TTS en streaming (síntesis de voz) y VAD (detección de actividad de voz), además de reconocimiento multilingüe y procesamiento de voz |
| Huella de voz | Admite el registro, la gestión y el reconocimiento de la huella de voz de varios usuarios; se procesa en paralelo con el ASR, identifica en tiempo real quién habla y se lo pasa al LLM para una respuesta personalizada |
| Diálogo inteligente | Admite varios LLM (modelos de lenguaje) para mantener un diálogo inteligente |
| Percepción visual | Admite varios VLLM (modelos de visión) para una interacción multimodal |
| Reconocimiento de intención | Admite el reconocimiento de intención con un modelo de lenguaje (LLM) externo y conectable, y la llamada autónoma a funciones del modelo, y ofrece un mecanismo de procesamiento de intenciones mediante plugins |
| Sistema de memoria | Admite memoria local a corto plazo, memoria por la interfaz mem0ai y memoria inteligente PowerMem, con resumen de la memoria |
| Base de conocimiento | Admite la base de conocimiento RAGFlow, para que el modelo decida si debe consultarla antes de responder |
| Llamada a herramientas | Admite el protocolo IOT del cliente, el protocolo MCP del cliente, el protocolo MCP del servidor, el protocolo de punto de acceso MCP y funciones de herramientas personalizadas |
| Envío de instrucciones | Apoyado en el protocolo MQTT, permite enviar instrucciones MCP desde la consola inteligente a los dispositivos ESP32 |
| Backend de administración | Ofrece una interfaz web de administración, con gestión de usuarios, configuración del sistema y gestión de dispositivos. La interfaz se muestra en chino simplificado, chino tradicional, inglés, alemán, vietnamita y portugués de Brasil |
| Herramientas de prueba | Incluye herramientas de prueba de rendimiento y de interacción de audio |
| Soporte de despliegue | Admite el despliegue con Docker y el despliegue local, y ofrece una gestión completa de los archivos de configuración |
| Sistema de plugins | Admite extensiones de plugins funcionales y el desarrollo de plugins propios; los nuevos archivos de plugin se cargan automáticamente en la siguiente conexión del dispositivo, y los cambios en el código de un plugin ya cargado requieren reiniciar el servicio |
### En desarrollo 🚧
Para ver el avance concreto del plan de desarrollo, [pulse aquí](https://github.com/users/xinnan-tech/projects/3). Las preguntas frecuentes y los tutoriales relacionados están en [este enlace](../FAQ.md)
Si desarrolla software, aquí tiene una [carta abierta a quienes desarrollan](../contributor_open_letter.md). La invitación está hecha.
---
## Ecosistema del producto 👬
Xiaozhi es un ecosistema. Al usar este producto, también puede ver otros [proyectos destacados](https://github.com/78/xiaozhi-esp32/blob/main/README_zh.md#%E7%9B%B8%E5%85%B3%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE) de este ecosistema
---
## Plataformas y componentes compatibles 📋
### LLM, modelos de lenguaje
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|:---:|:---:|:---:|
| Llamadas por la interfaz OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini |
| Llamadas por la interfaz Ollama | Ollama | - |
| Llamadas por la interfaz Dify | Dify | - |
| Llamadas por la interfaz FastGPT | FastGPT | - |
| Llamadas por la interfaz Coze | Coze | - |
| Llamadas por la interfaz Xinference | Xinference | - |
| Llamadas por la interfaz HomeAssistant | HomeAssistant | - |
En la práctica, se puede integrar cualquier LLM que admita llamadas por la interfaz OpenAI.
---
### VLLM, modelos de visión
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|:---:|:---:|:---:|
| Llamadas por la interfaz OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
En la práctica, se puede integrar cualquier VLLM que admita llamadas por la interfaz OpenAI.
---
### TTS, síntesis de voz
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|:---:|:---:|:---:|
| Llamadas por interfaz | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud y Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow (parcial) |
| Servicio local | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
---
### VAD, detección de actividad de voz
| Tipo | Plataforma | Forma de uso | Precio | Notas |
|:---:|:---------:|:----:|:----:|:--:|
| VAD | SileroVAD | Uso local | Gratuito | |
---
### ASR, reconocimiento de voz
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|:---:|:---:|:---:|
| Uso local | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
| Llamadas por interfaz | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud y Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
---
### Voiceprint, huella de voz
| Forma de uso | Plataformas compatibles | Plataformas gratuitas |
|:---:|:---:|:---:|
| Llamadas por interfaz | Servicio de reconocimiento de huella de voz (voiceprint-api) | - |
El reconocimiento de huella de voz requiere desplegar por separado el servicio [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) (basado en 3D-Speaker), que depende de MySQL; consulte la [guía de integración de la huella de voz](../voiceprint-integration.md)
---
### Memory, almacenamiento de memoria
| Tipo | Plataforma | Forma de uso | Precio | Notas |
|:------:|:---------------:|:----:|:---------:|:--:|
| Memory | mem0ai | Llamadas por interfaz | Cuota de 1000 veces al mes | |
| Memory | [powermem](../powermem-integration.md) | Resumen local | Depende del LLM y de la base de datos | OceanBase de código abierto; admite búsqueda inteligente |
| Memory | mem_local_short | Resumen local | Gratuito | |
| Memory | nomem | Modo sin memoria | Gratuito | |
| Memory | mem_report_only | Solo informe | Gratuito | Solo informa el historial de chat, sin resumen de memoria |
---
### Intent, reconocimiento de intención
| Tipo | Plataforma | Forma de uso | Precio | Notas |
|:------:|:-------------:|:----:|:-------:|:---------------------:|
| Intent | intent_llm | Llamadas por interfaz | Según el precio del LLM | Reconoce la intención mediante el modelo de lenguaje (LLM); gran capacidad de generalización |
| Intent | function_call | Llamadas por interfaz | Según el precio del LLM | Completa la intención con llamadas a funciones del modelo; rápido y con buen resultado |
| Intent | nointent | Modo sin intención | Gratuito | No reconoce la intención y devuelve directamente el resultado del diálogo |
---
### Rag, generación aumentada por recuperación
| Tipo | Plataforma | Forma de uso | Precio | Notas |
|:------:|:-------------:|:----:|:-------:|:---------------------:|
| Rag | ragflow | Llamadas por interfaz | Cobrado según los tokens consumidos en el troceado y la segmentación | Usa la generación aumentada por recuperación de RagFlow para dar respuestas más precisas |
---
## Agradecimientos 🙏
| Logo | Proyecto o empresa | Descripción |
|:---:|:---:|:---|
| <img src="../images/logo_bailing.png" width="160"> | [Robot de diálogo por voz Bailing (百聆语音对话机器人)](https://github.com/wwbin2017/bailing) | Este proyecto parte del [robot de diálogo por voz Bailing](https://github.com/wwbin2017/bailing) y se construye sobre esa base |
| <img src="../images/logo_tenclass.png" width="160"> | [Tenclass (十方融海)](https://www.tenclass.com/) | Gracias a [Tenclass](https://www.tenclass.com/) por definir el protocolo de comunicación estándar del ecosistema Xiaozhi, las soluciones de compatibilidad con varios dispositivos y los ejemplos prácticos de alta concurrencia, y por el apoyo de documentación técnica de todo el recorrido de este proyecto |
| <img src="../images/logo_xuanfeng.png" width="160"> | [Xuanfeng Technology (玄凤科技)](https://github.com/Eric0308) | Gracias a [Xuanfeng Technology](https://github.com/Eric0308) por el código del marco de llamada a funciones, del protocolo de comunicación MCP y del mecanismo de llamadas basado en plugins. Con un sistema estandarizado de despacho de instrucciones y capacidad de ampliación dinámica, mejora de forma clara la eficiencia de interacción y la extensibilidad de los dispositivos de frontend (IoT) |
| <img src="../images/logo_junsen.png" width="160"> | [huangjunsen](https://github.com/huangjunsen0406) | Gracias a [huangjunsen](https://github.com/huangjunsen0406) por el módulo `consola inteligente móvil`, que permite controlar con eficacia dispositivos móviles de varias plataformas e interactuar en tiempo real, y mejora mucho la comodidad de uso y la eficiencia de gestión en escenarios móviles |
| <img src="../images/logo_huiyuan.png" width="160"> | [Huiyuan Design (汇远设计)](http://ui.kwd988.net/) | Gracias a [Huiyuan Design](http://ui.kwd988.net/) por la solución visual de este proyecto, y por poner al servicio de la experiencia de uso la práctica de diseño acumulada con más de mil empresas |
| <img src="../images/logo_qinren.png" width="160"> | [Xi'an Qinren Information Technology (西安勤人信息科技)](https://www.029app.com/) | Gracias a [Xi'an Qinren Information Technology](https://www.029app.com/) por profundizar el sistema visual de este proyecto y mantener un estilo coherente y ampliable en distintos escenarios |
| <img src="../images/logo_contributors.png" width="160"> | [Quienes contribuyen código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Gracias a [todas las personas que contribuyen código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors). Su trabajo hace el proyecto más sólido y más capaz. |
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
</picture>
</a>

View file

@ -22,6 +22,7 @@ Suporte ao protocolo MQTT+UDP, protocolo WebSocket, ponto de acesso MCP, reconhe
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DBEDFA"></a>
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a>
@ -54,31 +55,31 @@ Quer ver os efeitos de uso? Clique nos vídeos abaixo 🎥
<td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture>
<img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
<img alt="A sensação da velocidade de resposta" src="../images/demo9.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
<picture>
<img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
<img alt="O segredo para otimizar a velocidade" src="../images/demo6.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
<picture>
<img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
<img alt="Humano digital Xiaozhi com ativação por voz" src="../images/demo8.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
<picture>
<img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
<img alt="Chamadas de dispositivo para dispositivo" src="../images/demo0.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture>
<img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
<img alt="Cenário médico complexo" src="../images/demo1.png" /></picture>
</a>
</td>
</tr>
@ -86,31 +87,31 @@ Quer ver os efeitos de uso? Clique nos vídeos abaixo 🎥
<td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture>
<img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
<img alt="Reproduzir música, consultar o tempo e ler as notícias" src="../images/demo7.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture>
<img alt="实时打断" src="docs/images/demo10.png" /></picture>
<img alt="Interrupção em tempo real" src="../images/demo10.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
<picture>
<img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
<img alt="Reconhecer objetos com uma foto" src="../images/demo12.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture>
<img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
<img alt="Controlar o acionamento de eletrodomésticos" src="../images/demo5.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture>
<img alt="多指令任务" src="docs/images/demo11.png" /></picture>
<img alt="Tarefas com vários comandos" src="../images/demo11.png" /></picture>
</a>
</td>
</tr>
@ -118,31 +119,31 @@ Quer ver os efeitos de uso? Clique nos vídeos abaixo 🎥
<td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture>
<img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
<img alt="Ponto de acesso MCP" src="../images/demo13.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
<picture>
<img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
<img alt="Envio de comandos MQTT" src="../images/demo4.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture>
<img alt="声纹识别" src="docs/images/demo14.png" /></picture>
<img alt="Reconhecimento de impressão vocal" src="../images/demo14.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture>
<img alt="自定义音色" src="docs/images/demo2.png" /></picture>
<img alt="Tom de voz personalizado" src="../images/demo2.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
<picture>
<img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
<img alt="Conversa em cantonês" src="../images/demo3.png" /></picture>
</a>
</td>
</tr>
@ -167,8 +168,8 @@ Este projeto oferece dois métodos de implantação. Por favor, escolha de acord
#### 🚀 Seleção do Método de Implantação
| Método de Implantação | Funcionalidades | Cenários Aplicáveis | Documentação de Implantação | Requisitos de Configuração | Tutoriais em Vídeo |
|---------|------|---------|---------|---------|---------|
| **Instalação Simplificada** | Diálogo inteligente, gerenciamento de agente único | Ambientes de baixa configuração, dados armazenados em arquivos de configuração, sem necessidade de banco de dados | [①Versão Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Implantação via Código-Fonte](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 núcleos 4GB se usar `FunASR`, 2 núcleos 2GB se todas APIs | - |
| **Instalação de Módulo Completo** | Diálogo inteligente, gerenciamento multiusuário, gerenciamento de múltiplos agentes, operação de interface do console inteligente | Experiência com funcionalidade completa, dados armazenados em banco de dados |[①Versão Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Implantação via Código-Fonte](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Tutorial de Atualização Automática via Código-Fonte](../dev-ops-integration.md) | 4 núcleos 8GB se usar `FunASR`, 2 núcleos 4GB se todas APIs| [Tutorial em Vídeo de Inicialização via Código-Fonte Local](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
| **Instalação Simplificada** | Diálogo inteligente, gerenciamento de agente único | Ambientes de baixa configuração, dados armazenados em arquivos de configuração, sem necessidade de banco de dados | [①Versão Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Implantação via Código-Fonte](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| `FunASR` local exige mais memória; usar apenas APIs mantém o consumo de recursos baixo | - |
| **Instalação de Módulo Completo** | Diálogo inteligente, gerenciamento multiusuário, gerenciamento de múltiplos agentes, operação de interface do console inteligente | Experiência com funcionalidade completa, dados armazenados em banco de dados |[①Versão Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Implantação via Código-Fonte](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Tutorial de Atualização Automática via Código-Fonte](../dev-ops-integration.md) | `FunASR` local exige mais memória e recursos de banco de dados; usar apenas APIs mantém o consumo de recursos baixo| [Tutorial em Vídeo de Inicialização via Código-Fonte Local](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
Perguntas frequentes e tutoriais relacionados podem ser consultados [neste link](../FAQ.md)
@ -209,15 +210,15 @@ Este projeto fornece as seguintes ferramentas de teste para ajudá-lo a verifica
| Nome da Ferramenta | Localização | Método de Uso | Descrição da Função |
|:---:|:---|:---:|:---:|
| Ferramenta de Teste de Interação por Áudio | main》digital-human》index.html | Execute `python start.py` em `main/digital-human` e depois abra `http://127.0.0.1:8006/index.html` | Testa as funções de reprodução e recepção de áudio, verifica se o processamento de áudio no lado Python está normal |
| Ferramenta de Teste de Resposta de Modelo | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Testa a velocidade de resposta dos três módulos principais: ASR(reconhecimento de fala), LLM(modelo de linguagem), VLLM(modelo de visão), TTS(síntese de voz) |
| Ferramenta de Teste de Interação por Áudio | main》digital-human》index.html | Em `main/digital-human`, instale as dependências como indica o README, depois execute `python start.py` e abra `http://127.0.0.1:8006/index.html` | Testa as funções de reprodução e recepção de áudio, verifica se o processamento de áudio no lado Python está normal |
| Ferramenta de Teste de Resposta de Modelo | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Testa a velocidade de resposta de módulos principais como ASR(reconhecimento de fala), LLM(modelo de linguagem), VLLM(modelo de visão), TTS(síntese de voz) |
> 💡 Nota: Ao testar a velocidade dos modelos, apenas os modelos com chaves configuradas serão testados.
---
## Lista de Funcionalidades ✨
### Implementado ✅
![请参考-全模块安装架构图](../images/deploy2.png)
![Diagrama de arquitetura da instalação de todos os módulos](../images/deploy2.png)
| Módulo de Funcionalidade | Descrição |
|:---:|:---|
| Arquitetura Principal | Baseado em [gateway MQTT+UDP](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), servidores WebSocket e HTTP, fornece sistema completo de gerenciamento de console e autenticação |
@ -225,15 +226,15 @@ Este projeto fornece as seguintes ferramentas de teste para ajudá-lo a verifica
| Reconhecimento de Impressão Vocal | Suporta registro, gerenciamento e reconhecimento de impressão vocal de múltiplos usuários, processa em paralelo com o ASR, reconhecimento de identidade do falante em tempo real e repassa ao LLM para respostas personalizadas |
| Diálogo Inteligente | Suporta múltiplos LLM (modelos de linguagem de grande porte), implementa diálogo inteligente |
| Percepção Visual | Suporta múltiplos VLLM (modelos de visão de grande porte), implementa interação multimodal |
| Reconhecimento de Intenção | Suporta reconhecimento de intenção por LLM, Function Call (chamada de função), fornece mecanismo de processamento de intenção baseado em plugins |
| Reconhecimento de Intenção | Suporta reconhecimento de intenção por LLM externo e conectável, chamada de função autônoma do modelo de linguagem, fornece mecanismo de processamento de intenção baseado em plugins |
| Sistema de Memória | Suporta memória local de curto prazo, memória via interface mem0ai, memória inteligente PowerMem, com funcionalidade de resumo de memória |
| Base de Conhecimento | Suporta base de conhecimento RAGFlow, permitindo que o LLM julgue se deve acionar a base de conhecimento após receber a pergunta do usuário, e então responda à pergunta |
| Chamada de Ferramentas | Suporta protocolo IOT do cliente, protocolo MCP do cliente, protocolo MCP do servidor, protocolo de endpoint MCP, funções de ferramentas personalizadas |
| Chamada de Ferramentas | Suporta protocolo IOT do cliente, protocolo MCP do cliente, protocolo MCP do servidor, protocolo de ponto de acesso MCP, funções de ferramentas personalizadas |
| Envio de Comandos | Suporta envio de comandos MCP para dispositivos ESP32 via protocolo MQTT a partir do Console Inteligente |
| Backend de Gerenciamento | Fornece interface de gerenciamento Web, suporta gerenciamento de usuários, configuração do sistema e gerenciamento de dispositivos; Suporta exibição em Chinês Simplificado, Chinês Tradicional e Inglês |
| Ferramentas de Teste | Fornece ferramentas de teste de desempenho, ferramentas de teste de modelo de visão e ferramentas de teste de interação por áudio |
| Backend de Gerenciamento | Fornece interface de gerenciamento Web, suporta gerenciamento de usuários, configuração do sistema e gerenciamento de dispositivos; Suporta exibição em Chinês Simplificado, Chinês Tradicional, Inglês, Alemão, Vietnamita e Português do Brasil |
| Ferramentas de Teste | Fornece ferramentas de teste de desempenho de resposta de modelo e ferramentas de teste de interação por áudio |
| Suporte à Implantação | Suporta implantação via Docker e implantação local, fornece gerenciamento completo de arquivos de configuração |
| Sistema de Plugins | Suporta extensões de plugins funcionais, desenvolvimento de plugins personalizados e carregamento dinâmico de plugins |
| Sistema de Plugins | Suporta extensões de plugins funcionais e desenvolvimento de plugins personalizados; novos arquivos de plugin são carregados na próxima conexão do dispositivo e alterações em plugins já carregados exigem reiniciar o serviço |
### Em Desenvolvimento 🚧
@ -253,7 +254,7 @@ Xiaozhi é um ecossistema. Ao utilizar este produto, você também pode conferir
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|:---:|:---:|:---:|
| Chamadas via interface OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK | Zhipu, Gemini |
| Chamadas via interface OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini |
| Chamadas via interface Ollama | Ollama | - |
| Chamadas via interface Dify | Dify | - |
| Chamadas via interface FastGPT | FastGPT | - |
@ -261,7 +262,7 @@ Xiaozhi é um ecossistema. Ao utilizar este produto, você também pode conferir
| Chamadas via interface Xinference | Xinference | - |
| Chamadas via interface HomeAssistant | HomeAssistant | - |
Na verdade, qualquer LLM que suporte chamadas via interface openai pode ser integrado e utilizado.
Na verdade, qualquer LLM que suporte chamadas via interface OpenAI pode ser integrado e utilizado.
---
@ -269,7 +270,7 @@ Na verdade, qualquer LLM que suporte chamadas via interface openai pode ser inte
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|:---:|:---:|:---:|
| Chamadas via interface OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
| Chamadas via interface OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser integrado e utilizado.
@ -279,8 +280,8 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|:---:|:---:|:---:|
| Chamadas via interface | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud e Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow(parcial) |
| Serviços locais | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
| Chamadas via interface | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud e Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow(parcial) |
| Serviços locais | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
---
@ -296,8 +297,8 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|:---:|:---:|:---:|
| Uso local | FunASR, SherpaASR | FunASR, SherpaASR |
| Chamadas via interface | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
| Uso local | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
| Chamadas via interface | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud e Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
---
@ -305,7 +306,9 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|:---:|:---:|:---:|
| Uso local | 3D-Speaker | 3D-Speaker |
| Chamadas via interface | Serviço de voiceprint (voiceprint-api) | - |
O reconhecimento de impressão vocal exige um serviço [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) implantado separadamente (baseado em 3D-Speaker) e MySQL. Veja o [guia de integração de voiceprint](../voiceprint-integration.md).
---
@ -317,6 +320,7 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
| Memória | [powermem](../powermem-integration.md) | Resumo local | Depende do LLM e BD | OceanBase de código aberto, suporta busca inteligente |
| Memória | mem_local_short | Resumo local | Gratuito | |
| Memória | nomem | Modo sem memória | Gratuito | |
| Memória | mem_report_only | Apenas relatório | Gratuito | Apenas reporta o histórico de chat, sem resumo de memória |
---
@ -351,11 +355,10 @@ Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser int
| <img src="../images/logo_contributors.png" width="160"> | [Contribuidores de Código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Agradecimentos a [todos os contribuidores de código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), seus esforços tornaram o projeto mais robusto e poderoso. |
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
</picture>
</a>

View file

@ -6,7 +6,7 @@
Dự án này dựa trên lý thuyết và công nghệ trí tuệ cộng sinh người-máy để phát triển hệ thống phần mềm và phần cứng thiết bị đầu cuối thông minh<br/>Cung cấp dịch vụ backend cho dự án phần cứng thông minh mã nguồn mở
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
Được triển khai bằng Python, Java, Vue theo <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">giao thức truyền thông Xiaozhi</a><br/>
Hỗ trợ giao thức MQTT+UDP, giao thức Websocket, điểm truy cập MCP, nhận dạng giọng nói và kho tri thức
Hỗ trợ giao thức MQTT+UDP, giao thức Websocket, điểm truy cập MCP, nhận dạng vân giọng và kho tri thức
</p>
<p align="center">
@ -22,6 +22,7 @@ Hỗ trợ giao thức MQTT+UDP, giao thức Websocket, điểm truy cập MCP,
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DBEDFA"></a>
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
<a href="./README_es.md"><img alt="Español" src="https://img.shields.io/badge/Español-DFE0E5"></a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a>
@ -38,7 +39,7 @@ Spearheaded by Professor Siyuan Liu's Team (South China University of Technology
</br>
Được dẫn dắt bởi nhóm Giáo sư Lưu Tư Nguyên (Đại học Bách khoa Nam Trung Quốc)
</br>
<img src="../images/hnlg.jpg" alt="华南理工大学" width="50%">
<img src="../images/hnlg.jpg" alt="Đại học Bách khoa Nam Trung Quốc" width="50%">
</p>
---
@ -54,31 +55,31 @@ Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
<td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture>
<img alt="响应速度感受" src="docs/images/demo9.png" /></picture>
<img alt="Cảm giác tốc độ phản hồi" src="../images/demo9.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
<picture>
<img alt="速度优化秘诀" src="docs/images/demo6.png" /></picture>
<img alt="Bí quyết tối ưu tốc độ" src="../images/demo6.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1WEcxzFEAT" target="_blank">
<picture>
<img alt="小智数字人 支持语音唤醒" src="docs/images/demo8.png" /></picture>
<img alt="Người ảo số Xiaozhi có đánh thức bằng giọng nói" src="../images/demo8.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CKVz6UEuB" target="_blank">
<picture>
<img alt="设备呼叫设备,打电话" src="docs/images/demo0.png" /></picture>
<img alt="Gọi giữa các thiết bị" src="../images/demo0.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture>
<img alt="复杂医疗场景" src="docs/images/demo1.png" /></picture>
<img alt="Tình huống y tế phức tạp" src="../images/demo1.png" /></picture>
</a>
</td>
</tr>
@ -86,31 +87,31 @@ Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
<td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture>
<img alt="播放音乐查询天气播报新闻" src="docs/images/demo7.png" /></picture>
<img alt="Phát nhạc, tra cứu thời tiết và đọc tin tức" src="../images/demo7.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture>
<img alt="实时打断" src="docs/images/demo10.png" /></picture>
<img alt="Ngắt giữa chừng theo thời gian thực" src="../images/demo10.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
<picture>
<img alt="拍照识物品" src="docs/images/demo12.png" /></picture>
<img alt="Nhận dạng vật thể qua ảnh chụp" src="../images/demo12.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture>
<img alt="控制家电开关" src="docs/images/demo5.png" /></picture>
<img alt="Bật tắt thiết bị gia dụng" src="../images/demo5.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture>
<img alt="多指令任务" src="docs/images/demo11.png" /></picture>
<img alt="Nhiệm vụ nhiều lệnh" src="../images/demo11.png" /></picture>
</a>
</td>
</tr>
@ -118,31 +119,31 @@ Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
<td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture>
<img alt="MCP接入点" src="docs/images/demo13.png" /></picture>
<img alt="Điểm truy cập MCP" src="../images/demo13.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
<picture>
<img alt="MQTT指令下发" src="docs/images/demo4.png" /></picture>
<img alt="Gửi lệnh MQTT" src="../images/demo4.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture>
<img alt="声纹识别" src="docs/images/demo14.png" /></picture>
<img alt="Nhận dạng vân giọng" src="../images/demo14.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture>
<img alt="自定义音色" src="docs/images/demo2.png" /></picture>
<img alt="Giọng nói tùy chỉnh" src="../images/demo2.png" /></picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
<picture>
<img alt="使用粤语交流" src="docs/images/demo3.png" /></picture>
<img alt="Trò chuyện bằng tiếng Quảng Đông" src="../images/demo3.png" /></picture>
</a>
</td>
</tr>
@ -168,12 +169,12 @@ Dự án này cung cấp hai phương pháp triển khai, vui lòng chọn theo
#### 🚀 Lựa chọn phương pháp triển khai
| Phương pháp triển khai | Đặc điểm | Tình huống áp dụng | Tài liệu triển khai | Yêu cầu cấu hình | Video hướng dẫn |
|---------|------|---------|---------|---------|---------|
| **Cài đặt tối giản** | Đối thoại thông minh, quản lý đơn tác nhân | Môi trường cấu hình thấp, dữ liệu lưu trong tệp cấu hình, không cần cơ sở dữ liệu | [①Phiên bản Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Triển khai mã nguồn](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 nhân 4GB nếu dùng `FunASR`, 2 nhân 2GB nếu toàn API | - |
| **Cài đặt toàn bộ module** | Đối thoại thông minh, quản lý đa người dùng, quản lý đa tác nhân, bảng điều khiển thông minh | Trải nghiệm đầy đủ tính năng, dữ liệu lưu trong cơ sở dữ liệu |[①Phiên bản Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Triển khai mã nguồn](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Hướng dẫn tự động cập nhật triển khai mã nguồn](../dev-ops-integration.md) | 4 nhân 8GB nếu dùng `FunASR`, 2 nhân 4GB nếu toàn API| [Video hướng dẫn khởi động mã nguồn cục bộ](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
| **Cài đặt tối giản** | Đối thoại thông minh, quản lý đơn tác nhân | Môi trường cấu hình thấp, dữ liệu lưu trong tệp cấu hình, không cần cơ sở dữ liệu | [①Phiên bản Docker](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Triển khai mã nguồn](../Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| `FunASR` cục bộ cần nhiều bộ nhớ; dùng toàn API thì mức dùng tài nguyên thấp | - |
| **Cài đặt toàn bộ module** | Đối thoại thông minh, quản lý đa người dùng, quản lý đa tác nhân, thao tác qua bảng điều khiển thông minh | Trải nghiệm đầy đủ tính năng, dữ liệu lưu trong cơ sở dữ liệu |[①Phiên bản Docker](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Triển khai mã nguồn](../Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Hướng dẫn tự động cập nhật triển khai mã nguồn](../dev-ops-integration.md) | `FunASR` cục bộ cần nhiều bộ nhớ, thêm tài nguyên cơ sở dữ liệu; dùng toàn API thì mức dùng tài nguyên thấp| [Video hướng dẫn khởi động mã nguồn cục bộ](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
Câu hỏi thường gặp và hướng dẫn liên quan, vui lòng tham khảo [liên kết này](../FAQ.md)
> 💡 Gợi ý: Dưới đây là nền tảng thử nghiệm được triển khai theo mã mới nhất, có thể flash để thử nghiệm nếu cần, đồng thời là 6, dữ liệu sẽ được xóa mỗi ngày,
> 💡 Gợi ý: Dưới đây là nền tảng thử nghiệm được triển khai theo mã mới nhất, có thể flash để thử nghiệm nếu cần, đồng thời là 6, dữ liệu sẽ được xóa mỗi ngày.
```
Địa chỉ bảng điều khiển thông minh: https://2662r3426b.vicp.fun
@ -192,7 +193,7 @@ Công cụ kiểm tra dịch vụ: https://2662r3426b.vicp.fun/test/
>
> 2. `Cấu hình streaming`: Phù hợp với demo, đào tạo, hơn 2 đồng thời, v.v., sử dụng công nghệ xử lý streaming, tốc độ phản hồi nhanh hơn, trải nghiệm tốt hơn.
>
> Từ phiên bản `0.5.2`, dự án hỗ trợ cấu hình streaming, so với phiên bản đầu, tốc độ phản hồi cải thiện khoảng `2.5 giây`, cải thiện đáng kể trải nghiệm người dùng.
> Từ phiên bản `0.5.2`, dự án hỗ trợ cấu hình streaming, so với các phiên bản trước đó, tốc độ phản hồi cải thiện khoảng `2.5 giây`, cải thiện đáng kể trải nghiệm người dùng.
| Tên module | Cài đặt miễn phí cho người mới | Cấu hình streaming |
|:---:|:---:|:---:|
@ -210,15 +211,15 @@ Dự án này cung cấp các công cụ kiểm tra sau để giúp bạn xác m
| Tên công cụ | Vị trí | Phương pháp sử dụng | Mô tả chức năng |
|:---:|:---|:---:|:---:|
| Công cụ kiểm tra tương tác âm thanh | main》digital-human》index.html | Chạy `python start.py` trong `main/digital-human`, sau đó mở `http://127.0.0.1:8006/index.html` | Kiểm tra chức năng phát và nhận âm thanh, xác minh xử lý âm thanh phía Python có bình thường không |
| Công cụ kiểm tra phản hồi mô hình | main》xiaozhi-server》performance_tester.py | Thực hiện `python performance_tester.py` | Kiểm tra tốc độ phản hồi của ba module cốt lõi ASR(Nhận dạng giọng nói), LLM(Mô hình lớn), VLLM(Mô hình thị giác), TTS(Tổng hợp giọng nói) |
| Công cụ kiểm tra tương tác âm thanh | main》digital-human》index.html | Trong `main/digital-human`, cài đặt các phụ thuộc theo README, rồi chạy `python start.py` và mở `http://127.0.0.1:8006/index.html` | Kiểm tra chức năng phát và nhận âm thanh, xác minh xử lý âm thanh phía Python có bình thường không |
| Công cụ kiểm tra phản hồi mô hình | main》xiaozhi-server》performance_tester.py | Thực hiện `python performance_tester.py` | Kiểm tra tốc độ phản hồi của các module cốt lõi như ASR(Nhận dạng giọng nói), LLM(Mô hình lớn), VLLM(Mô hình thị giác), TTS(Tổng hợp giọng nói) |
> 💡 Gợi ý: Khi kiểm tra tốc độ mô hình, chỉ kiểm tra các mô hình đã cấu hình khóa.
---
## Danh sách tính năng ✨
### Đã thực hiện ✅
![请参考-全模块安装架构图](../images/deploy2.png)
![Sơ đồ kiến trúc cài đặt đầy đủ các module](../images/deploy2.png)
| Module chức năng | Mô tả |
|:---:|:---|
| Kiến trúc cốt lõi | Dựa trên [cổng MQTT+UDP](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket, máy chủ HTTP, cung cấp hệ thống quản lý bảng điều khiển và xác thực hoàn chỉnh |
@ -231,10 +232,10 @@ Dự án này cung cấp các công cụ kiểm tra sau để giúp bạn xác m
| Kho tri thức | Hỗ trợ kho tri thức RAGFlow, cho phép mô hình lớn đánh giá cần gọi kho tri thức trước khi trả lời |
| Gọi công cụ | Hỗ trợ giao thức IOT phía client, giao thức MCP phía client, giao thức MCP phía server, giao thức điểm truy cập MCP, hàm công cụ tùy chỉnh |
| Gửi lệnh | Dựa vào giao thức MQTT, hỗ trợ gửi lệnh MCP từ bảng điều khiển thông minh xuống thiết bị ESP32 |
| Backend quản lý | Cung cấp giao diện quản lý Web, hỗ trợ quản lý người dùng, cấu hình hệ thống và quản lý thiết bị; giao diện hỗ trợ hiển thị tiếng Trung giản thể, tiếng Trung phồn thể, tiếng Anh |
| Công cụ kiểm tra | Cung cấp công cụ kiểm tra hiệu suất, công cụ kiểm tra mô hình thị giác và công cụ kiểm tra tương tác âm thanh |
| Backend quản lý | Cung cấp giao diện quản lý Web, hỗ trợ quản lý người dùng, cấu hình hệ thống và quản lý thiết bị; giao diện hỗ trợ hiển thị tiếng Trung giản thể, tiếng Trung phồn thể, tiếng Anh, tiếng Đức, tiếng Việt và tiếng Bồ Đào Nha Brazil |
| Công cụ kiểm tra | Cung cấp công cụ kiểm tra hiệu suất phản hồi mô hình và công cụ kiểm tra tương tác âm thanh |
| Hỗ trợ triển khai | Hỗ trợ triển khai Docker và triển khai cục bộ, cung cấp quản lý tệp cấu hình hoàn chỉnh |
| Hệ thống plugin | Hỗ trợ mở rộng plugin chức năng, phát triển plugin tùy chỉnh và hot loading plugin |
| Hệ thống plugin | Hỗ trợ mở rộng plugin chức năng và phát triển plugin tùy chỉnh; file plugin mới được tải ở lần kết nối thiết bị tiếp theo, thay đổi mã của plugin đã tải cần khởi động lại dịch vụ |
### Đang phát triển 🚧
@ -254,7 +255,7 @@ Xiaozhi là một hệ sinh thái, khi bạn sử dụng sản phẩm này, bạ
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|:---:|:---:|:---:|
| Gọi giao diện openai | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFlytek | Zhipu, Gemini |
| Gọi giao diện OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK, LM Studio | Zhipu, Gemini |
| Gọi giao diện ollama | Ollama | - |
| Gọi giao diện dify | Dify | - |
| Gọi giao diện fastgpt | Fastgpt | - |
@ -262,7 +263,7 @@ Xiaozhi là một hệ sinh thái, khi bạn sử dụng sản phẩm này, bạ
| Gọi giao diện xinference | Xinference | - |
| Gọi giao diện homeassistant | HomeAssistant | - |
Trên thực tế, bất kỳ LLM nào hỗ trợ gọi giao diện openai đều có thể truy cập sử dụng.
Trên thực tế, bất kỳ LLM nào hỗ trợ gọi giao diện OpenAI đều có thể truy cập sử dụng.
---
@ -270,9 +271,9 @@ Trên thực tế, bất kỳ LLM nào hỗ trợ gọi giao diện openai đề
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|:---:|:---:|:---:|
| Gọi giao diện openai | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
| Gọi giao diện OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM |
Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đều có thể truy cập sử dụng.
Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện OpenAI đều có thể truy cập sử dụng.
---
@ -280,8 +281,8 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|:---:|:---:|:---:|
| Gọi giao diện | EdgeTTS, iFlytek, Volcano Engine, Tencent Cloud, Alibaba Cloud và Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi streaming TTS, MinimaxTTS | Lingxi streaming TTS, EdgeTTS, CosyVoiceSiliconflow(một phần) |
| Dịch vụ cục bộ | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
| Gọi giao diện | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud và Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, CustomTTS, OpenAITTS, MinimaxTTS | EdgeTTS, CosyVoiceSiliconflow(một phần) |
| Dịch vụ cục bộ | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, IndexStreamTTS, PaddleSpeechTTS | IndexStreamTTS, PaddleSpeechTTS, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
---
@ -297,8 +298,8 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|:---:|:---:|:---:|
| Sử dụng cục bộ | FunASR, SherpaASR | FunASR, SherpaASR |
| Gọi giao diện | FunASRServer, Volcano Engine, iFlytek, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
| Sử dụng cục bộ | FunASR, SherpaASR, SherpaParaformerASR, VoskASR | FunASR, SherpaASR, SherpaParaformerASR, VoskASR |
| Gọi giao diện | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud và Bailian, Baidu Cloud, OpenAI ASR, GroqASR, Qwen3ASRFlash | FunASRServer |
---
@ -306,7 +307,9 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|:---:|:---:|:---:|
| Sử dụng cục bộ | 3D-Speaker | 3D-Speaker |
| Gọi giao diện | Dịch vụ nhận dạng vân giọng (voiceprint-api) | - |
Nhận dạng vân giọng cần dịch vụ [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) được triển khai riêng (dựa trên 3D-Speaker) và MySQL. Xem [hướng dẫn tích hợp voiceprint](../voiceprint-integration.md).
---
@ -318,6 +321,7 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
| Memory | [powermem](../powermem-integration.md) | Tóm tắt cục bộ | Phụ thuộc vào LLM và DB | OceanBase mã nguồn mở, hỗ trợ tìm kiếm thông minh |
| Memory | mem_local_short | Tóm tắt cục bộ | Miễn phí | |
| Memory | nomem | Chế độ không có bộ nhớ | Miễn phí | |
| Memory | mem_report_only | Chỉ báo cáo | Miễn phí | Chỉ báo cáo lịch sử trò chuyện, không tóm tắt bộ nhớ |
---
@ -352,11 +356,10 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
| <img src="../images/logo_contributors.png" width="160"> | [Người đóng góp mã](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Cảm ơn [tất cả người đóng góp mã](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), sự cống hiến của bạn khiến dự án mạnh mẽ và vững chắc hơn. |
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
<a href="https://www.star-history.com/?repos=xinnan-tech%2Fxiaozhi-esp32-server&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&theme=dark&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=xinnan-tech/xiaozhi-esp32-server&type=date&legend=top-left&sealed_token=cQovHKgZjqEnQ-svfYfN392irNvGuq-6pyv4cA8nd2jQEhQLz1ETV4YHTVk2UZyLMFbCQuZA7jduRh3YbeK5WPYaRLrfmIimGQa3lram652jJL9oQk-UuSZA5H6L4dPIhZc8KCc-Ur_UAUNbly7TePpnTR2otGknBLCOjOliD4fk1st6z7tPEDVjSRx5" />
</picture>
</a>

View file

@ -16,7 +16,7 @@
点击它,下载本项目源码压缩包。下载到你电脑后,解压它,此时它的名字可能叫`voiceprint-api-main`
你需要把它重命名成`voiceprint-api`。
## 第二步, 创建数据库和表
## 第二步, 确认 MySQL 能访问
声纹识别需要依赖`mysql`数据库。如果你之前已经部署`智控台`,说明你已经安装了`mysql`。你可以共用它。
@ -39,7 +39,7 @@ telnet 127.0.0.1 3306
networks:
- default
expose:
- "3306:3306"
- 3306
```
修改后
@ -58,8 +58,9 @@ telnet 127.0.0.1 3306
# 进入你docker-compose_all.yml所在的文件夹,例如我的是xiaozhi-server
cd xiaozhi-server
docker compose -f docker-compose_all.yml down
docker compose -f docker-compose.yml up -d
docker compose -f docker-compose_all.yml up -d
```
数据库服务`xiaozhi-esp32-server-db`在`docker-compose_all.yml`里,最小化的`docker-compose.yml`只有服务本身,所以两条命令都用`docker-compose_all.yml`。
启动完后,在宿主机再使用`telnet`命令,看看能不能正常访问`mysql`的`3306`端口。
```
@ -171,6 +172,8 @@ http://192.168.1.25:8005/voiceprint/health?key=abcd
然后搜索参数`server.voice_print`,此时,它的值应该是`null`值。
点击修改按钮,把上一步得来的`声纹接口地址`粘贴到`参数值`里。然后保存。
声纹识别的相似度阈值是另一个系统参数`server.voiceprint_similarity_threshold`(默认0.4,范围0.0-1.0,数值越高越严格),要调整就在同一个`参数管理`页面里改。
如果能保存成功,说明一切顺利,你可以去智能体查看效果了。如果不成功,说明智控台无法访问声纹识别,很大概率是网络防火墙,或者没有填写正确的局域网ip。
## 第二步 设置智能体记忆模式
@ -186,7 +189,7 @@ http://192.168.1.25:8005/voiceprint/health?key=abcd
在智控台,`智能体管理`页面,在智能体的面板里,有一个`声纹识别`按钮,点击它。在底部有一个`新增按钮`。就可以对某个人说的话进行声纹注册。
在弹出的框里,`描述`这个属性建议填写上,可以是这个人的职业、性格、爱好。方便智能体对说话人进行分析和了解。
## 第三步 和你的智能体聊天
## 第五步 验证效果
将你的设备通电,问它,你知道我是谁吗?如果他能回答得出,说明声纹识别功能正常。
@ -205,6 +208,9 @@ voiceprint:
- "test1,张三,张三是一个程序员"
- "test2,李四,李四是一个产品经理"
- "test3,王五,王五是一个设计师"
# 声纹识别相似度阈值,范围0.0-1.0,默认0.4
# 数值越高越严格,减少误识别但可能增加拒识率
similarity_threshold: 0.4
```
把上一步得来的 `声纹接口地址` 粘贴到 `url` 里。然后保存。

View file

@ -2,14 +2,16 @@
## 功能简介
联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持三个搜索源:秘塔(Metaso)、Tavily和Serply,用户可根据需要选择其中一个。
联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持五个搜索源:秘塔(Metaso)、Tavily、Serply、Outcrawl和SpecStream,用户可根据需要选择其中一个。
## API Key申请指南
目前我们适配了`秘塔搜索`、`Tavily搜索`和`Serply搜索`。
目前我们适配了`秘塔搜索`、`Tavily搜索`、`Serply搜索`、`Outcrawl搜索`和`SpecStream搜索`。
- Tavily搜索:每个月1000次免费额度。
- 秘塔搜索:拥有较为优质的国内数据源。
- Serply搜索:返回谷歌搜索结果,注册赠送2500次免费额度,额度用完后需要付费。
- Outcrawl搜索:面向AI智能体的网页搜索接口,每月1000 credits免费额度。
- SpecStream搜索:注册赠送10美元,每条结果带来源链接和摘要,有发布日期时一并返回;每1000次搜索5美元(每次最多10条结果)。
## API Key申请指南
@ -32,6 +34,20 @@
- 复制生成的API Key,这是配置所需的关键信息
- 接口说明见 [Serply文档](https://serply.io/docs)
### 方式四:使用Outcrawl搜索
- 访问 [Outcrawl](https://outcrawl.ai),注册并登录账号
- 在控制台中创建API Key
- 复制生成的API Key,这是配置所需的关键信息
- 接口说明见 [Outcrawl文档](https://outcrawl.ai/docs/search/overview)
### 方式五:使用SpecStream搜索
- 访问 [SpecStream](https://specstream.ai/signup?src=xiaozhi-esp32-server),注册并登录账号
- 在工作区的 Agents & API 页面创建API Key
- 复制生成的API Key,这是配置所需的关键信息
- 接口说明见 [SpecStream文档](https://specstream.ai/search-api)
## 配置方式
### 方式1. 使用智控台部署(推荐)
@ -40,14 +56,14 @@
- 进入"配置角色"页面,选择要配置的智能体
- 点击"编辑功能"按钮,在右侧参数配置区域找到"联网搜索"插件
- 勾选"联网搜索"
- 填入搜索源(`metaso`、`tavily`或`serply`),并将对应的`API Key`填入配置项
- 填入搜索源(`metaso`、`tavily`、`serply`、`outcrawl`或`specstream`),并将对应的`API Key`填入配置项
- 保存配置,再保存智能体配置
### 方式2. 单模块xiaozhi-server部署
在 `data/.config.yaml` 中配置:
- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily` 或 `serply`
- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily`、`serply`、`outcrawl` 或 `specstream`
- 将申请到的API Key填入 `api_key`
```yaml

View file

@ -16,3 +16,28 @@ Vue 3.x
# 接口文档
启动后打开:http://localhost:8002/xiaozhi/doc.html
# 跑测试
测试分两种:纯单元测试,和要真连 MySQL、Redis 的集成测试(`DeviceTest`、`loginControllerTest`、`ModelConfigPersistenceTest`)。
集成测试需要先起好 MySQL 8 和 Redis 8。没起的时候这类测试整类跳过,不会让构建变红,日志里会写明缺的是哪个依赖。CI 上不一样:依赖连不上就直接让构建失败,不许跳过,免得门禁被悄悄掏空。
本地用 Docker 起这两个依赖:
```bash
docker run -d --name xiaozhi-mysql -p 3306:3306 \
-e MYSQL_ROOT_PASSWORD=123456 -e MYSQL_DATABASE=xiaozhi_esp32_server mysql:8.0
docker run -d --name xiaozhi-redis -p 6379:6379 redis:8.0
```
跑全部测试:
```bash
mvn -B test -DskipTests=false
```
只想编译、不跑测试:
```bash
mvn -B package -DskipTests=true
```

View file

@ -32,7 +32,7 @@
<liquibase-core.version>4.20.0</liquibase-core.version>
<aliyun-sms-version>4.1.0</aliyun-sms-version>
<okio-version>3.4.0</okio-version>
<skipTests>true</skipTests>
<skipTests>false</skipTests>
<argLine></argLine>
</properties>

View file

@ -0,0 +1,44 @@
#!/usr/bin/env bash
# 检查那几个要连 MySQL 和 Redis 的集成测试是不是真的跑了。
# 守卫要是哪天手滑把它们全跳过了,CI 必须红,不能安安静静少跑一半门禁。
set -uo pipefail
REPORT_DIR="${1:-target/surefire-reports}"
WATCHED=(
"xiaozhi.modules.device.DeviceTest"
"xiaozhi.modules.model.service.impl.ModelConfigPersistenceTest"
"xiaozhi.modules.sys.loginControllerTest"
)
if [ ! -d "$REPORT_DIR" ]; then
echo "找不到测试报告目录:$REPORT_DIR"
exit 1
fi
missing=()
for class in "${WATCHED[@]}"; do
count=0
for report in "$REPORT_DIR"/TEST-*.xml; do
[ -e "$report" ] || continue
name=$(sed -n 's/.*<testsuite[^>]*name="\([^"]*\)".*/\1/p' "$report" | head -1)
if [ "$name" = "$class" ]; then
count=$(sed -n 's/.*<testsuite[^>]*tests="\([0-9]*\)".*/\1/p' "$report" | head -1)
count=${count:-0}
break
fi
done
if [ "$count" -eq 0 ]; then
missing+=("$class")
else
echo "OK $class 跑了 $count 条"
fi
done
if [ ${#missing[@]} -ne 0 ]; then
echo "这几个集成测试一条都没跑:${missing[*]}"
echo "守卫把门禁掏空了,构建必须失败"
exit 1
fi
echo "集成测试都跑过了"

View file

@ -324,7 +324,7 @@ public interface Constant {
/**
* 版本号
*/
public static final String VERSION = "0.9.7";
public static final String VERSION = "0.9.8";
/**
* 无效固件URL

View file

@ -19,8 +19,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
@ -44,7 +42,6 @@ import xiaozhi.modules.agent.dto.AgentDTO;
import xiaozhi.modules.agent.dto.AgentMemoryDTO;
import xiaozhi.modules.agent.dto.AgentUpdateDTO;
import xiaozhi.modules.agent.entity.AgentEntity;
import xiaozhi.modules.agent.entity.AgentTemplateEntity;
import xiaozhi.modules.agent.dto.AgentTagDTO;
import xiaozhi.modules.agent.entity.AgentTagEntity;
import xiaozhi.modules.agent.service.AgentTagService;
@ -52,7 +49,6 @@ import xiaozhi.modules.agent.service.AgentChatAudioService;
import xiaozhi.modules.agent.service.AgentChatHistoryService;
import xiaozhi.modules.agent.service.AgentChatSummaryService;
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.security.user.SecurityUser;
@ -65,7 +61,6 @@ public class AgentController {
private static final long AUDIO_PLAY_TOKEN_EXPIRE_SECONDS = 300L;
private final AgentService agentService;
private final AgentTemplateService agentTemplateService;
private final AgentChatHistoryService agentChatHistoryService;
private final AgentChatAudioService agentChatAudioService;
private final AgentChatSummaryService agentChatSummaryService;
@ -192,15 +187,6 @@ public class AgentController {
return new Result<>();
}
@GetMapping("/template")
@Operation(summary = "智能体模板模板列表")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentTemplateEntity>> templateList() {
List<AgentTemplateEntity> list = agentTemplateService
.list(new QueryWrapper<AgentTemplateEntity>().orderByAsc("sort"));
return new Result<List<AgentTemplateEntity>>().ok(list);
}
@GetMapping("/{id}/sessions")
@Operation(summary = "获取智能体会话列表")
@RequiresPermissions("sys:role:normal")

View file

@ -41,6 +41,17 @@ public class AgentTemplateController {
private final AgentTemplateService agentTemplateService;
// 单独用 normal 权限(而非类级 superAdmin)是有意保留:
// 普通用户也需查询可用模板,与 /page 的管理入口分离,保持原行为契约。
@GetMapping
@Operation(summary = "智能体模板列表")
@RequiresPermissions("sys:role:normal")
public Result<List<AgentTemplateEntity>> getAgentTemplates() {
List<AgentTemplateEntity> list = agentTemplateService
.list(new QueryWrapper<AgentTemplateEntity>().orderByAsc("sort"));
return new Result<List<AgentTemplateEntity>>().ok(list);
}
@GetMapping("/page")
@Operation(summary = "获取模板分页列表")
@RequiresPermissions("sys:role:superAdmin")

View file

@ -174,6 +174,9 @@ public class DeviceController {
@Operation(summary = "获取设备通讯录")
@RequiresPermissions("sys:role:normal")
public Result<Object> getAddressBook(@PathVariable String macAddress) {
if (deviceService.getOwnedDeviceByMacAddress(macAddress) == null) {
return new Result<Object>().error(ErrorCode.DEVICE_NOT_EXIST);
}
return new Result<Object>().ok(deviceAddressBookService.getAddressBookList(macAddress));
}
@ -192,9 +195,7 @@ public class DeviceController {
@Operation(summary = "更新设备通讯录别名")
@RequiresPermissions("sys:role:normal")
public Result<Void> updateAlias(@Valid @RequestBody DeviceAddressBookAliasDTO dto) {
UserDetail user = SecurityUser.getUser();
DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(dto.getMacAddress());
if (callerDevice == null || !callerDevice.getUserId().equals(user.getId())) {
if (deviceService.getOwnedDeviceByMacAddress(dto.getMacAddress()) == null) {
return new Result<Void>().error("无权限操作该设备");
}
deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), dto.getAlias(), null);
@ -205,9 +206,7 @@ public class DeviceController {
@Operation(summary = "更新设备通讯录权限")
@RequiresPermissions("sys:role:normal")
public Result<Void> updatePermission(@Valid @RequestBody DeviceAddressBookPermissionDTO dto) {
UserDetail user = SecurityUser.getUser();
DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(dto.getMacAddress());
if (callerDevice == null || !callerDevice.getUserId().equals(user.getId())) {
if (deviceService.getOwnedDeviceByMacAddress(dto.getMacAddress()) == null) {
return new Result<Void>().error("无权限操作该设备");
}
deviceAddressBookService.saveOrUpdate(dto.getMacAddress(), dto.getTargetMac(), null, dto.getHasPermission());

View file

@ -83,6 +83,16 @@ public interface DeviceService extends BaseService<DeviceEntity> {
*/
DeviceEntity getDeviceByMacAddress(String macAddress);
/**
* 根据MAC地址获取当前登录用户名下的设备信息
* <p>
* 设备不存在或不属于当前用户时返回null,调用方无需再自行比对归属。
*
* @param macAddress MAC地址
* @return 当前用户名下的设备信息,不存在或无权限时返回null
*/
DeviceEntity getOwnedDeviceByMacAddress(String macAddress);
/**
* 根据设备ID获取激活码
*

View file

@ -1,9 +1,13 @@
package xiaozhi.modules.device.service.impl;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
@ -18,6 +22,7 @@ import xiaozhi.common.redis.RedisKeys;
import xiaozhi.common.redis.RedisUtils;
import xiaozhi.modules.device.dao.DeviceAddressBookDao;
import xiaozhi.modules.device.entity.DeviceAddressBookEntity;
import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.service.DeviceAddressBookService;
import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.modules.sys.service.SysParamsService;
@ -40,7 +45,11 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
@Override
public List<DeviceAddressBookEntity> getAddressBookList(String macAddress) {
return deviceAddressBookDao.getAddressBookList(macAddress);
List<DeviceAddressBookEntity> rows = assignUniqueAliases(deviceAddressBookDao.getAddressBookList(macAddress));
// 取名按固定顺序算完了,前端要看的是最近改过的排前面,放回去
rows.sort(Comparator
.comparing(DeviceAddressBookEntity::getUpdateDate, Comparator.nullsLast(Comparator.reverseOrder())));
return rows;
}
@Override
@ -63,7 +72,7 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
}
// 主动呼叫模式
Map<String, String> callerBook = allBooks.get(callerMac.toLowerCase());
Map<String, String> callerBook = allBooks.get(bookKey(callerMac));
if (callerBook == null) {
return errorResult("未找到备注为'" + nickname + "'的设备");
}
@ -80,13 +89,20 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
}
// 获取目标设备如何称呼主叫方
Map<String, String> targetBook = allBooks.get(targetMac.toLowerCase());
Map<String, String> targetBook = allBooks.get(bookKey(targetMac));
String callerNickname = null;
if (targetBook != null) {
callerNickname = targetBook.get(callerMac.toLowerCase());
callerNickname = targetBook.get(bookKey(callerMac));
}
if (StringUtils.isBlank(callerNickname)) {
callerNickname = deviceService.getDeviceByMacAddress(callerMac).getAlias();
// 主叫显示名取的是主叫方自己那台设备在设备表里的名字,不是对方的。
// 对方那边给主叫方起的称呼在上面的 targetBook 里已经查过。
// 产品上按「来电显示」的口径处理,所以这里不套通讯录那套「不抄对方私产」的限制
// 这个接口没有登录用户上下文,归属校验那个查法在这里会返回空,只能用不校验归属的查法
DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(callerMac);
if (callerDevice != null) {
callerNickname = callerDevice.getAlias();
}
if (StringUtils.isBlank(callerNickname)) {
callerNickname = formatMacAsDeviceName(callerMac);
}
@ -100,32 +116,26 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
@Override
public void refreshCache() {
Map<String, Map<String, String>> result = new HashMap<>();
List<DeviceAddressBookEntity> allRecords = deviceAddressBookDao.selectList(null);
List<DeviceAddressBookEntity> allRecords = assignUniqueAliases(deviceAddressBookDao.selectList(null));
Map<String, String> reverseMap = new HashMap<>();
for (DeviceAddressBookEntity entity : allRecords) {
String macA = entity.getMacAddress().toLowerCase();
String macB = entity.getTargetMac().toLowerCase();
String alias = entity.getAlias();
Boolean hasPermission = entity.getHasPermission();
String macA = bookKey(entity.getMacAddress());
String macB = bookKey(entity.getTargetMac());
// 构建正向映射: A对B的映射 nickname -> macB|permission
if (alias != null && !alias.isEmpty()) {
result.computeIfAbsent(macA, k -> new HashMap<>());
String permStr = (hasPermission != null && hasPermission) ? "1" : "0";
result.get(macA).put(alias, macB + "|" + permStr);
}
Map<String, String> book = result.computeIfAbsent(macA, k -> new HashMap<>());
String permStr = (Boolean.TRUE.equals(entity.getHasPermission())) ? "1" : "0";
book.put(entity.getAlias(), macB + "|" + permStr);
// 构建反向记录用于查找B对A的称呼
if (alias != null && !alias.isEmpty()) {
reverseMap.put(macB + ":" + macA, alias);
}
// 构建反向记录用于查找B对A的称呼,用同一个去重后的名字,两边才对得上
reverseMap.put(macB + ":" + macA, entity.getAlias());
}
// 构建反向映射: B对A的映射 macA -> nickname
for (DeviceAddressBookEntity entity : allRecords) {
String macA = entity.getMacAddress().toLowerCase();
String macB = entity.getTargetMac().toLowerCase();
String macA = bookKey(entity.getMacAddress());
String macB = bookKey(entity.getTargetMac());
String aliasBtoA = reverseMap.get(macA + ":" + macB);
if (aliasBtoA != null && !aliasBtoA.isEmpty()) {
result.computeIfAbsent(macB, k -> new HashMap<>());
@ -136,6 +146,54 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
redisUtils.set(RedisKeys.getAddressBookKey(), result);
}
/**
* 给每行算出一个不重名的称呼,返回排好序、alias 已写好的新列表
*
* 昵称在同一个人的通讯录里是索引,同名后写的会盖掉先写的,按昵称呼会呼错设备。
* 库里本来就有重名:空别名补出来的尾号称呼只有 256 种取值,一本通讯录十几条
* 没起名就撞上了。所以显示和呼叫都得走这一份,
* 不然前端看到的字和呼叫时用的名字对不上,用户照着点的名字呼不到人。
* 不改传入的那个列表:它是 DAO 刚查出来的,调用方还要按自己的顺序用
*/
private List<DeviceAddressBookEntity> assignUniqueAliases(List<DeviceAddressBookEntity> rows) {
// 取名要靠先后定谁拿原名,而 selectList 不带 order by,返回顺序不保证。
// 排一次,同样的数据每次算出来的结果一样,缓存不会来回变。
// 按归一后的地址排:同一个人不管库里是哪种写法都排到一起,
// 后面两级比较器再分先后。同一本里 target_mac 不会重复(主键摆着),
// 所以顺序还是由这三个键定死的,不会掉回"跟着数据库返回顺序走"
List<DeviceAddressBookEntity> ordered = new ArrayList<>(rows);
ordered.sort(Comparator
.comparing((DeviceAddressBookEntity row) -> bookKey(row.getMacAddress()),
Comparator.nullsFirst(Comparator.naturalOrder()))
// 权限排在地址前面:撞名时让对方准许呼我的那台先拿原名。
// 排在后面等于不起作用,两条地址不同时谁先谁后是地址定的,
// 没权限那条照样占住原名,用户照前端看到的名字呼叫命中的就是它,
// 界面上只会说没权限,怎么点都不通
.thenComparing(DeviceAddressBookEntity::getHasPermission,
Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(DeviceAddressBookEntity::getTargetMac, Comparator.nullsFirst(Comparator.naturalOrder())));
Map<String, Set<String>> takenByOwner = new HashMap<>();
for (DeviceAddressBookEntity row : ordered) {
// 建表时 alias 默认是空的,用户没起名就是空的,这是默认状态不是异常。
// 补个尾号称呼顶上,整条跳过的话接口照样返回成功,对方却再也呼不过来
String alias = StringUtils.isBlank(row.getAlias())
? formatMacAsDeviceName(row.getTargetMac())
: row.getAlias();
// 加后缀的写法跟 generateUniqueAlias 保持一致,不搞两套命名规则
Set<String> taken = takenByOwner.computeIfAbsent(bookKey(row.getMacAddress()), k -> new HashSet<>());
String uniqueAlias = alias;
int suffix = 1;
while (taken.contains(uniqueAlias)) {
uniqueAlias = alias + suffix++;
}
taken.add(uniqueAlias);
row.setAlias(uniqueAlias);
}
return ordered;
}
@Override
public void updateAlias(String macAddress, String targetMac, String alias) {
String finalAlias = generateUniqueAlias(macAddress, targetMac, alias);
@ -154,14 +212,29 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
QueryWrapper<DeviceAddressBookEntity> wrapper = new QueryWrapper<>();
wrapper.eq("mac_address", macAddress).eq("target_mac", targetMac);
DeviceAddressBookEntity record = deviceAddressBookDao.selectOne(wrapper);
System.out.println("saveOrUpdate - mac=" + macAddress + ", targetMac=" + targetMac + ", alias=" + alias + ", record=" + (record == null ? "null" : "not null"));
if (record == null) {
DeviceAddressBookEntity entity = new DeviceAddressBookEntity();
entity.setMacAddress(macAddress);
entity.setTargetMac(targetMac);
// 如果 alias 为空,就默认使用设备名称
// 调用方没起名就退回尾号称呼。对方设备在智控台上起的名字是对方的私产,
// 抄进调用方的通讯录等于把别人的昵称漏出去,所以别人的设备一律不去设备表取名
if (StringUtils.isBlank(alias)) {
alias = deviceService.getDeviceByMacAddress(targetMac).getAlias();
// 只有给自己那台设备起名时才用设备表里的名字,那本来就是调用方自己的
if (isOwnDevice(macAddress, targetMac)) {
// 用带归属校验的那个查法。设备表里同一个 MAC 可能有两行只差大小写,
// 一次只准取一条的那种查法撞上这种数据会抛 TooManyResultsException,
// 整个保存接口带崩;按 id 取第一条,撞行也不报错
DeviceEntity ownDevice = deviceService.getOwnedDeviceByMacAddress(macAddress);
if (ownDevice != null && StringUtils.isNotBlank(ownDevice.getAlias())) {
alias = ownDevice.getAlias();
}
}
// 设备登记了但用户没起过名,alias 建表就是 null,这是默认状态
// 不是异常。这时候落个 null 进去,缓存刷新会把整条跳过,
// 接口照样返回成功,对方却永远呼不过来
if (StringUtils.isBlank(alias)) {
alias = formatMacAsDeviceName(targetMac);
}
}
// 检查重名
alias = generateUniqueAlias(macAddress, targetMac, alias);
@ -229,11 +302,37 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
}
}
/**
* 通讯录里当主人用的地址键
*
* <p>
* 写缓存、查缓存、算称呼都靠它分组,三处必须是同一个值。少归一一次,同一个人的两行
* 会被当成两个人:各自拿到同名,写进同一本时后者盖掉前者,一台设备直接从缓存里消失。
* 库里确实能出现这种数据——表是 utf8mb4_0900_ai_ci,主键 (mac_address, target_mac)
* 大小写不敏感,owner 只差大小写而 target 不同的话两行不撞
*/
private static String bookKey(String macAddress) {
return macAddress == null ? null : macAddress.toLowerCase();
}
/**
* 目标设备是不是调用方自己那台
*
* <p>
* MAC 不区分大小写,比较前先按通讯录的键归一化,跟别处的比较口径保持一致
*/
private static boolean isOwnDevice(String macAddress, String targetMac) {
return bookKey(macAddress) != null && bookKey(macAddress).equals(bookKey(targetMac));
}
private String formatMacAsDeviceName(String mac) {
if (StringUtils.isBlank(mac) || mac.length() < 2) {
return mac;
}
String lastTwo = mac.substring(mac.length() - 2);
// MAC 本身不区分大小写,落库、查库走的都是小写化的值。
// 这里跟着小写化,不跟着的话同一个地址在两条路径上会算出两个称呼,
// 数据搬到智控台上看到的名字就叫不到人了
String lastTwo = mac.substring(mac.length() - 2).toLowerCase();
return "尾号为" + lastTwo + "的设备";
}

View file

@ -316,6 +316,12 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
if (device == null) {
return;
}
// 后面删通讯录那步是按 mac_address 删的,不看 user_id。
// 设备本身因为带了 user_id 条件删不掉,通讯录却会照删不误,
// 任意登录用户知道对方的设备 id 就能把对方整本通讯录清空
if (userId == null || device.getUserId() == null || !device.getUserId().equals(userId)) {
return;
}
String macAddress = device.getMacAddress();
if (StringUtils.isNotBlank(device.getAgentId())) {
// 清除智能体设备数量缓存
@ -400,6 +406,29 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
return baseDao.selectOne(wrapper);
}
@Override
public DeviceEntity getOwnedDeviceByMacAddress(String macAddress) {
if (StringUtils.isBlank(macAddress)) {
return null;
}
// 同一 MAC 可能有两行只差大小写,selectOne 会抛 TooManyResultsException
// 把整个读通讯录接口带崩。按 id 取第一条做归属校验,撞行不报错
QueryWrapper<DeviceEntity> wrapper = new QueryWrapper<>();
wrapper.eq("mac_address", macAddress).orderByAsc("id");
List<DeviceEntity> devices = baseDao.selectList(wrapper);
if (devices == null || devices.isEmpty()) {
return null;
}
DeviceEntity device = devices.get(0);
UserDetail user = SecurityUser.getUser();
// getUser() 在取不到 subject、principal 时返回的是空对象,不是 null,
// 所以这里不会拿到 null。匿名调用走的就是空对象那一条,id 是空的,比不上
if (device.getUserId() == null || !device.getUserId().equals(user.getId())) {
return null;
}
return device;
}
private DeviceReportRespDTO.ServerTime buildServerTime() {
DeviceReportRespDTO.ServerTime serverTime = new DeviceReportRespDTO.ServerTime();
TimeZone tz = TimeZone.getDefault();

View file

@ -64,6 +64,37 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
private static final String DEFAULT_TITLE_PROMPT = "请根据以下对话内容,生成一个简洁的会话标题(约15字以内),只返回标题,不要包含任何解释或标点符号:\n{conversation}";
/**
* Ollama的OpenAI兼容端点位于{base_url}/v1下,与xiaozhi-server侧ollama provider逻辑保持一致:
* 先去尾斜杠、再剥离用户误填的完整端点后缀,仅对不含路径的纯主机地址补/v1。
* 空串返回null,交由上层"配置不完整"必填校验拦截
*/
private static String normalizeOllamaBaseUrl(String baseUrl) {
if (baseUrl == null) {
return null;
}
String url = baseUrl.trim();
if (url.isEmpty()) {
return null;
}
while (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
if (url.endsWith("/chat/completions")) {
url = url.substring(0, url.length() - "/chat/completions".length());
while (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
}
if (url.isEmpty()) {
return null;
}
if (url.replaceFirst("^https?://[^/]+", "").isEmpty()) {
url = url + "/v1";
}
return url;
}
@Override
public String generateSummary(String conversation) {
return generateSummary(conversation, null, null);
@ -101,6 +132,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String baseUrl = configJson.getStr("base_url");
String model = configJson.getStr("model_name");
String apiKey = configJson.getStr("api_key");
if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) {
baseUrl = normalizeOllamaBaseUrl(baseUrl);
// Ollama免鉴权:未填api_key时兜底为"ollama",与xiaozhi-server侧ollama.py一致
if (StringUtils.isBlank(apiKey)) {
apiKey = "ollama";
}
}
Double temperature = configJson.getDouble("temperature");
Integer maxTokens = configJson.getInt("max_tokens");
@ -196,6 +234,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String baseUrl = configJson.getStr("base_url");
String model = configJson.getStr("model_name");
String apiKey = configJson.getStr("api_key");
if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) {
baseUrl = normalizeOllamaBaseUrl(baseUrl);
// Ollama免鉴权:未填api_key时兜底为"ollama",与xiaozhi-server侧ollama.py一致
if (StringUtils.isBlank(apiKey)) {
apiKey = "ollama";
}
}
if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
log.error("LLM配置不完整,baseUrl或apiKey为空");
@ -271,8 +316,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String baseUrl = configJson.getStr("base_url");
String apiKey = configJson.getStr("api_key");
// Ollama免鉴权:不要求api_key
boolean ollama = "ollama".equalsIgnoreCase(configJson.getStr("type"));
return baseUrl != null && !baseUrl.trim().isEmpty() &&
apiKey != null && !apiKey.trim().isEmpty();
(ollama || (apiKey != null && !apiKey.trim().isEmpty()));
} catch (Exception e) {
log.error("检查LLM服务可用性时发生异常:", e);
return false;
@ -297,8 +344,10 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String baseUrl = configJson.getStr("base_url");
String apiKey = configJson.getStr("api_key");
// Ollama免鉴权:不要求api_key
boolean ollama = "ollama".equalsIgnoreCase(configJson.getStr("type"));
return baseUrl != null && !baseUrl.trim().isEmpty() &&
apiKey != null && !apiKey.trim().isEmpty();
(ollama || (apiKey != null && !apiKey.trim().isEmpty()));
} catch (Exception e) {
log.error("检查LLM服务可用性时发生异常,modelId: {}", modelId, e);
return false;
@ -354,6 +403,13 @@ public class OpenAIStyleLLMServiceImpl implements LLMService {
String baseUrl = configJson.getStr("base_url");
String model = configJson.getStr("model_name");
String apiKey = configJson.getStr("api_key");
if ("ollama".equalsIgnoreCase(configJson.getStr("type"))) {
baseUrl = normalizeOllamaBaseUrl(baseUrl);
// Ollama免鉴权:未填api_key时兜底为"ollama",与xiaozhi-server侧ollama.py一致
if (StringUtils.isBlank(apiKey)) {
apiKey = "ollama";
}
}
if (StringUtils.isBlank(baseUrl) || StringUtils.isBlank(apiKey)) {
log.error("LLM配置不完整,baseUrl或apiKey为空");

View file

@ -110,8 +110,8 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
// 1. 参数验证
validateEditParameters(modelType, provideCode, id, modelConfigBodyDTO);
// 2. 验证模型提供者
validateModelProvider(modelType, provideCode);
// 2. 验证模型提供者,使用注册类型的大小写
String registeredModelType = resolveModelType(modelType, provideCode);
// 3. 获取原始配置(不经过敏感数据处理)
ModelConfigEntity originalEntity = getOriginalConfigFromDb(id);
@ -120,7 +120,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
validateLlmConfiguration(modelConfigBodyDTO);
// 5. 准备更新实体并处理敏感数据
ModelConfigEntity modelConfigEntity = prepareUpdateEntity(modelConfigBodyDTO, originalEntity, modelType, id);
ModelConfigEntity modelConfigEntity = prepareUpdateEntity(modelConfigBodyDTO, originalEntity, registeredModelType, id);
// 6. 执行数据库更新
modelConfigDao.updateById(modelConfigEntity);
@ -136,9 +136,9 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
public ModelConfigDTO add(String modelType, String provideCode, ModelConfigBodyDTO modelConfigBodyDTO) {
validateAddParameters(modelType, provideCode, modelConfigBodyDTO);
validateModelProvider(modelType, provideCode);
String registeredModelType = resolveModelType(modelType, provideCode);
ModelConfigEntity modelConfigEntity = prepareAddEntity(modelConfigBodyDTO, modelType);
ModelConfigEntity modelConfigEntity = prepareAddEntity(modelConfigBodyDTO, registeredModelType);
modelConfigDao.insert(modelConfigEntity);
@ -283,13 +283,14 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
}
/**
* 验证模型提供者
* 验证模型提供者并获取注册类型,保留 TTS、Memory、Intent 等类型的大小写
*/
private void validateModelProvider(String modelType, String provideCode) {
private String resolveModelType(String modelType, String provideCode) {
List<ModelProviderDTO> providerList = modelProviderService.getList(modelType, provideCode);
if (CollectionUtil.isEmpty(providerList)) {
throw new RenException(ErrorCode.MODEL_PROVIDER_NOT_EXIST);
}
return providerList.get(0).getModelType();
}
/**

View file

@ -86,6 +86,7 @@ public class ShiroConfig {
filterMap.put("/user/captcha", "anon");
filterMap.put("/user/smsVerification", "anon");
filterMap.put("/user/login", "anon");
filterMap.put("/user/refresh", "anon");
filterMap.put("/user/pub-config", "anon");
filterMap.put("/user/register", "anon");
filterMap.put("/user/retrieve-password", "anon");

View file

@ -16,6 +16,7 @@ import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -110,6 +111,17 @@ public class LoginController {
return sysUserTokenService.createToken(userDTO.getId());
}
@PostMapping("/refresh")
@Operation(summary = "刷新token:用旧token换新token")
public Result<TokenDTO> refresh(HttpServletRequest request) {
String authorization = request.getHeader(Constant.AUTHORIZATION);
if (StringUtils.isBlank(authorization) || !authorization.startsWith("Bearer ")) {
throw new RenException(ErrorCode.UNAUTHORIZED);
}
String oldToken = authorization.replace("Bearer ", "");
return sysUserTokenService.refreshToken(oldToken);
}
@PostMapping("/register")
@Operation(summary = "注册")
public Result<Void> register(@RequestBody LoginDTO login) {

View file

@ -21,4 +21,14 @@ public interface SysUserTokenDao extends BaseDao<SysUserTokenEntity> {
SysUserTokenEntity getByUserId(Long userId);
void logout(@Param("userId") Long userId, @Param("expireDate") Date expireDate);
/**
* 用旧 token 换新 token 的 CAS 更新:仅当旧 token 未过期且属于指定 user 时才覆盖。
* 返回受影响行数(0 表示条件不满足 = token 已被并发刷新或过期)。
*/
int refreshTokenCAS(@Param("userId") Long userId,
@Param("oldToken") String oldToken,
@Param("newToken") String newToken,
@Param("newExpire") Date newExpire,
@Param("updateDate") Date updateDate);
}

View file

@ -21,6 +21,13 @@ public interface SysUserTokenService extends BaseService<SysUserTokenEntity> {
*/
Result<TokenDTO> createToken(Long userId);
/**
* 用旧token换新token,旧token立即失效
*
* @param oldToken 旧token字符串
*/
Result<TokenDTO> refreshToken(String oldToken);
SysUserDTO getUserByToken(String token);
/**

View file

@ -2,7 +2,9 @@ package xiaozhi.modules.security.service.impl;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.date.DateUtil;
import lombok.AllArgsConstructor;
@ -81,6 +83,36 @@ public class SysUserTokenServiceImpl extends BaseServiceImpl<SysUserTokenDao, Sy
return new Result<TokenDTO>().ok(tokenDTO);
}
@Override
@Transactional
public Result<TokenDTO> refreshToken(String oldToken) {
if (StringUtils.isBlank(oldToken)) {
throw new RenException(ErrorCode.UNAUTHORIZED);
}
SysUserTokenEntity tokenEntity = baseDao.getByToken(oldToken);
if (tokenEntity == null) {
throw new RenException(ErrorCode.TOKEN_INVALID);
}
if (tokenEntity.getExpireDate().before(new Date())) {
throw new RenException(ErrorCode.UNAUTHORIZED);
}
// CAS 更新:并发场景下只有一个请求能匹配到该 oldToken,另一个返 0 行
String newToken = TokenGenerator.generateValue();
Date now = new Date();
Date expireTime = new Date(now.getTime() + EXPIRE * 1000L);
int affected = baseDao.refreshTokenCAS(tokenEntity.getUserId(), oldToken, newToken, expireTime, now);
if (affected == 0) {
throw new RenException(ErrorCode.TOKEN_INVALID);
}
TokenDTO dto = new TokenDTO();
dto.setToken(newToken);
dto.setExpire(EXPIRE);
dto.setClientHash(HttpContextUtils.getClientCode());
return new Result<TokenDTO>().ok(dto);
}
@Override
public SysUserDTO getUserByToken(String token) {
SysUserTokenEntity userToken = baseDao.getByToken(token);

View file

@ -0,0 +1,4 @@
-- 添加MCP接入点附带说话人身份的开关参数配置
delete from `sys_params` where param_code = 'mcp_forward_speaker';
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark)
VALUES (313, 'mcp_forward_speaker', 'true', 'boolean', 1, '是否随MCP调用附带说话人身份');

View file

@ -0,0 +1,17 @@
-- Ollama LLM配置补充api_key占位值,走鉴权网关/Ollama Cloud时使用
UPDATE `ai_model_config`
SET `config_json` = JSON_SET(`config_json`, '$.api_key', 'ollama')
WHERE `id` = 'LLM_OllamaLLM' AND JSON_EXTRACT(`config_json`, '$.api_key') IS NULL;
-- Ollama供应商追加api_key字段定义,password类型
UPDATE `ai_model_provider`
SET `fields` = JSON_ARRAY_APPEND(COALESCE(`fields`, JSON_ARRAY()), '$',
JSON_OBJECT('key', 'api_key', 'label', 'API密钥', 'type', 'password'))
WHERE `id` = 'SYSTEM_LLM_ollama'
AND JSON_SEARCH(`fields`, 'one', 'api_key', NULL, '$[*].key') IS NULL;
-- 配置说明补充api_key条目
UPDATE `ai_model_config`
SET `remark` = CONCAT(`remark`, '\n4. 走鉴权网关或使用Ollama Cloud时,需填写api_key')
WHERE `id` = 'LLM_OllamaLLM'
AND `remark` IS NOT NULL AND `remark` NOT LIKE '%api_key%';

View file

@ -0,0 +1,22 @@
-- PaddleSpeechTTS:智控台协议收敛为仅 websocket(与 xiaozhi-server 实现一致)
UPDATE `ai_model_provider`
SET `fields` = JSON_ARRAY(
JSON_OBJECT('key', 'protocol', 'label', '协议类型', 'type', 'string', 'options', JSON_ARRAY('websocket')),
JSON_OBJECT('key', 'url', 'label', '服务地址', 'type', 'string'),
JSON_OBJECT('key', 'spk_id', 'label', '音色', 'type', 'int'),
JSON_OBJECT('key', 'sample_rate', 'label', '采样率', 'type', 'float'),
JSON_OBJECT('key', 'speed', 'label', '语速', 'type', 'float'),
JSON_OBJECT('key', 'volume', 'label', '音量', 'type', 'float'),
JSON_OBJECT('key', 'save_path', 'label', '保存路径', 'type', 'string')
)
WHERE `id` = 'SYSTEM_TTS_PaddleSpeechTTS';
UPDATE `ai_model_config`
SET `remark` = 'PaddleSpeechTTS 配置说明:
1. PaddleSpeech 是百度飞桨开源的语音合成工具,支持本地离线部署和模型训练。paddlepaddle百度飞浆框架地址:https://www.paddlepaddle.org.cn/
2. 当前仅支持 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';

View file

@ -0,0 +1,9 @@
-- 联网搜索插件新增Outcrawl搜索源
UPDATE `ai_model_provider`
SET `fields` = JSON_SET(
`fields`,
'$[0].label',
'搜索源:metaso / tavily / serply / outcrawl'
)
WHERE `id` = 'SYSTEM_PLUGIN_WEB_SEARCH';

View file

@ -0,0 +1,9 @@
-- 联网搜索插件新增SpecStream搜索源
UPDATE `ai_model_provider`
SET `fields` = JSON_SET(
`fields`,
'$[0].label',
'搜索源:metaso / tavily / serply / outcrawl / specstream'
)
WHERE `id` = 'SYSTEM_PLUGIN_WEB_SEARCH';

View file

@ -0,0 +1,6 @@
-- 为 LLM 的 OpenAI 接口配置表单新增 chat_template_kwargs 字段(dict, 前端映射为 JSON 文本框)
-- 用于向 vLLM/SGLang 等自托管 OpenAI 兼容后端透传 chat template 控制参数(如 enable_thinking)
-- 注意: DashScope 等云服务不识别此字段, 仅供自托管后端使用
UPDATE `ai_model_provider`
SET `fields` = '[{"key":"base_url","label":"基础URL","type":"string"},{"key":"model_name","label":"模型名称","type":"string"},{"key":"api_key","label":"API密钥","type":"string"},{"key":"temperature","label":"温度","type":"number"},{"key":"max_tokens","label":"最大令牌数","type":"number"},{"key":"top_p","label":"top_p值","type":"number"},{"key":"top_k","label":"top_k值","type":"number"},{"key":"frequency_penalty","label":"频率惩罚","type":"number"},{"key":"chat_template_kwargs","label":"模板变量(JSON)","type":"dict"}]'
WHERE `id` = 'SYSTEM_LLM_openai';

View file

@ -753,3 +753,45 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202609172100.sql
- changeSet:
id: 202610261030
author: RanChen
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202610261030.sql
- changeSet:
id: 202610291451
author: RanChen
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202610291451.sql
- changeSet:
id: 202610302051
author: shinjiyu
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202610302051.sql
- changeSet:
id: 202611021200
author: heydryft
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202611021200.sql
- changeSet:
id: 202611101200
author: Specstreamai
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202611101200.sql
- changeSet:
id: 202611181622
author: RanChen
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202611181622.sql

View file

@ -14,4 +14,12 @@
<update id="logout">
update sys_user_token set expire_date = #{expireDate} where user_id = #{userId}
</update>
<update id="refreshTokenCAS">
update sys_user_token
set token = #{newToken}, update_date = #{updateDate}, expire_date = #{newExpire}
where token = #{oldToken}
and expire_date > NOW()
and user_id = #{userId}
</update>
</mapper>

View file

@ -44,7 +44,7 @@ class SensitiveDataUtilsTest {
void maskMiddle_keeps_four_at_each_end_for_long_strings() {
String masked = SensitiveDataUtils.maskMiddle("verylongapikeyvalue123");
assertTrue(masked.startsWith("very"));
assertTrue(masked.endsWith("3123"));
assertTrue(masked.endsWith("e123"));
assertTrue(masked.contains("****"));
assertEquals("verylongapikeyvalue123".length(), masked.length());
}

View file

@ -14,9 +14,14 @@ import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import xiaozhi.modules.agent.dao.AgentCorrectWordMappingDao;
import xiaozhi.modules.agent.entity.AgentCorrectWordMappingEntity;
import xiaozhi.modules.correctword.dao.CorrectWordFileDao;
@ -37,6 +42,20 @@ class CorrectWordFileServiceImplTest {
private final CorrectWordFileServiceImpl service =
new CorrectWordFileServiceImpl(fileDao, itemDao, mappingDao);
@BeforeAll
static void registerEntityMetadata() {
// 这条用例不起 Spring 上下文,MyBatis-Plus 的实体元数据没人注册,
// LambdaQueryWrapper 拼条件时找不到 lambda 缓存就抛异常。
// 全量跑的时候是前面的上下文测试顺带注册好的,单独跑就露馅。
// 这里自己补上,单独跑和跟着全量跑结果一样。
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
CorrectWordItemEntity.class);
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
CorrectWordFileEntity.class);
}
@Test
void getAllItemsByAgentId_returns_empty_list_when_no_mappings() {
when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(Collections.emptyList());

View file

@ -3,6 +3,7 @@ package xiaozhi.modules.device;
import java.util.HashMap;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
@ -15,6 +16,7 @@ import xiaozhi.common.exception.RenException;
import xiaozhi.common.redis.RedisUtils;
import xiaozhi.modules.sys.dto.SysUserDTO;
import xiaozhi.modules.sys.service.SysUserService;
import xiaozhi.testsupport.IntegrationTestEnvironment;
@Slf4j
@SpringBootTest
@ -22,6 +24,11 @@ import xiaozhi.modules.sys.service.SysUserService;
@DisplayName("设备测试")
public class DeviceTest {
@BeforeAll
static void checkDependencies() {
IntegrationTestEnvironment.requireDatabaseAndRedis();
}
@Autowired
private RedisUtils redisUtils;
@Autowired

View file

@ -1,11 +1,15 @@
package xiaozhi.modules.device.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
@ -15,7 +19,10 @@ import xiaozhi.common.redis.RedisUtils;
import xiaozhi.common.user.UserDetail;
import xiaozhi.common.utils.MessageUtils;
import xiaozhi.common.utils.Result;
import xiaozhi.modules.device.dto.DeviceAddressBookAliasDTO;
import xiaozhi.modules.device.dto.DeviceAddressBookPermissionDTO;
import xiaozhi.modules.device.dto.DeviceUpdateDTO;
import xiaozhi.modules.device.entity.DeviceAddressBookEntity;
import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.service.DeviceAddressBookService;
import xiaozhi.modules.device.service.DeviceService;
@ -26,6 +33,8 @@ import xiaozhi.modules.sys.service.SysParamsService;
class DeviceControllerTest {
private static final String DEVICE_ID = "device-id";
private static final String MAC = "00:11:22:33:44:55";
private static final String OTHER_MAC = "00:11:22:33:44:66";
private static final long USER_ID = 1L;
@Test
@ -35,7 +44,7 @@ class DeviceControllerTest {
DeviceEntity entity = ownedDevice();
when(deviceService.selectById(DEVICE_ID)).thenReturn(entity);
when(deviceService.updateById(entity)).thenReturn(false);
DeviceController controller = controller(deviceService);
DeviceController controller = controller(deviceService, mock(DeviceAddressBookService.class));
DeviceUpdateDTO update = new DeviceUpdateDTO();
update.setAutoUpdate(0);
@ -54,10 +63,84 @@ class DeviceControllerTest {
}
}
private DeviceController controller(DeviceService deviceService) {
@Test
@DisplayName("读取他人设备通讯录时一律按设备不存在处理")
void addressBookOfDeviceOwnedByAnotherUserIsRejected() {
DeviceService deviceService = mock(DeviceService.class);
DeviceAddressBookService addressBookService = mock(DeviceAddressBookService.class);
when(deviceService.getOwnedDeviceByMacAddress(OTHER_MAC)).thenReturn(null);
DeviceController controller = controller(deviceService, addressBookService);
try (MockedStatic<MessageUtils> messageUtils = mockStatic(MessageUtils.class)) {
messageUtils.when(() -> MessageUtils.getMessage(ErrorCode.DEVICE_NOT_EXIST))
.thenReturn("Device not exist");
Result<Object> result = controller.getAddressBook(OTHER_MAC);
assertEquals(ErrorCode.DEVICE_NOT_EXIST, result.getCode());
assertNull(result.getData());
verify(addressBookService, never()).getAddressBookList(OTHER_MAC);
}
}
@Test
@DisplayName("读取本机设备通讯录照常返回")
void addressBookOfOwnDeviceIsReturned() {
DeviceService deviceService = mock(DeviceService.class);
DeviceAddressBookService addressBookService = mock(DeviceAddressBookService.class);
List<DeviceAddressBookEntity> entries = List.of(new DeviceAddressBookEntity());
when(deviceService.getOwnedDeviceByMacAddress(MAC)).thenReturn(ownedDevice());
when(addressBookService.getAddressBookList(MAC)).thenReturn(entries);
DeviceController controller = controller(deviceService, addressBookService);
Result<Object> result = controller.getAddressBook(MAC);
assertEquals(0, result.getCode());
assertEquals(entries, result.getData());
}
@Test
@DisplayName("以他人设备名义改别名被拒")
void updateAliasOnDeviceOwnedByAnotherUserIsRejected() {
DeviceService deviceService = mock(DeviceService.class);
DeviceAddressBookService addressBookService = mock(DeviceAddressBookService.class);
when(deviceService.getOwnedDeviceByMacAddress(OTHER_MAC)).thenReturn(null);
DeviceController controller = controller(deviceService, addressBookService);
DeviceAddressBookAliasDTO dto = new DeviceAddressBookAliasDTO();
dto.setMacAddress(OTHER_MAC);
dto.setTargetMac(MAC);
dto.setAlias("office");
Result<Void> result = controller.updateAlias(dto);
assertEquals("无权限操作该设备", result.getMsg());
verify(addressBookService, never()).saveOrUpdate(OTHER_MAC, MAC, "office", null);
}
@Test
@DisplayName("以他人设备名义改权限被拒")
void updatePermissionOnDeviceOwnedByAnotherUserIsRejected() {
DeviceService deviceService = mock(DeviceService.class);
DeviceAddressBookService addressBookService = mock(DeviceAddressBookService.class);
when(deviceService.getOwnedDeviceByMacAddress(OTHER_MAC)).thenReturn(null);
DeviceController controller = controller(deviceService, addressBookService);
DeviceAddressBookPermissionDTO dto = new DeviceAddressBookPermissionDTO();
dto.setMacAddress(OTHER_MAC);
dto.setTargetMac(MAC);
dto.setHasPermission(true);
Result<Void> result = controller.updatePermission(dto);
assertEquals("无权限操作该设备", result.getMsg());
verify(addressBookService, never()).saveOrUpdate(OTHER_MAC, MAC, null, true);
}
private DeviceController controller(DeviceService deviceService, DeviceAddressBookService addressBookService) {
return new DeviceController(
deviceService,
mock(DeviceAddressBookService.class),
addressBookService,
mock(RedisUtils.class),
mock(SysParamsService.class));
}

View file

@ -1,26 +1,49 @@
package xiaozhi.modules.device.service.impl;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
import xiaozhi.common.constant.Constant;
import xiaozhi.common.redis.RedisKeys;
import xiaozhi.common.redis.RedisUtils;
import xiaozhi.modules.device.dao.DeviceAddressBookDao;
import xiaozhi.modules.device.entity.DeviceAddressBookEntity;
import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.modules.sys.service.SysParamsService;
class DeviceAddressBookServiceImplTest {
private static final String MAC = "00:11:22:33:44:55";
private static final String OTHER_MAC = "00:11:22:33:44:66";
private static final String THIRD_MAC = "00:11:22:33:44:77";
// 纯数字的 MAC 大小写化后跟原来一模一样,拿它造不出"只差大小写"的两行
private static final String HEX_MAC = "00:11:22:33:44:ab";
@Test
void newEntryUsesTheDedicatedAddressBookInsertMapping() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
@ -32,15 +55,530 @@ class DeviceAddressBookServiceImplTest {
when(addressBookDao.selectOne(any())).thenReturn(null);
when(addressBookDao.selectList(null)).thenReturn(List.of());
service.saveOrUpdate("00:11:22:33:44:55", "00:11:22:33:44:66", "living-room", true);
service.saveOrUpdate(MAC, OTHER_MAC, "living-room", true);
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
DeviceAddressBookEntity entity = entityCaptor.getValue();
assertEquals("00:11:22:33:44:55", entity.getMacAddress());
assertEquals("00:11:22:33:44:66", entity.getTargetMac());
assertEquals(MAC, entity.getMacAddress());
assertEquals(OTHER_MAC, entity.getTargetMac());
assertEquals("living-room", entity.getAlias());
assertTrue(entity.getHasPermission());
verify(addressBookDao, never()).insert(any(DeviceAddressBookEntity.class));
}
@Test
void blankAliasOnUnregisteredTargetFallsBackToMacSuffix() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
DeviceService deviceService = mock(DeviceService.class);
SysParamsService sysParamsService = mock(SysParamsService.class);
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, deviceService, sysParamsService);
when(addressBookDao.selectOne(any())).thenReturn(null);
when(addressBookDao.selectList(null)).thenReturn(List.of());
when(deviceService.getOwnedDeviceByMacAddress(anyString())).thenReturn(null);
service.saveOrUpdate(MAC, OTHER_MAC, null, true);
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
DeviceAddressBookEntity entity = entityCaptor.getValue();
assertNotNull(entity.getAlias());
assertEquals("尾号为66的设备", entity.getAlias());
assertTrue(entity.getHasPermission());
verify(deviceService, never()).getOwnedDeviceByMacAddress(anyString());
}
@Test
void blankAliasOnAnotherDeviceFallsBackToMacSuffixWithoutAskingTheDeviceTable() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
DeviceService deviceService = mock(DeviceService.class);
SysParamsService sysParamsService = mock(SysParamsService.class);
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, deviceService, sysParamsService);
when(addressBookDao.selectOne(any())).thenReturn(null);
when(addressBookDao.selectList(null)).thenReturn(List.of());
DeviceEntity registered = new DeviceEntity();
registered.setMacAddress(OTHER_MAC);
registered.setAlias(null);
when(deviceService.getDeviceByMacAddress(OTHER_MAC)).thenReturn(registered);
when(deviceService.getOwnedDeviceByMacAddress(OTHER_MAC)).thenReturn(registered);
service.saveOrUpdate(MAC, OTHER_MAC, null, true);
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
assertEquals("尾号为66的设备", entityCaptor.getValue().getAlias(),
"登记了但没起名的设备落个空名,缓存刷新会跳过这条,对方永远呼不过来");
verify(deviceService, never()).getDeviceByMacAddress(anyString());
verify(deviceService, never()).getOwnedDeviceByMacAddress(anyString());
}
@Test
void blankAliasOnRegisteredTargetDoesNotTakeOverTheirNickname() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
DeviceService deviceService = mock(DeviceService.class);
SysParamsService sysParamsService = mock(SysParamsService.class);
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, deviceService, sysParamsService);
when(addressBookDao.selectOne(any())).thenReturn(null);
when(addressBookDao.selectList(null)).thenReturn(List.of());
DeviceEntity theirs = new DeviceEntity();
theirs.setMacAddress(OTHER_MAC);
theirs.setAlias("老王的音响");
when(deviceService.getDeviceByMacAddress(OTHER_MAC)).thenReturn(theirs);
when(deviceService.getOwnedDeviceByMacAddress(OTHER_MAC)).thenReturn(theirs);
service.saveOrUpdate(MAC, OTHER_MAC, null, true);
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
assertEquals("尾号为66的设备", entityCaptor.getValue().getAlias(),
"对方在智控台上给这台设备起的名字被抄进了调用方的通讯录");
verify(deviceService, never()).getDeviceByMacAddress(anyString());
verify(deviceService, never()).getOwnedDeviceByMacAddress(anyString());
}
@Test
void blankAliasOnOwnDeviceUsesTheNameFromItsOwnDeviceRow() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
DeviceService deviceService = mock(DeviceService.class);
SysParamsService sysParamsService = mock(SysParamsService.class);
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, deviceService, sysParamsService);
when(addressBookDao.selectOne(any())).thenReturn(null);
when(addressBookDao.selectList(null)).thenReturn(List.of());
DeviceEntity mine = new DeviceEntity();
mine.setMacAddress(MAC);
mine.setAlias("我的书房");
when(deviceService.getOwnedDeviceByMacAddress(MAC)).thenReturn(mine);
service.saveOrUpdate(MAC, MAC, null, true);
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
assertEquals("我的书房", entityCaptor.getValue().getAlias(),
"给自己那台设备起名,用的就是自己设备表里的名字");
}
@Test
void ownDeviceWithoutAliasInDeviceTableFallsBackToMacSuffix() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
DeviceService deviceService = mock(DeviceService.class);
SysParamsService sysParamsService = mock(SysParamsService.class);
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, deviceService, sysParamsService);
when(addressBookDao.selectOne(any())).thenReturn(null);
when(addressBookDao.selectList(null)).thenReturn(List.of());
DeviceEntity mine = new DeviceEntity();
mine.setMacAddress(MAC);
mine.setAlias(null);
when(deviceService.getOwnedDeviceByMacAddress(MAC)).thenReturn(mine);
service.saveOrUpdate(MAC, MAC, null, true);
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
assertEquals("尾号为55的设备", entityCaptor.getValue().getAlias(),
"自己的设备在设备表里也没起名,落个空名的话缓存刷新会跳过这条");
}
@Test
void duplicateDeviceRowsDifferingOnlyInCaseDoNotBreakNaming() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
DeviceService deviceService = mock(DeviceService.class);
SysParamsService sysParamsService = mock(SysParamsService.class);
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, deviceService, sysParamsService);
when(addressBookDao.selectOne(any())).thenReturn(null);
when(addressBookDao.selectList(null)).thenReturn(List.of());
// 设备表里同一个 MAC 有两行只差大小写,一次只准取一条的那种查法会直接抛异常
when(deviceService.getDeviceByMacAddress(anyString()))
.thenThrow(new TooManyResultsException("selectOne 撞上两行只差大小写的数据"));
DeviceEntity first = new DeviceEntity();
first.setMacAddress(MAC);
first.setAlias("我的书房");
when(deviceService.getOwnedDeviceByMacAddress(MAC)).thenReturn(first);
assertDoesNotThrow(() -> service.saveOrUpdate(MAC, MAC, null, true),
"同 MAC 有两行只差大小写时,取名不能把整个接口带崩");
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
assertEquals("我的书房", entityCaptor.getValue().getAlias(),
"撞行时按 id 取第一条那条的名字");
}
@Test
void ownDeviceIsRecognizedWhateverCaseTheAddressIsWrittenIn() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
DeviceService deviceService = mock(DeviceService.class);
SysParamsService sysParamsService = mock(SysParamsService.class);
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, deviceService, sysParamsService);
when(addressBookDao.selectOne(any())).thenReturn(null);
when(addressBookDao.selectList(null)).thenReturn(List.of());
DeviceEntity mine = new DeviceEntity();
mine.setMacAddress(HEX_MAC);
mine.setAlias("我的书房");
when(deviceService.getOwnedDeviceByMacAddress(HEX_MAC)).thenReturn(mine);
service.saveOrUpdate(HEX_MAC, HEX_MAC.toUpperCase(), null, true);
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
assertEquals("我的书房", entityCaptor.getValue().getAlias(),
"同一个地址写成大小写两种样子,就被当成别人的设备了");
}
@Test
void explicitAliasIsKeptAsIs() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
DeviceService deviceService = mock(DeviceService.class);
SysParamsService sysParamsService = mock(SysParamsService.class);
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, deviceService, sysParamsService);
when(addressBookDao.selectOne(any())).thenReturn(null);
when(addressBookDao.selectList(null)).thenReturn(List.of());
service.saveOrUpdate(MAC, OTHER_MAC, "客厅", true);
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
assertEquals("客厅", entityCaptor.getValue().getAlias(),
"自己给别人的设备起名是通讯录的本意,不能被兜底逻辑改掉");
verify(deviceService, never()).getDeviceByMacAddress(anyString());
verify(deviceService, never()).getOwnedDeviceByMacAddress(anyString());
}
@Test
void blankAliasOnUnregisteredTargetDoesNotBlowUp() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
DeviceService deviceService = mock(DeviceService.class);
SysParamsService sysParamsService = mock(SysParamsService.class);
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, deviceService, sysParamsService);
when(addressBookDao.selectOne(any())).thenReturn(null);
when(addressBookDao.selectList(null)).thenReturn(List.of());
when(deviceService.getOwnedDeviceByMacAddress(anyString())).thenReturn(null);
assertDoesNotThrow(() -> service.saveOrUpdate(MAC, OTHER_MAC, null, true),
"目标设备没登记时接口得正常返回,不能抛异常");
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
assertEquals("尾号为66的设备", entityCaptor.getValue().getAlias());
}
@Test
void refreshCacheKeepsEntriesWhoseAliasWasNeverFilledIn() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
when(addressBookDao.selectList(null)).thenReturn(List.of(row(MAC, OTHER_MAC, null)));
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
service.refreshCache();
Map<String, String> book = cachedBook(service, redisUtils).get(MAC);
assertNotNull(book, "空别名整条被跳过,这条设备就再也呼不过来了");
assertEquals(OTHER_MAC + "|1", book.get("尾号为66的设备"));
}
@Test
void refreshCacheDisambiguatesTwoEntriesSharingAnAlias() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
when(addressBookDao.selectList(null)).thenReturn(List.of(
row(MAC, OTHER_MAC, "客厅"),
row(MAC, THIRD_MAC, "客厅")));
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
service.refreshCache();
Map<String, String> book = cachedBook(service, redisUtils).get(MAC);
assertEquals(2, book.size(), "撞名的两台设备只留得下一台:" + book);
assertEquals(OTHER_MAC + "|1", book.get("客厅"));
assertEquals(THIRD_MAC + "|1", book.get("客厅1"));
}
@Test
void refreshCacheGivesTheSameResultWhateverOrderRowsComeBackIn() {
DeviceAddressBookEntity first = row(MAC, OTHER_MAC, "客厅");
DeviceAddressBookEntity second = row(MAC, THIRD_MAC, "客厅");
Map<String, String> inOrder = refreshAndRead(List.of(first, second));
Map<String, String> reversed = refreshAndRead(List.of(second, first));
assertEquals(inOrder, reversed, "同样的数据两次刷新结果不一样,缓存里的称呼会来回变");
}
/**
* 库里能同时存在两条 owner 只差大小写的行:表是 utf8mb4_0900_ai_ci,
* 主键 (mac_address, target_mac) 大小写不敏感,target 不同就不会撞。
* 这是同一个人,算称呼和写缓存都得按小写归成一本
*/
@Test
void ownersDifferingOnlyInCaseShareOneBook() {
String upper = HEX_MAC.toUpperCase();
assertNotEquals(HEX_MAC, upper, "这个用例得真的造出大小写差异才有效");
Map<String, Map<String, String>> books = refreshAndReadAll(List.of(
row(upper, OTHER_MAC, "客厅"),
row(HEX_MAC, THIRD_MAC, "客厅")));
Map<String, String> book = books.get(HEX_MAC);
assertNotNull(book, "同一个人被算成了两个人:" + books.keySet());
assertEquals(2, book.size(), "两台设备只剩一台,另一台从缓存里消失了:" + book);
assertEquals(OTHER_MAC + "|1", book.get("客厅"));
assertEquals(THIRD_MAC + "|1", book.get("客厅1"));
assertEquals(1, books.size(), "两种写法的地址被拆成了两本:" + books.keySet());
}
@Test
void listAndCacheAgreeWhenOwnersDifferOnlyInCase() {
String upper = HEX_MAC.toUpperCase();
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
when(addressBookDao.getAddressBookList(upper)).thenReturn(new ArrayList<>(List.of(
row(upper, OTHER_MAC, "客厅"), row(HEX_MAC, THIRD_MAC, "客厅"))));
when(addressBookDao.selectList(null)).thenReturn(List.of(
row(upper, OTHER_MAC, "客厅"), row(HEX_MAC, THIRD_MAC, "客厅")));
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
Map<String, String> shownToConsole = namesByTargetMac(service.getAddressBookList(upper));
assertEquals(2, shownToConsole.size(),
"接口按原值分组,同一个人的两台设备被算成一个,前端只能看到一台:" + shownToConsole);
service.refreshCache();
Map<String, String> callableNames = new HashMap<>();
cachedBook(service, redisUtils).get(HEX_MAC)
.forEach((name, macAndPerm) -> callableNames.put(name, macAndPerm.split("\\|")[0]));
assertEquals(shownToConsole, callableNames,
"接口按原值分组、缓存按小写分组,用户照前端看到的名字呼,命中的不是同一台设备");
}
@Test
void nameAssignmentDoesNotDependOnWhichSpellingOfTheOwnerCameBack() {
String upper = HEX_MAC.toUpperCase();
Map<String, String> expected = Map.of("客厅", OTHER_MAC + "|1", "客厅1", THIRD_MAC + "|1");
Map<String, String> lowerFirst = refreshAndRead(HEX_MAC, List.of(
row(HEX_MAC, OTHER_MAC, "客厅"), row(upper, THIRD_MAC, "客厅")));
Map<String, String> upperFirst = refreshAndRead(HEX_MAC, List.of(
row(upper, THIRD_MAC, "客厅"), row(HEX_MAC, OTHER_MAC, "客厅")));
assertEquals(expected, lowerFirst,
"同一个人的称呼取决于库里哪种写法先返回,刷新一次就换一次名字");
assertEquals(expected, upperFirst, "顺序反过来结果就该不一样:" + upperFirst);
}
@SuppressWarnings("unchecked")
private Map<String, Map<String, String>> refreshAndReadAll(List<DeviceAddressBookEntity> rows) {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
when(addressBookDao.selectList(null)).thenReturn(rows);
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
service.refreshCache();
return cachedBook(service, redisUtils);
}
private Map<String, String> refreshAndRead(List<DeviceAddressBookEntity> rows) {
return refreshAndRead(MAC, rows);
}
private Map<String, String> refreshAndRead(String owner, List<DeviceAddressBookEntity> rows) {
return refreshAndReadAll(rows).get(owner);
}
@SuppressWarnings("unchecked")
private Map<String, Map<String, String>> cachedBook(DeviceAddressBookServiceImpl service, RedisUtils redisUtils) {
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
verify(redisUtils).set(eq(RedisKeys.getAddressBookKey()), captor.capture());
return (Map<String, Map<String, String>>) captor.getValue();
}
private DeviceAddressBookEntity row(String macAddress, String targetMac, String alias) {
return row(macAddress, targetMac, alias, Boolean.TRUE);
}
private DeviceAddressBookEntity row(String macAddress, String targetMac, String alias, Boolean hasPermission) {
DeviceAddressBookEntity entity = new DeviceAddressBookEntity();
entity.setMacAddress(macAddress);
entity.setTargetMac(targetMac);
entity.setAlias(alias);
entity.setHasPermission(hasPermission);
return entity;
}
@Test
void listAndCacheHandOutTheSameNameForCollidingEntries() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
// 两次 DAO 调用各给一份新行:取名会写回实体,共用同一份的话第二遍读到的是算过的名字
// 用可变列表,跟 MyBatis 实际返回的一致,免得排序那步先炸掉、断言根本没跑到
when(addressBookDao.getAddressBookList(MAC)).thenReturn(
new ArrayList<>(List.of(row(MAC, OTHER_MAC, "客厅"), row(MAC, THIRD_MAC, "客厅"))));
when(addressBookDao.selectList(null)).thenReturn(List.of(
row(MAC, OTHER_MAC, "客厅"), row(MAC, THIRD_MAC, "客厅")));
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
Map<String, String> shownToConsole = namesByTargetMac(service.getAddressBookList(MAC));
service.refreshCache();
Map<String, String> callableNames = new HashMap<>();
cachedBook(service, redisUtils).get(MAC)
.forEach((name, macAndPerm) -> callableNames.put(name, macAndPerm.split("\\|")[0]));
assertEquals(callableNames, shownToConsole,
"接口和缓存给的是两个名字,用户照前端看到的那个名字呼叫,命中的不是同一台设备");
}
@Test
void theCallableEntryKeepsThePlainNameWhenTwoCollide() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
// OTHER_MAC 的 target_mac 排在前面,没权限的那条会先占住原名
when(addressBookDao.selectList(null)).thenReturn(List.of(
row(MAC, OTHER_MAC, "客厅", Boolean.FALSE),
row(MAC, THIRD_MAC, "客厅", Boolean.TRUE)));
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
service.refreshCache();
Map<String, String> book = cachedBook(service, redisUtils).get(MAC);
assertEquals(THIRD_MAC + "|1", book.get("客厅"),
"能呼的那台被挤到后缀名上了,用户照前端看到的名字点,界面只会说没权限");
assertEquals(OTHER_MAC + "|0", book.get("客厅1"));
}
@Test
void listFillsInBlankAliasesSoTheConsoleShowsWhatCanBeCalled() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
when(addressBookDao.getAddressBookList(MAC)).thenReturn(new ArrayList<>(List.of(row(MAC, OTHER_MAC, null))));
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
List<DeviceAddressBookEntity> rows = service.getAddressBookList(MAC);
assertEquals("尾号为66的设备", rows.get(0).getAlias(),
"空别名原样返回的话前端回落显示设备名,用户照着那个名字呼叫却只会说找不到备注");
}
@Test
void anUppercaseMacGetsTheSameNameWhicheverPathAddsItToTheBook() {
// 兜底称呼只有这一处算法:存进去的时候算一次,之后接口和缓存里显示的
// 都是同一个字符串。不跟着小写化的话同一个地址在两条路径上算出两个称呼,
// 用户照着看到的名字呼过去,命中的不是自己刚存的那台
//
// 运行期这一侧:saveOrUpdate 传的是 DTO 原样过来的地址,大小写没归一
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
DeviceService deviceService = mock(DeviceService.class);
when(addressBookDao.selectOne(any())).thenReturn(null);
when(addressBookDao.selectList(null)).thenReturn(List.of());
when(deviceService.getOwnedDeviceByMacAddress(anyString())).thenReturn(null);
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, deviceService, mock(SysParamsService.class));
service.saveOrUpdate(MAC, "ff:ee:dd:cc:bb:AB", null, true);
ArgumentCaptor<DeviceAddressBookEntity> entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
assertEquals("尾号为ab的设备", entityCaptor.getValue().getAlias(),
"MAC 大小写不区分,末尾两位要跟着小写化,否则接口和呼叫那边算出来的称呼对不上");
}
/**
* 接口按最近改过的排前面
*
* <p>
* 智控台那条 Vue 是按 targetMac 把 alias 合进 allDevices 的,接口顺序被丢掉了,
* 这条现在对 console 没有效果。用例留着是把这个契约钉住:哪天当无用代码删了,
* 会有用例报出来,而不是静悄悄换掉接口的返回顺序
*/
@Test
void listPutsTheMostRecentlyTouchedEntryFirst() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
DeviceAddressBookEntity older = row(MAC, OTHER_MAC, "客厅");
older.setUpdateDate(new Date(1767321840000L));
DeviceAddressBookEntity newer = row(MAC, THIRD_MAC, "书房");
newer.setUpdateDate(new Date(1778000000000L));
DeviceAddressBookEntity neverTouched = row(MAC, "00:11:22:33:44:88", "阳台");
when(addressBookDao.getAddressBookList(MAC)).thenReturn(
new ArrayList<>(List.of(older, neverTouched, newer)));
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, mock(DeviceService.class), mock(SysParamsService.class));
List<DeviceAddressBookEntity> rows = service.getAddressBookList(MAC);
assertEquals(List.of("书房", "客厅", "阳台"), rows.stream().map(DeviceAddressBookEntity::getAlias).toList(),
"最近改过的应该排前面,没改过的排最后");
}
private Map<String, String> namesByTargetMac(List<DeviceAddressBookEntity> rows) {
Map<String, String> byAlias = new HashMap<>();
for (DeviceAddressBookEntity row : rows) {
byAlias.put(row.getAlias(), row.getTargetMac());
}
return byAlias;
}
@Test
void callByNicknameFallsBackToMacSuffixWhenCallerHasNoAlias() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
DeviceService deviceService = mock(DeviceService.class);
SysParamsService sysParamsService = mock(SysParamsService.class);
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, deviceService, sysParamsService);
Map<String, Map<String, String>> books = new HashMap<>();
Map<String, String> callerBook = new HashMap<>();
callerBook.put("office", OTHER_MAC + "|1");
books.put(MAC, callerBook);
when(redisUtils.get(RedisKeys.getAddressBookKey())).thenReturn(books);
when(deviceService.getDeviceByMacAddress(MAC)).thenReturn(null);
when(sysParamsService.getValue("server.mqtt_manager_api", true)).thenReturn("127.0.0.1:1883");
when(sysParamsService.getValue(Constant.SERVER_MQTT_SECRET, true)).thenReturn("gateway-key");
// 网关是真的 http 调用,桩掉它,否则测试会往 127.0.0.1:1883 真发请求
AtomicReference<String> sentUrl = new AtomicReference<>();
AtomicReference<String> sentBody = new AtomicReference<>();
Map<String, Object> result;
try (MockedStatic<MqttGatewayAuthorization> gateway = mockStatic(MqttGatewayAuthorization.class)) {
gateway.when(() -> MqttGatewayAuthorization.postJson(
anyString(), anyString(), anyString(), any(), anyInt()))
.thenAnswer(invocation -> {
sentUrl.set(invocation.getArgument(0));
sentBody.set(invocation.getArgument(1));
return "{\"status\":\"success\",\"message\":\"ok\"}";
});
result = service.callByNickname(MAC, "office", false);
}
assertEquals("success", result.get("status"));
assertEquals("http://127.0.0.1:1883/api/call/request", sentUrl.get());
assertTrue(sentBody.get().contains("尾号为55的设备"),
"主叫方没登记也没起名时该退回尾号称呼:" + sentBody.get());
}
}

View file

@ -0,0 +1,184 @@
package xiaozhi.modules.device.service.impl;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import xiaozhi.common.redis.RedisUtils;
import xiaozhi.common.user.UserDetail;
import xiaozhi.modules.device.dao.DeviceDao;
import xiaozhi.modules.device.entity.DeviceEntity;
import xiaozhi.modules.device.service.DeviceAddressBookService;
import xiaozhi.modules.device.service.OtaService;
import xiaozhi.modules.security.user.SecurityUser;
import xiaozhi.modules.sys.service.SysParamsService;
import xiaozhi.modules.sys.service.SysUserUtilService;
@DisplayName("设备归属校验回归测试")
class DeviceServiceImplTest {
private static final String MAC = "00:11:22:33:44:55";
private static final long USER_ID = 1L;
private static final long OTHER_USER_ID = 2L;
@Test
@DisplayName("设备属于当前用户时返回设备")
void deviceOwnedByCurrentUserIsReturned() {
DeviceEntity device = device(USER_ID);
DeviceServiceImpl service = serviceWithDeviceDao(daoReturning(device));
try (MockedStatic<SecurityUser> securityUser = mockStatic(SecurityUser.class)) {
securityUser.when(SecurityUser::getUser).thenReturn(user(USER_ID));
assertSame(device, service.getOwnedDeviceByMacAddress(MAC));
}
}
@Test
@DisplayName("设备属于他人时按查不到处理")
void deviceOwnedByAnotherUserIsHidden() {
DeviceServiceImpl service = serviceWithDeviceDao(daoReturning(device(OTHER_USER_ID)));
try (MockedStatic<SecurityUser> securityUser = mockStatic(SecurityUser.class)) {
securityUser.when(SecurityUser::getUser).thenReturn(user(USER_ID));
assertNull(service.getOwnedDeviceByMacAddress(MAC));
}
}
@Test
@DisplayName("设备未登记时按查不到处理")
void unregisteredDeviceIsHidden() {
DeviceServiceImpl service = serviceWithDeviceDao(daoReturning(List.of()));
try (MockedStatic<SecurityUser> securityUser = mockStatic(SecurityUser.class)) {
securityUser.when(SecurityUser::getUser).thenReturn(user(USER_ID));
assertNull(service.getOwnedDeviceByMacAddress(MAC));
}
}
@Test
@DisplayName("设备没有归属人时按查不到处理")
void unboundDeviceIsHidden() {
DeviceServiceImpl service = serviceWithDeviceDao(daoReturning(device(null)));
try (MockedStatic<SecurityUser> securityUser = mockStatic(SecurityUser.class)) {
securityUser.when(SecurityUser::getUser).thenReturn(user(USER_ID));
assertNull(service.getOwnedDeviceByMacAddress(MAC));
}
}
@Test
@DisplayName("没有登录用户时按查不到处理")
void anonymousCallerGetsNothing() {
DeviceServiceImpl service = serviceWithDeviceDao(daoReturning(device(USER_ID)));
// 匿名调用的实际形态:getUser() 返回空对象,id 是空的,不是返回 null
try (MockedStatic<SecurityUser> securityUser = mockStatic(SecurityUser.class)) {
securityUser.when(SecurityUser::getUser).thenReturn(new UserDetail());
assertNull(service.getOwnedDeviceByMacAddress(MAC));
}
}
@Test
@DisplayName("库里同一 MAC 有两行只差大小写时,取第一条做归属校验,不再抛异常")
void duplicateMacDifferingOnlyInCaseStillReturnsTheDevice() {
DeviceEntity first = device(USER_ID, "device-1");
DeviceEntity second = device(USER_ID, "device-2");
DeviceServiceImpl service = serviceWithDeviceDao(daoReturning(List.of(first, second)));
try (MockedStatic<SecurityUser> securityUser = mockStatic(SecurityUser.class)) {
securityUser.when(SecurityUser::getUser).thenReturn(user(USER_ID));
assertSame(first, service.getOwnedDeviceByMacAddress(MAC));
}
}
@Test
@DisplayName("解绑自己的设备时,通讯录跟着一起清")
void unbindOwnDeviceClearsItsAddressBook() {
DeviceDao dao = mock(DeviceDao.class);
when(dao.selectById("device-1")).thenReturn(device(USER_ID, "device-1"));
DeviceAddressBookService addressBookService = mock(DeviceAddressBookService.class);
DeviceServiceImpl service = serviceWithDao(dao, addressBookService);
service.unbindDevice(USER_ID, "device-1");
verify(dao).delete(any(UpdateWrapper.class));
verify(addressBookService).deleteByMacAddresses(List.of(MAC));
}
@Test
@DisplayName("解绑别人的设备时什么都不删,通讯录不能跟着没")
void unbindAnotherUsersDeviceDeletesNothing() {
DeviceDao dao = mock(DeviceDao.class);
when(dao.selectById("device-1")).thenReturn(device(OTHER_USER_ID, "device-1"));
DeviceAddressBookService addressBookService = mock(DeviceAddressBookService.class);
DeviceServiceImpl service = serviceWithDao(dao, addressBookService);
service.unbindDevice(USER_ID, "device-1");
verify(dao, never()).delete(any(UpdateWrapper.class));
verify(addressBookService, never()).deleteByMacAddresses(anyList());
}
private DeviceServiceImpl serviceWithDao(DeviceDao dao, DeviceAddressBookService addressBookService) {
// baseDao 由父类持有,子类内部赋给 this,测试类自己碰不到它
return new DeviceServiceImpl(
dao, mock(SysUserUtilService.class), mock(SysParamsService.class),
mock(RedisUtils.class), mock(OtaService.class), addressBookService) {
{
this.baseDao = dao;
}
};
}
private DeviceServiceImpl serviceWithDeviceDao(DeviceDao dao) {
return serviceWithDao(dao, mock(DeviceAddressBookService.class));
}
private DeviceDao daoReturning(DeviceEntity device) {
return daoReturning(List.of(device));
}
private DeviceDao daoReturning(List<DeviceEntity> rows) {
DeviceDao dao = mock(DeviceDao.class);
when(dao.selectList(any())).thenReturn(rows);
return dao;
}
private DeviceEntity device(Long userId) {
return device(userId, null);
}
private DeviceEntity device(Long userId, String id) {
DeviceEntity entity = new DeviceEntity();
entity.setId(id);
entity.setMacAddress(MAC);
entity.setUserId(userId);
return entity;
}
private UserDetail user(long id) {
UserDetail user = new UserDetail();
user.setId(id);
return user;
}
}

View file

@ -0,0 +1,82 @@
package xiaozhi.modules.model.service.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.UUID;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.json.JSONObject;
import xiaozhi.common.redis.RedisKeys;
import xiaozhi.common.redis.RedisUtils;
import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
import xiaozhi.modules.model.dto.ModelConfigDTO;
import xiaozhi.modules.model.service.ModelConfigService;
import xiaozhi.testsupport.IntegrationTestEnvironment;
@SpringBootTest
@ActiveProfiles("dev")
@Transactional
class ModelConfigPersistenceTest {
@BeforeAll
static void checkDependencies() {
IntegrationTestEnvironment.requireDatabaseAndRedis();
}
@Autowired
private ModelConfigService service;
@Autowired
private JdbcTemplate jdbc;
@Autowired
private RedisUtils redis;
@ParameterizedTest
@CsvSource({"tts,TTS", "memory,Memory", "intent,Intent"})
void preservesRegisteredTypeWhenAddingAndEditing(String requestedType, String registeredType) {
String id = UUID.randomUUID().toString().replace("-", "");
String providerCode = "test-" + id;
jdbc.update("INSERT INTO ai_model_provider (id, model_type, provider_code, name, fields) VALUES (?, ?, ?, ?, ?)",
id, registeredType, providerCode, "Persistence test provider", "[]");
ModelConfigBodyDTO body = new ModelConfigBodyDTO();
body.setId(id);
body.setModelCode(providerCode);
body.setModelName("Persistence test model");
body.setIsDefault(0);
body.setIsEnabled(1);
body.setSort(1);
body.setConfigJson(new JSONObject().set("type", providerCode));
ModelConfigDTO added = service.add(requestedType, providerCode, body);
assertEquals(registeredType, added.getModelType());
assertEquals(registeredType,
jdbc.queryForObject("SELECT model_type FROM ai_model_config WHERE id = ?", String.class, id));
String cacheKey = RedisKeys.getModelConfigById(id);
try {
redis.set(cacheKey, "cached model");
body.setModelName("Updated persistence test model");
ModelConfigDTO edited = service.edit(requestedType, providerCode, id, body);
assertEquals(registeredType, edited.getModelType());
assertEquals(registeredType,
jdbc.queryForObject("SELECT model_type FROM ai_model_config WHERE id = ?", String.class, id));
assertEquals(body.getModelName(),
jdbc.queryForObject("SELECT model_name FROM ai_model_config WHERE id = ?", String.class, id));
assertNull(redis.get(cacheKey));
} finally {
redis.delete(cacheKey);
}
}
}

View file

@ -0,0 +1,120 @@
package xiaozhi.modules.model.service.impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
import xiaozhi.common.exception.ErrorCode;
import xiaozhi.common.exception.RenException;
import xiaozhi.common.redis.RedisUtils;
import xiaozhi.common.utils.MessageUtils;
import xiaozhi.modules.agent.dao.AgentDao;
import xiaozhi.modules.model.dao.ModelConfigDao;
import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
import xiaozhi.modules.model.dto.ModelConfigDTO;
import xiaozhi.modules.model.dto.ModelProviderDTO;
import xiaozhi.modules.model.entity.ModelConfigEntity;
import xiaozhi.modules.model.service.ModelProviderService;
class ModelConfigServiceImplTest {
private ModelConfigDao modelConfigDao;
private ModelProviderService modelProviderService;
private ModelConfigServiceImpl service;
@BeforeEach
void setUp() {
modelConfigDao = mock(ModelConfigDao.class);
modelProviderService = mock(ModelProviderService.class);
service = new ModelConfigServiceImpl(
modelConfigDao, modelProviderService, mock(RedisUtils.class), mock(AgentDao.class));
}
@ParameterizedTest
@CsvSource({
"vad, VAD", "asr, ASR", "tts, TTS", "llm, LLM", "vllm, VLLM",
"memory, Memory", "intent, Intent", "rag, RAG", "LLM, LLM"
})
void addPreservesRegisteredProviderModelType(String requestedType, String registeredType) {
registerProvider(requestedType, registeredType);
ModelConfigDTO result = service.add(requestedType, "test-provider", modelBody());
ArgumentCaptor<ModelConfigEntity> saved = ArgumentCaptor.forClass(ModelConfigEntity.class);
verify(modelConfigDao).insert(saved.capture());
assertEquals(registeredType, saved.getValue().getModelType());
assertEquals(registeredType, result.getModelType());
}
@ParameterizedTest
@CsvSource({
"vad, VAD", "asr, ASR", "tts, TTS", "llm, LLM", "vllm, VLLM",
"memory, Memory", "intent, Intent", "rag, RAG", "LLM, LLM"
})
void editPreservesRegisteredProviderModelType(String requestedType, String registeredType) {
registerProvider(requestedType, registeredType);
ModelConfigEntity original = new ModelConfigEntity();
original.setId("test-model");
original.setModelType(registeredType);
when(modelConfigDao.selectById("test-model")).thenReturn(original);
ModelConfigDTO result = service.edit(requestedType, "test-provider", "test-model", modelBody());
ArgumentCaptor<ModelConfigEntity> saved = ArgumentCaptor.forClass(ModelConfigEntity.class);
verify(modelConfigDao).updateById(saved.capture());
assertEquals(registeredType, saved.getValue().getModelType());
assertEquals(registeredType, result.getModelType());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void rejectsUnknownProviderBeforeWriting(boolean editing) {
when(modelProviderService.getList("tts", "missing")).thenReturn(List.of());
try (MockedStatic<MessageUtils> messages = mockStatic(MessageUtils.class)) {
messages.when(() -> MessageUtils.getMessage(ErrorCode.MODEL_PROVIDER_NOT_EXIST))
.thenReturn("Model provider does not exist");
RenException error = assertThrows(RenException.class, () -> {
if (editing) {
service.edit("tts", "missing", "test-model", modelBody());
} else {
service.add("tts", "missing", modelBody());
}
});
assertEquals(ErrorCode.MODEL_PROVIDER_NOT_EXIST, error.getCode());
}
verify(modelConfigDao, never()).insert(any(ModelConfigEntity.class));
verify(modelConfigDao, never()).updateById(any(ModelConfigEntity.class));
}
private void registerProvider(String requestedType, String registeredType) {
ModelProviderDTO provider = new ModelProviderDTO();
provider.setModelType(registeredType);
provider.setProviderCode("test-provider");
when(modelProviderService.getList(requestedType, "test-provider")).thenReturn(List.of(provider));
}
private ModelConfigBodyDTO modelBody() {
ModelConfigBodyDTO body = new ModelConfigBodyDTO();
body.setId("test-model");
body.setModelName("Test model");
body.setIsEnabled(1);
body.setSort(1);
return body;
}
}

View file

@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@ -18,12 +19,18 @@ import xiaozhi.modules.security.dto.LoginDTO;
import xiaozhi.modules.security.dto.SmsVerificationDTO;
import xiaozhi.modules.sys.dto.RetrievePasswordDTO;
import xiaozhi.modules.sys.service.SysUserService;
import xiaozhi.testsupport.IntegrationTestEnvironment;
@Slf4j
@SpringBootTest
@ActiveProfiles("dev")
class loginControllerTest {
@BeforeAll
static void checkDependencies() {
IntegrationTestEnvironment.requireDatabaseAndRedis();
}
@Autowired
LoginController loginController;

View file

@ -0,0 +1,149 @@
package xiaozhi.testsupport;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.time.Duration;
import org.junit.jupiter.api.Assumptions;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.PropertySourcesPropertyResolver;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import lombok.extern.slf4j.Slf4j;
/**
* 几个 @SpringBootTest 要真连 MySQL 和 Redis。本地没起这两个依赖时,
* 整类测试跳过,别让 Spring 上下文起不来变成一堆看不懂的报错;
* CI 里依赖必须真的在,探不通就直接让构建红。
*/
@Slf4j
public final class IntegrationTestEnvironment {
/** 集成测试用的配置文件,跟应用本身读的是同一套 */
private static final String[] CONFIG_FILES = {"application.yml", "application-dev.yml"};
private static Boolean available;
private static String problem;
private IntegrationTestEnvironment() {
}
/**
* 放在要连库的测试类的 @BeforeAll 里。
* 本地依赖不齐就整类跳过,CI 里依赖不齐就直接失败。
*/
public static void requireDatabaseAndRedis() {
String issue = probe();
if (issue == null) {
return;
}
if (isCi()) {
throw new IllegalStateException(
"CI 环境里" + issue + ",这几个集成测试必须真的跑起来,不能跳过");
}
log.warn("跳过依赖 MySQL 和 Redis 的集成测试:{}", issue);
Assumptions.assumeTrue(false, issue);
}
/** GitHub Actions 上会带 CI=true */
public static boolean isCi() {
String value = System.getenv("CI");
if (value == null) {
return false;
}
String trimmed = value.trim();
return !trimmed.isEmpty() && !"false".equalsIgnoreCase(trimmed);
}
/** 依赖都齐返回 null,不齐返回缺什么 */
static synchronized String probe() {
if (available != null) {
return problem;
}
PropertySourcesPropertyResolver resolver = resolver();
StringBuilder issues = new StringBuilder();
String url = firstNonBlank(resolver.getProperty("spring.datasource.druid.url", ""),
resolver.getProperty("spring.datasource.url", ""));
String username = firstNonBlank(resolver.getProperty("spring.datasource.druid.username", ""),
resolver.getProperty("spring.datasource.username", ""));
String password = firstNonBlank(resolver.getProperty("spring.datasource.druid.password", ""),
resolver.getProperty("spring.datasource.password", ""));
if (url.isBlank()) {
issues.append("配置里找不到数据源地址;");
} else {
try {
DriverManager.setLoginTimeout(5);
try (Connection connection = DriverManager.getConnection(url, username, password)) {
connection.isValid(3);
}
} catch (Exception e) {
issues.append("连不上 MySQL(").append(e.getMessage()).append(");");
}
}
String redisHost = resolver.getProperty("spring.data.redis.host", "localhost");
int redisPort = resolver.getProperty("spring.data.redis.port", Integer.class, 6379);
String redisPassword = resolver.getProperty("spring.data.redis.password", "");
try {
RedisURI.Builder builder = RedisURI.builder()
.withHost(redisHost)
.withPort(redisPort)
.withTimeout(Duration.ofSeconds(3));
if (redisPassword != null && !redisPassword.isBlank()) {
builder.withPassword(redisPassword.toCharArray());
}
RedisClient client = RedisClient.create(builder.build());
try {
StatefulRedisConnection<String, String> connection = client.connect();
connection.sync().ping();
connection.close();
} finally {
client.shutdown();
}
} catch (Exception e) {
issues.append("连不上 Redis(").append(e.getMessage()).append(");");
}
if (issues.length() == 0) {
available = Boolean.TRUE;
problem = null;
} else {
available = Boolean.FALSE;
problem = issues.toString();
}
return problem;
}
/** 读应用自己那份配置,命令行上的 -D 参数优先级更高,跟应用保持一致 */
private static PropertySourcesPropertyResolver resolver() {
ConfigurableEnvironment environment = new StandardEnvironment();
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
for (String name : CONFIG_FILES) {
Resource resource = new ClassPathResource(name);
if (!resource.exists()) {
continue;
}
try {
for (PropertySource<?> source : loader.load(name, resource)) {
environment.getPropertySources().addLast(source);
}
} catch (IOException e) {
log.warn("读配置 {} 失败:{}", name, e.getMessage());
}
}
return new PropertySourcesPropertyResolver(environment.getPropertySources());
}
private static String firstNonBlank(String first, String second) {
return first != null && !first.isBlank() ? first : (second == null ? "" : second);
}
}

View file

@ -120,6 +120,11 @@ export default defineManifestConfig({
/* 小程序特有相关 */
'mp-weixin': {
appid: VITE_WX_APPID,
// 仅供开发者工具选择调试基础库版本;线上客户端的最低基础库门槛需在
// 微信公众平台「开发管理 → 基础库最低版本设置」中配置(代码里改不动)。
// 功能硬性要求:wx.getRandomValues 需基础库 >= 2.17.3,低于该版本的
// 线上客户端登录时将收到 fail-closed 报错
libVersion: '2.19.4',
setting: {
urlCheck: false,
// 是否启用 ES6 转 ES5

View file

@ -101,7 +101,7 @@
"js-cookie": "^3.0.5",
"pinia": "2.0.36",
"pinia-plugin-persistedstate": "3.2.1",
"sm-crypto": "^0.3.13",
"sm-crypto": "0.5.8",
"vue": "^3.4.21",
"wot-design-uni": "^1.9.1",
"z-paging": "2.8.7"

View file

@ -0,0 +1,29 @@
diff --git a/src/sm2/rng.js b/src/sm2/rng.js
index c6572c1756579fb100c0d7bdf0cec323971ec211..cdb1f1fcc7d58c52138f6f9fd76240bae5dde5d4 100644
--- a/src/sm2/rng.js
+++ b/src/sm2/rng.js
@@ -54,8 +54,14 @@ function rngSeedTime() {
rngSeedInt(new Date().getTime())
}
-// Initialize the pool with junk if needed.
-if (rngPool == null) {
+// [xiaozhi patch] 熵池初始化从模块加载时推迟到首次取随机字节时(见 rngGetByte)。
+// 原因:微信小程序等环境没有同步的 crypto.getRandomValues,模块加载即取熵会直接抛异常;
+// 推迟后,调用方可在首次使用前异步准备好真随机源(见 manager-mobile/src/utils/secure-random.ts)。
+// fail-closed 语义保持不变:首次取熵时仍要求存在可用的 crypto.getRandomValues,否则抛出异常。
+function ensureRngPool() {
+ if (rngPool != null)
+ return
+
rngPool = []
rngPptr = 0
let t
@@ -82,6 +88,7 @@ if (rngPool == null) {
function rngGetByte() {
if (rngState == null) {
+ ensureRngPool()
rngSeedTime()
rngState = new Arcfour()
rngState.init(rngPool)

View file

@ -11,6 +11,9 @@ patchedDependencies:
'@dcloudio/uni-h5':
hash: 5763725268e9a493075be3c82d91b590b9ae30e997a04a418494dd7d6d327b9d
path: patches/@dcloudio__uni-h5.patch
sm-crypto@0.5.8:
hash: 62930665cf9612107916df2f12c9deab4ad907f6ac9080520b84bffe016c3352
path: patches/sm-crypto@0.5.8.patch
importers:
@ -92,8 +95,8 @@ importers:
specifier: 3.2.1
version: 3.2.1(pinia@2.0.36(typescript@5.7.2)(vue@3.5.15(typescript@5.7.2)))
sm-crypto:
specifier: ^0.3.13
version: 0.3.14
specifier: 0.5.8
version: 0.5.8(patch_hash=62930665cf9612107916df2f12c9deab4ad907f6ac9080520b84bffe016c3352)
vue:
specifier: ^3.4.21
version: 3.5.15(typescript@5.7.2)
@ -6026,8 +6029,8 @@ packages:
resolution: {integrity: sha512-bSiSngZ/jWeX93BqeIAbImyTbEihizcwNjFoRUIY/T1wWQsfsm2Vw1agPKylXvQTU7iASGdHhyqRlqQzfz+Htg==}
engines: {node: '>=18'}
sm-crypto@0.3.14:
resolution: {integrity: sha512-sR7NuGAJH93Om8keAF2/rj1EqFzEiUey4aKGyDo3nQ2BiVqhgq8UkiIoIp5qhV9w4pG7qArhfqyewcG8AbhXbg==}
sm-crypto@0.5.8:
resolution: {integrity: sha512-bpz1/PthgZHcLHyIl28mbYZHmeuTDrdWpwHZ7BGzFjQuB7OOhjlbcPEMt44aqUfZ2S5YJXM8v20xYO1j9CC45Q==}
source-map-js@1.2.1:
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
@ -14156,7 +14159,7 @@ snapshots:
ansi-styles: 6.2.1
is-fullwidth-code-point: 5.0.0
sm-crypto@0.3.14:
sm-crypto@0.5.8(patch_hash=62930665cf9612107916df2f12c9deab4ad907f6ac9080520b84bffe016c3352):
dependencies:
jsbn: 1.1.0

View file

@ -1,6 +1,6 @@
packages:
- '**'
- '!node_modules'
patchedDependencies:
'@dcloudio/uni-h5': patches/@dcloudio__uni-h5.patch
sm-crypto@0.5.8: patches/sm-crypto@0.5.8.patch

View file

@ -0,0 +1,136 @@
<script lang="ts">
import { defineComponent } from 'vue'
// #ifdef APP-PLUS
import { ensureSecureRandomReady, registerRandomBridge, unregisterRandomBridge } from '@/utils/secure-random'
// #endif
interface BridgeItem {
length: number
resolve: (bytes: number[]) => void
reject: (err: Error) => void
}
/**
* App 端专用(页面中 #ifdef APP-PLUS 条件挂载):
* 逻辑层无 Web Crypto,经 renderjs 在视图层 WebView 取
* crypto.getRandomValues 后 callMethod 回传,注册为 secure-random 的随机源。
*/
export default defineComponent({
data() {
return {
/** 变化后触发 renderjs 取随机(每次新对象引用确保 prop 变更被感知) */
bridgeRequest: null as { id: number, length: number } | null,
// 仅类型检查用:renderjs 模块绑定由 uni-app 编译期处理,运行时不读取
secureRandomRenderer: { onPropChange: () => {} } as { onPropChange: (...args: any[]) => void },
seq: 0,
queue: [] as BridgeItem[],
sending: false,
currentId: 0,
timeoutTimer: undefined as ReturnType<typeof setTimeout> | undefined,
provider: undefined as ((length: number) => Promise<Uint8Array>) | undefined,
}
},
mounted() {
// #ifdef APP-PLUS
this.provider = (length: number) =>
this.requestBytes(length).then(bytes => new Uint8Array(bytes))
registerRandomBridge(this.provider)
ensureSecureRandomReady().catch((e: Error) => {
console.warn('[secure-random] App 端随机源预热失败', e)
})
// #endif
},
beforeUnmount() {
// #ifdef APP-PLUS
// 拒绝队列项并注销,否则销毁后 pending 的 Promise 永不 settle,readyPromise 死锁
if (this.provider)
unregisterRandomBridge(this.provider)
for (const item of this.queue)
item.reject(new Error('secure-random-bridge 组件已卸载,随机数请求中止'))
this.queue = []
this.sending = false
// #endif
clearTimeout(this.timeoutTimer)
},
methods: {
requestBytes(length: number): Promise<number[]> {
return new Promise((resolve, reject) => {
this.queue.push({ length, resolve, reject })
this.pump()
})
},
/** 串行发送:prop 变更过快时视图层可能丢失中间状态,故一次只发一个请求 */
pump() {
if (this.sending || this.queue.length === 0)
return
this.sending = true
const item = this.queue[0]
this.currentId = ++this.seq
this.bridgeRequest = { id: this.currentId, length: item.length }
// 超时保护:视图层无响应时按 fail-closed 报错,避免登录流程永久挂起
clearTimeout(this.timeoutTimer)
this.timeoutTimer = setTimeout(() => {
this.onRandomResult({ id: this.currentId, error: 'renderjs 随机数请求超时' })
}, 5000)
},
/** renderjs 通过 callMethod 回传结果(或错误) */
onRandomResult(res: { id: number, bytes?: number[], error?: string }) {
if (res.id !== this.currentId)
return
clearTimeout(this.timeoutTimer)
const item = this.queue.shift()
this.sending = false
if (item) {
if (res.error)
item.reject(new Error(res.error))
else
item.resolve(res.bytes || [])
}
this.pump()
},
},
})
</script>
<script module="secureRandomRenderer" lang="renderjs">
// 视图层(WebView):可访问 crypto.getRandomValues
export default {
methods: {
onPropChange(newVal, oldVal, ownerInstance, instance) {
if (!newVal || !newVal.id || !newVal.length)
return
try {
const cryptoObj = (typeof crypto !== 'undefined' && crypto)
|| (typeof window !== 'undefined' && window.crypto)
if (!cryptoObj || typeof cryptoObj.getRandomValues !== 'function')
throw new Error('视图层缺少 crypto.getRandomValues')
const bytes = new Uint8Array(newVal.length)
cryptoObj.getRandomValues(bytes)
ownerInstance.callMethod('onRandomResult', { id: newVal.id, bytes: Array.from(bytes) })
}
catch (e) {
ownerInstance.callMethod('onRandomResult', {
id: newVal.id,
error: String((e && e.message) || e),
})
}
},
},
}
</script>
<template>
<view
class="secure-random-bridge"
:prop="bridgeRequest"
:change:prop="secureRandomRenderer.onPropChange"
/>
</template>
<style>
.secure-random-bridge {
width: 0;
height: 0;
overflow: hidden;
}
</style>

View file

@ -92,6 +92,7 @@
"minified": true
},
"usingComponents": true,
"libVersion": "2.19.4",
"optimization": {
"subPackages": true
},

View file

@ -13,6 +13,10 @@ import { onLoad } from '@dcloudio/uni-app'
import { computed, onMounted, ref } from 'vue'
// 导入API接口
import { retrievePassword, sendSmsCode } from '@/api/auth'
// #ifdef APP-PLUS
// App 端随机源桥接:为 SM2 加密提供安全随机数(无视觉展示)
import SecureRandomBridge from '@/components/secure-random-bridge/index.vue'
// #endif
// 导入国际化相关功能
import { initI18n, t } from '@/i18n'
import { useConfigStore } from '@/store'
@ -235,7 +239,7 @@ async function handleResetPassword() {
try {
// 拼接图形验证码和新密码进行加密
const captchaAndPassword = formData.value.captcha + formData.value.newPassword
encryptedPassword = sm2Encrypt(sm2PublicKey.value, captchaAndPassword)
encryptedPassword = await sm2Encrypt(sm2PublicKey.value, captchaAndPassword)
}
catch (error) {
console.error('密码加密失败:', error)
@ -305,6 +309,9 @@ onMounted(async () => {
class="app-container box-border h-screen w-full"
:style="{ paddingTop: `${safeAreaInsets?.top}px` }"
>
<!-- #ifdef APP-PLUS -->
<SecureRandomBridge />
<!-- #endif -->
<view class="header">
<view class="back-button" @click="goBack">
<wd-icon name="arrow-left" custom-class="back-icon" />

View file

@ -13,6 +13,10 @@ import type { LoginData } from '@/api/auth'
import type { Language } from '@/store/lang'
import { computed, onMounted, ref } from 'vue'
import { login } from '@/api/auth'
// #ifdef APP-PLUS
// App 端随机源桥接:为 SM2 加密提供安全随机数(无视觉展示)
import SecureRandomBridge from '@/components/secure-random-bridge/index.vue'
// #endif
// 导入国际化相关功能
import { changeLanguage, getCurrentLanguage, getSupportedLanguages, initI18n, t } from '@/i18n'
import { useConfigStore, useUserStore } from '@/store'
@ -202,7 +206,7 @@ async function handleLogin() {
try {
// 拼接验证码和密码
const captchaAndPassword = formData.value.captcha + formData.value.password
encryptedPassword = sm2Encrypt(sm2PublicKey, captchaAndPassword)
encryptedPassword = await sm2Encrypt(sm2PublicKey, captchaAndPassword)
}
catch (error) {
console.error('密码加密失败:', error)
@ -281,6 +285,9 @@ onMounted(async () => {
<template>
<view class="app-container box-border h-screen w-full" :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
<!-- #ifdef APP-PLUS -->
<SecureRandomBridge />
<!-- #endif -->
<view class="header">
<view class="logo-section">
<wd-img :width="80" :height="80" round src="/static/logo.png" class="logo" />

View file

@ -11,6 +11,10 @@
<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { register, sendSmsCode } from '@/api/auth'
// #ifdef APP-PLUS
// App 端随机源桥接:为 SM2 加密提供安全随机数(无视觉展示)
import SecureRandomBridge from '@/components/secure-random-bridge/index.vue'
// #endif
// 导入国际化相关功能
import { initI18n, t } from '@/i18n'
import { useConfigStore } from '@/store'
@ -251,7 +255,7 @@ async function handleRegister() {
try {
// 拼接验证码和密码
const captchaAndPassword = formData.value.captcha + formData.value.password
encryptedPassword = sm2Encrypt(sm2PublicKey.value, captchaAndPassword)
encryptedPassword = await sm2Encrypt(sm2PublicKey.value, captchaAndPassword)
}
catch (error) {
console.error('密码加密失败:', error)
@ -325,6 +329,9 @@ onMounted(async () => {
<template>
<view class="app-container box-border h-screen w-full" :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
<!-- #ifdef APP-PLUS -->
<SecureRandomBridge />
<!-- #endif -->
<view class="header">
<view class="back-button" @click="goBack">
<wd-icon name="arrow-left" custom-class="back-icon" />

View file

@ -265,7 +265,7 @@ function showAbout() {
title: t('settings.aboutApp', { appName: import.meta.env.VITE_APP_TITLE }),
content: t('settings.aboutContent', {
appName: import.meta.env.VITE_APP_TITLE,
version: '0.9.7',
version: '0.9.8',
}),
showCancel: false,
confirmText: t('common.confirm'),

View file

@ -2,6 +2,21 @@ import smCrypto from 'sm-crypto'
import { pages, subPackages } from '@/pages.json'
import { isMpWeixin } from './platform'
import { ensureSecureRandomReady } from './secure-random'
/**
* 获取 sm2 模块(确保密码学安全随机源已就绪)。
*
* sm-crypto >= 0.5.0(CVE-2026-73567 修复)强制要求 crypto.getRandomValues。
* 小程序等环境没有该 API,项目中通过 pnpm patch(patches/sm-crypto@0.5.8.patch)
* 将 sm-crypto 的熵池初始化推迟到首次取随机字节时,并由 secure-random.ts 提供
* 垫片。因此小程序端首次调用 sm2 前必须 await 本方法,用 wx.getRandomValues
* 预热真随机缓冲池;浏览器 / Node 等原生支持 globalThis.crypto 的环境立即就绪。
*/
async function getSm2(): Promise<typeof smCrypto.sm2> {
await ensureSecureRandomReady()
return smCrypto.sm2
}
/**
* 运行时服务端地址覆盖存储键
@ -201,11 +216,11 @@ export function getEnvBaseUploadUrl() {
/**
* 生成SM2密钥对(十六进制格式)
* @returns {object} 包含公钥和私钥的对象
* @returns {Promise<object>} 包含公钥和私钥的对象
*/
export function generateSm2KeyPairHex() {
export async function generateSm2KeyPairHex() {
// 使用sm-crypto库生成SM2密钥对
const sm2 = smCrypto.sm2
const sm2 = await getSm2()
const keypair = sm2.generateKeyPairHex()
return {
@ -220,9 +235,9 @@ export function generateSm2KeyPairHex() {
* SM2公钥加密
* @param {string} publicKey 公钥(十六进制格式)
* @param {string} plainText 明文
* @returns {string} 加密后的密文(十六进制格式)
* @returns {Promise<string>} 加密后的密文(十六进制格式)
*/
export function sm2Encrypt(publicKey: string, plainText: string): string {
export async function sm2Encrypt(publicKey: string, plainText: string): Promise<string> {
if (!publicKey) {
throw new Error('公钥不能为null或undefined')
}
@ -231,7 +246,7 @@ export function sm2Encrypt(publicKey: string, plainText: string): string {
throw new Error('明文不能为空')
}
const sm2 = smCrypto.sm2
const sm2 = await getSm2()
// SM2加密,添加04前缀表示未压缩公钥
const encrypted = sm2.doEncrypt(plainText, publicKey, 1)
// 转换为十六进制格式(与后端保持一致,添加04前缀)
@ -244,10 +259,10 @@ export function sm2Encrypt(publicKey: string, plainText: string): string {
* SM2私钥解密
* @param {string} privateKey 私钥(十六进制格式)
* @param {string} cipherText 密文(十六进制格式)
* @returns {string} 解密后的明文
* @returns {Promise<string>} 解密后的明文(当前项目内暂无调用点,保留备用)
*/
export function sm2Decrypt(privateKey: string, cipherText: string): string {
const sm2 = smCrypto.sm2
export async function sm2Decrypt(privateKey: string, cipherText: string): Promise<string> {
const sm2 = await getSm2()
// 移除04前缀(与后端保持一致)
const dataWithoutPrefix = cipherText.startsWith('04') ? cipherText.substring(2) : cipherText
// SM2解密

View file

@ -0,0 +1,206 @@
/**
* 为 sm-crypto >= 0.5.0 提供 crypto.getRandomValues 兼容层
* (0.5.0 起强制要求 CSPRNG,不支持时模块加载即抛异常,见 CVE-2026-73567)。
*
* 策略:
* 1. 经平台异步 CSPRNG API 分块并行取真随机字节,填入同步缓冲池。
* 探测顺序 wx → uni → my → tt → swan → ks → qq → jd → lark → xhs;
* App 端逻辑层无 CSPRNG,
* 由 secure-random-bridge 组件经 renderjs 回传(registerRandomBridge 兜底)。
* 2. 垫片同步从缓冲池取字节,池不足即抛错,不回退弱随机(fail-closed)。
* 3. sm-crypto 熵池初始化已通过 pnpm patch 推迟到首次取随机
* (patches/sm-crypto@0.5.8.patch),首次 sm2 调用前 await
* ensureSecureRandomReady() 即可。
*
* 无任何 CSPRNG 的平台(如支付宝/百度小程序)会 reject,属预期行为。
*/
const CHUNK_SIZE = 64
const CHUNK_COUNT = 8
const LOW_WATER_MARK = 128
// 标记垫片自身,探测时与原生实现区分,避免失败重试被短路成假成功
const SHIM_MARKER = Symbol('secureRandomShim')
// App 端桥接通道,由 secure-random-bridge 组件挂载时注册
let bridgeProvider: ((length: number) => Promise<Uint8Array>) | null = null
export function registerRandomBridge(provider: (length: number) => Promise<Uint8Array>) {
bridgeProvider = provider
}
/** 仅当当前注册者仍是该实例时注销,避免多页栈下误清后挂载实例的注册 */
export function unregisterRandomBridge(provider: (length: number) => Promise<Uint8Array>) {
if (bridgeProvider === provider)
bridgeProvider = null
}
let pool: number[] = []
let readyPromise: Promise<void> | null = null
let refillInFlight = false
function getGlobalObj(): Record<string, any> | null {
// sm-crypto 读取的是 globalThis.crypto,垫片必须装在同一对象上
if (typeof globalThis !== 'undefined')
return globalThis as unknown as Record<string, any>
return null
}
function hasNativeGetRandomValues(): boolean {
try {
// 探测 globalThis.crypto:Node、h5:ssr 等环境有原生 CSPRNG 但无 window
const fn = getGlobalObj()?.crypto?.getRandomValues
// 排除垫片自身,否则失败重试会被短路成假成功
return typeof fn === 'function' && !(fn as any)[SHIM_MARKER]
}
catch {
return false
}
}
/**
* 按优先级探测提供异步 CSPRNG 的平台全局对象。
* uni.getRandomValues 仅有声明无实现,故排在 wx 之后兜底;
* 其余平台对象未在 TS 类型中声明,经 globalThis 探测,
* 对应平台未来实现同名 API 时自动生效。
*/
function findRandomApi(): { name: string, api: any } | null {
const globalObj = getGlobalObj()
const candidates: Array<[string, any]> = [
['wx', typeof wx !== 'undefined' ? wx : null],
['uni', typeof uni !== 'undefined' ? uni : null],
['my', globalObj ? globalObj.my : null],
['tt', globalObj ? globalObj.tt : null],
['swan', globalObj ? globalObj.swan : null],
['ks', globalObj ? globalObj.ks : null],
['qq', globalObj ? globalObj.qq : null],
['jd', globalObj ? globalObj.jd : null],
['lark', globalObj ? globalObj.lark : null],
['xhs', globalObj ? globalObj.xhs : null],
]
for (const [name, api] of candidates) {
if (api && typeof api.getRandomValues === 'function')
return { name, api }
}
return null
}
function fetchRandomChunk(length: number): Promise<Uint8Array> {
return new Promise((resolve, reject) => {
const found = findRandomApi()
if (!found && !bridgeProvider) {
reject(new Error(
'当前平台不支持获取密码学安全随机数(getRandomValues),无法安全执行 SM2 加密。'
+ '当前已适配:微信小程序(wx.getRandomValues)、浏览器、Node 环境、'
+ 'App 端(renderjs 桥接,需页面挂载 secure-random-bridge 组件);'
+ '其余小程序平台因缺少 CSPRNG API 被按 fail-closed 原则拒绝,'
+ '如需支持请扩展 secure-random.ts 的 findRandomApi 适配链。',
))
return
}
if (found) {
// 平台 API 异常时可能 success/fail 均不回调,超时兜底防止 readyPromise 死锁
const timer = setTimeout(() => {
reject(new Error(`${found.name}.getRandomValues 超时(5s 无响应)`))
}, 5000)
found.api.getRandomValues({
length,
success: (res: { randomValues: ArrayBuffer | Uint8Array | number[] }) => {
clearTimeout(timer)
resolve(new Uint8Array(res.randomValues))
},
fail: (err: unknown) => {
clearTimeout(timer)
reject(err instanceof Error ? err : new Error(`getRandomValues 调用失败: ${JSON.stringify(err)}`))
},
})
return
}
bridgeProvider!(length).then(resolve, (err: unknown) => {
reject(err instanceof Error ? err : new Error(`renderjs 桥接取随机失败: ${String(err)}`))
})
})
}
async function refillPool(totalLength: number): Promise<void> {
const chunks = await Promise.all(
Array.from({ length: Math.ceil(totalLength / CHUNK_SIZE) }, () => fetchRandomChunk(CHUNK_SIZE)),
)
for (const chunk of chunks) {
for (let i = 0; i < chunk.length; i++)
pool.push(chunk[i])
}
}
function scheduleRefill() {
if (refillInFlight)
return
refillInFlight = true
refillPool(256)
.catch((err) => {
// 补充失败仅告警:池仍够用则无感,耗尽时由 getRandomValues 抛错兜底
console.warn('[secure-random] 补充随机数缓冲池失败', err)
})
.finally(() => {
refillInFlight = false
})
}
function createGetRandomValues<T extends ArrayBufferView>(array: T): T {
// 按字节拷贝,兼容 Uint16Array/Uint32Array 等视图
const view = array as unknown as ArrayBufferView
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength)
if (pool.length < bytes.length) {
scheduleRefill()
throw new Error('安全随机数缓冲池未就绪或已耗尽,请先等待 ensureSecureRandomReady() 完成')
}
for (let i = 0; i < bytes.length; i++)
bytes[i] = pool[i]
pool = pool.slice(bytes.length)
if (pool.length < LOW_WATER_MARK)
scheduleRefill()
return array
}
;(createGetRandomValues as any)[SHIM_MARKER] = true
function installShim() {
const globalObj = getGlobalObj()
if (!globalObj)
throw new Error('无法获取全局对象,无法安装 crypto.getRandomValues 垫片')
if (globalObj.crypto && typeof globalObj.crypto.getRandomValues === 'function')
return
if (globalObj.crypto) {
// 只补缺的方法,保留宿主 crypto 其他成员;defineProperty 规避只读访问器赋值失败
Object.defineProperty(globalObj.crypto, 'getRandomValues', {
value: createGetRandomValues,
configurable: true,
writable: true,
})
}
else {
globalObj.crypto = { getRandomValues: createGetRandomValues }
}
}
/**
* 确保密码学安全随机源可用(首次 sm2 调用前必须 await)。
* 原生支持的环境直接就绪;缺失环境安装垫片并预热缓冲池;
* 无 CSPRNG 的环境 reject,由调用方 fail-closed 处理。
*/
export function ensureSecureRandomReady(): Promise<void> {
if (hasNativeGetRandomValues())
return Promise.resolve()
if (!readyPromise) {
readyPromise = (async () => {
installShim()
await refillPool(CHUNK_SIZE * CHUNK_COUNT)
})().catch((err) => {
// 失败后重置,允许后续重试
readyPromise = null
throw err
})
}
return readyPromise
}

View file

@ -17,7 +17,7 @@
"normalize.css": "^8.0.1",
"opus-decoder": "^0.7.7",
"opus-recorder": "^8.0.5",
"sm-crypto": "^0.3.13",
"sm-crypto": "^0.5.8",
"v-code-diff": "^1.16.0",
"vue": "^2.6.14",
"vue-axios": "^3.5.2",
@ -12485,9 +12485,9 @@
}
},
"node_modules/sm-crypto": {
"version": "0.3.13",
"resolved": "https://registry.npmmirror.com/sm-crypto/-/sm-crypto-0.3.13.tgz",
"integrity": "sha512-ztNF+pZq6viCPMA1A6KKu3bgpkmYti5avykRHbcFIdSipFdkVmfUw2CnpM2kBJyppIalqvczLNM3wR8OQ0pT5w==",
"version": "0.5.8",
"resolved": "https://registry.npmmirror.com/sm-crypto/-/sm-crypto-0.5.8.tgz",
"integrity": "sha512-bpz1/PthgZHcLHyIl28mbYZHmeuTDrdWpwHZ7BGzFjQuB7OOhjlbcPEMt44aqUfZ2S5YJXM8v20xYO1j9CC45Q==",
"license": "MIT",
"dependencies": {
"jsbn": "^1.1.0"

View file

@ -22,7 +22,7 @@
"normalize.css": "^8.0.1",
"opus-decoder": "^0.7.7",
"opus-recorder": "^8.0.5",
"sm-crypto": "^0.3.13",
"sm-crypto": "^0.5.8",
"v-code-diff": "^1.16.0",
"vue": "^2.6.14",
"vue-axios": "^3.5.2",

View file

@ -1,6 +1,7 @@
import Fly from 'flyio/dist/npm/fly';
import store from '../store/index';
import Constant from '../utils/constant';
import { getServiceUrl } from '../apis/api';
import { goToPage, isNotNull, showDanger, showWarning } from '../utils/index';
import i18n from '../i18n/index';
@ -8,13 +9,98 @@ const fly = new Fly()
// 设置超时
fly.config.timeout = 30000
// 独立 fly 实例给 silent refresh 用,避免任何回调链回到 sendRequest
const refreshFly = new Fly()
refreshFly.config.timeout = 30000
// silent refresh:剩 1h 触发换 token,单飞锁避免并发
const REFRESH_AHEAD_MS = 60 * 60 * 1000
let refreshPromise = null
function getTokenExpireAt() {
// 与 persistTokenExpireAt 同源读 localStorage(store 走的是 state.token 缓存,
// 刚写入 localStorage 后再走 store 拿不到补写的 _localStoredAt)
const raw = localStorage.getItem('token')
if (!raw) return 0
try {
const parsed = JSON.parse(raw)
if (!parsed || !parsed.expire) return 0
// login.vue 写入 store 时是 setToken(now),token 对象里没有 createdAt;
// 用 _localStoredAt 作为本地落地时间基准
return (parsed._localStoredAt || 0) + parsed.expire * 1000
} catch (e) {
return 0
}
}
// 首次见到该 token 时记下落地时间;同步刷新 localStorage 与 store,保证两端一致
function persistTokenExpireAt() {
const raw = localStorage.getItem('token')
if (!raw) return
try {
const parsed = JSON.parse(raw)
if (parsed && parsed.expire && !parsed._localStoredAt) {
parsed._localStoredAt = Date.now()
const next = JSON.stringify(parsed)
localStorage.setItem('token', next)
store.commit('setToken', next)
}
} catch (e) { /* ignore */ }
}
function shouldRefresh() {
persistTokenExpireAt()
const exp = getTokenExpireAt()
if (!exp) return false
return exp - Date.now() < REFRESH_AHEAD_MS
}
function doRefresh() {
// 直接走 fly.request,绕过 sendRequest,避免死循环触发 silent refresh
const raw = localStorage.getItem('token')
if (!raw) return Promise.reject(new Error('no token'))
let bearer
try {
bearer = JSON.parse(raw).token
} catch (e) {
return Promise.reject(e)
}
return refreshFly.request(getServiceUrl() + '/user/refresh', {}, {
method: 'POST',
headers: { Authorization: 'Bearer ' + bearer }
}).then((res) => {
const body = res && res.data
if (!body || (body.code !== 0 && body.code !== 'success')) {
throw new Error('refresh failed: ' + (body && body.msg))
}
const newDto = body.data
newDto._localStoredAt = Date.now()
store.commit('setToken', JSON.stringify(newDto))
return newDto
})
}
function triggerSilentRefresh() {
if (!refreshPromise) {
refreshPromise = doRefresh().catch((err) => {
store.commit('clearAuth')
goToPage(Constant.PAGE.LOGIN, true)
throw err
}).finally(() => {
refreshPromise = null
})
}
return refreshPromise
}
/**
* Request服务封装
*/
export default {
sendRequest,
reAjaxFun,
clearRequestTime
clearRequestTime,
triggerSilentRefresh
}
function sendRequest() {
@ -37,30 +123,41 @@ function sendRequest() {
acceptLanguage = 'en-US';
}
this._header['Accept-Language'] = acceptLanguage;
if (isNotNull(store.getters.getToken)) {
this._header.Authorization = 'Bearer ' + (JSON.parse(store.getters.getToken)).token
const doSend = () => {
if (isNotNull(store.getters.getToken)) {
this._header.Authorization = 'Bearer ' + (JSON.parse(store.getters.getToken)).token
}
// 打印请求信息
fly.request(this._url, this._data, {
method: this._method,
headers: this._header,
responseType: this._responseType
}).then((res) => {
const error = httpHandlerError(res, this._failCallback, this._networkFailCallback);
if (error) {
return
}
if (this._sucCallback) {
this._sucCallback(res)
}
}).catch((res) => {
// 打印失败响应
console.log('catch', res)
httpHandlerError(res, this._failCallback, this._networkFailCallback)
})
}
// 打印请求信息
fly.request(this._url, this._data, {
method: this._method,
headers: this._header,
responseType: this._responseType
}).then((res) => {
const error = httpHandlerError(res, this._failCallback, this._networkFailCallback);
if (error) {
return
}
if (this._sucCallback) {
this._sucCallback(res)
}
}).catch((res) => {
// 打印失败响应
console.log('catch', res)
httpHandlerError(res, this._failCallback, this._networkFailCallback)
})
// 剩 1h 内过期就先 silent refresh 再发,确保请求带新 token
if (shouldRefresh()) {
triggerSilentRefresh().then(doSend).catch(() => {
// 触发 refresh 后被拦截跳登录,这里什么都不用做
})
} else {
doSend()
}
return this
},
'success'(callback) {

View file

@ -3,7 +3,7 @@ import RequestService from '../httpRequest';
export default {
// 已绑设备
getAgentBindDevices(agentId, callback) {
getAgentBindDevices(agentId, callback, failCallback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/device/bind/${agentId}`)
.method('GET')
@ -11,15 +11,21 @@ export default {
RequestService.clearRequestTime();
callback(res);
})
.fail((err) => {
RequestService.clearRequestTime();
if (failCallback) {
failCallback(err);
}
})
.networkFail((err) => {
console.error('获取设备列表失败:', err);
RequestService.reAjaxFun(() => {
this.getAgentBindDevices(agentId, callback);
this.getAgentBindDevices(agentId, callback, failCallback);
});
}).send();
},
// 解绑设备
unbindDevice(device_id, callback) {
unbindDevice(device_id, callback, failCallback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/device/unbind`)
.method('POST')
@ -28,15 +34,21 @@ export default {
RequestService.clearRequestTime();
callback(res);
})
.fail((err) => {
RequestService.clearRequestTime();
if (failCallback) {
failCallback(err);
}
})
.networkFail((err) => {
console.error('解绑设备失败:', err);
RequestService.reAjaxFun(() => {
this.unbindDevice(device_id, callback);
this.unbindDevice(device_id, callback, failCallback);
});
}).send();
},
// 绑定设备
bindDevice(agentId, deviceCode, callback) {
bindDevice(agentId, deviceCode, callback, failCallback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/device/bind/${agentId}/${deviceCode}`)
.method('POST')
@ -44,14 +56,20 @@ export default {
RequestService.clearRequestTime();
callback(res);
})
.fail((err) => {
RequestService.clearRequestTime();
if (failCallback) {
failCallback(err);
}
})
.networkFail((err) => {
console.error('绑定设备失败:', err);
RequestService.reAjaxFun(() => {
this.bindDevice(agentId, deviceCode, callback);
this.bindDevice(agentId, deviceCode, callback, failCallback);
});
}).send();
},
updateDeviceInfo(id, payload, callback) {
updateDeviceInfo(id, payload, callback, failCallback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/device/update/${id}`)
.method('PUT')
@ -60,16 +78,22 @@ export default {
RequestService.clearRequestTime()
callback(res)
})
.fail((err) => {
RequestService.clearRequestTime();
if (failCallback) {
failCallback(err);
}
})
.networkFail((err) => {
console.error('更新OTA状态失败:', err)
this.$message.error(err.msg || '更新OTA状态失败')
RequestService.reAjaxFun(() => {
this.updateDeviceInfo(id, payload, callback)
this.updateDeviceInfo(id, payload, callback, failCallback)
})
}).send()
},
// 手动添加设备
manualAddDevice(params, callback) {
manualAddDevice(params, callback, failCallback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/device/manual-add`)
.method('POST')
@ -78,15 +102,21 @@ export default {
RequestService.clearRequestTime();
callback(res);
})
.fail((err) => {
RequestService.clearRequestTime();
if (failCallback) {
failCallback(err);
}
})
.networkFail((err) => {
console.error('手动添加设备失败:', err);
RequestService.reAjaxFun(() => {
this.manualAddDevice(params, callback);
this.manualAddDevice(params, callback, failCallback);
});
}).send();
},
// 获取设备状态
getDeviceStatus(agentId, callback) {
getDeviceStatus(agentId, callback, failCallback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/device/bind/${agentId}`)
.method('POST')
@ -95,14 +125,17 @@ export default {
RequestService.clearRequestTime();
callback(res);
})
.fail((res) => {
callback(res);
.fail((err) => {
RequestService.clearRequestTime();
if (failCallback) {
failCallback(err);
}
})
.networkFail((err) => {
console.error('获取设备状态失败:', err);
RequestService.reAjaxFun(() => {
this.getDeviceStatus(agentId, callback);
this.getDeviceStatus(agentId, callback, failCallback);
});
}).send();
},
}
}

View file

@ -19,7 +19,7 @@ export default {
})
.networkFail(() => {
RequestService.reAjaxFun(() => {
this.login(loginForm, callback)
this.login(loginForm, callback, failCallback)
})
}).send()
},

View file

@ -1,39 +1,37 @@
<template>
<el-dialog :visible="visible" @close="handleClose" width="24%" center>
<div
style="margin: 0 10px 10px;display: flex;align-items: center;gap: 10px;font-weight: 700;font-size: 20px;text-align: left;color: #3d4566;">
<div
style="width: 40px;height: 40px;border-radius: 50%;background: #5778ff;display: flex;align-items: center;justify-content: center;">
<img src="@/assets/home/equipment.png" alt="" style="width: 18px;height: 15px;" />
<CustomDialog
:title="$t('device.dialogTitle')"
:visible.sync="visible"
width="420px"
:confirmLoading="loading"
@confirm="confirm"
@cancel="cancel"
@close="handleClose"
:confirmText="$t('device.confirmButton')"
:cancelText="$t('device.cancelButton')"
>
<div class="add-device-body">
<div class="add-device-label">
<span class="required">*</span>
{{ $t('device.verificationCode') }}
</div>
{{ $t('device.dialogTitle') }}
<el-input
:placeholder="$t('device.verificationCodePlaceholder')"
v-model="deviceCode"
class="add-device-input"
@keyup.enter.native="confirm"
/>
</div>
<div style="height: 1px;background: #e8f0ff;" />
<div style="margin: 22px 15px;">
<div style="font-weight: 400;font-size: 14px;text-align: left;color: #3d4566;">
<div style="color: red;display: inline-block;">*</div>
<span style="font-size: 11px"> {{ $t('device.verificationCode') }}</span>
</div>
<div class="input-46" style="margin-top: 12px;">
<el-input :placeholder="$t('device.verificationCodePlaceholder')" v-model="deviceCode" @keyup.enter.native="confirm" />
</div>
</div>
<div style="display: flex;margin: 15px 15px;gap: 7px;">
<div class="dialog-btn" @click="confirm">
{{ $t('device.confirmButton') }}
</div>
<div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;" @click="cancel">
{{ $t('device.cancelButton') }}
</div>
</div>
</el-dialog>
</CustomDialog>
</template>
<script>
import Api from '@/apis/api';
import CustomDialog from './CustomDialog.vue';
export default {
name: 'AddDeviceDialog',
components: { CustomDialog },
props: {
visible: { type: Boolean, required: true },
agentId: { type: String, required: true }
@ -53,7 +51,8 @@ export default {
this.loading = true;
Api.device.bindDevice(
this.agentId,
this.deviceCode, ({ data }) => {
this.deviceCode,
({ data }) => {
this.loading = false;
if (data.code === 0) {
this.$emit('refresh');
@ -68,59 +67,53 @@ export default {
showClose: true
});
}
},
(err) => {
this.loading = false;
const msg = err && err.data && err.data.msg;
this.$message.error({
message: msg || this.$t('device.bindFailed'),
showClose: true
});
}
);
},
closeDialog() {
this.$emit('update:visible', false);
this.loading = false;
this.deviceCode = '';
this.$emit('update:visible', false);
},
cancel() {
this.$emit('update:visible', false)
this.deviceCode = ""
this.closeDialog();
},
handleClose() {
this.$emit('update:visible', false);
},
this.closeDialog();
}
}
}
</script>
<style scoped>
.input-46 {
border: 1px solid #e4e6ef;
background: #f6f8fb;
border-radius: 10px;
.add-device-body {
padding: 6px 4px 4px;
}
.dialog-btn {
cursor: pointer;
flex: 1;
border-radius: 23px;
background: #5778ff;
.add-device-label {
font-size: 14px;
color: #475569;
text-align: left;
margin-bottom: 12px;
}
.add-device-label .required {
color: #f56c6c;
margin-right: 2px;
}
.add-device-input ::v-deep(.el-input__inner) {
height: 40px;
font-weight: 500;
font-size: 12px;
color: #fff;
line-height: 40px;
text-align: center;
}
::v-deep .el-dialog {
border-radius: 15px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
::v-deep .el-dialog__headerbtn {
display: none;
}
::v-deep .el-dialog__body {
padding: 4px 6px;
}
::v-deep .el-dialog__header {
padding: 10px;
border-radius: 8px;
border-color: #e2e8f0;
font-size: 14px;
}
</style>

View file

@ -2,7 +2,8 @@
<CustomDialog
:visible.sync="dialogVisible"
:title="$t('modelConfigDialog.addModel')"
width="57%"
width="960px"
size="large"
class="add-model-dialog"
:confirmLoading="saving"
@close="handleClose"
@ -76,7 +77,14 @@
<el-form :model="formData.configJson" label-width="auto" label-position="left" class="custom-form">
<div v-for="(row, rowIndex) in chunkedCallInfoFields" :key="rowIndex" class="form-row">
<el-form-item v-for="field in row" :key="field.prop" :label="field.label" :prop="field.prop" style="flex: 1;">
<el-input v-model="formData.configJson[field.prop]" :placeholder="field.placeholder"
<el-select v-if="field.type === 'select'" v-model="formData.configJson[field.prop]"
:placeholder="field.placeholder" class="custom-input-bg" style="width: 100%">
<el-option v-for="opt in field.options" :key="opt" :label="opt" :value="opt"></el-option>
</el-select>
<el-input v-else-if="field.type === 'json-textarea'" v-model="formData.configJson[field.prop]" type="textarea"
:rows="3" :placeholder="field.placeholder" class="custom-input-bg">
</el-input>
<el-input v-else v-model="formData.configJson[field.prop]" :placeholder="field.placeholder"
:type="field.type || 'text'" class="custom-input-bg" :show-password="field.type === 'password'">
</el-input>
</el-form-item>
@ -160,7 +168,8 @@ export default {
fields: JSON.parse(item.fields || '[]').map(f => ({
label: f.label,
prop: f.key,
type: f.type === 'password' ? 'password' : 'text',
type: f.type === 'dict' ? 'json-textarea' : f.type === 'password' ? 'password' : (f.type === 'select' ? 'select' : 'text'),
options: f.options || [],
placeholder: `请输入${f.key}`
}))
}))
@ -203,6 +212,24 @@ export default {
return;
}
// dict 字段必须解析为 JSON 对象再提交,否则会以字符串入库
for (const field of this.providerFields) {
if (field.type !== 'json-textarea') continue;
const raw = this.formData.configJson[field.prop];
if (!raw || typeof raw === 'object') continue;
try {
const parsed = JSON.parse(raw);
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error('not object');
}
this.formData.configJson[field.prop] = parsed;
} catch (e) {
this.$message.error('必须输入字典格式(如 {"key":"value"})');
this.saving = false;
return;
}
}
const submitData = {
id: this.formData.id || '',
modelName: this.formData.modelName || '',

View file

@ -1,51 +1,53 @@
<template>
<el-dialog :visible="visible" @close="handleClose" width="25%" center @open="handleOpen">
<div
style="margin: 0 10px 10px;display: flex;align-items: center;gap: 10px;font-weight: 700;font-size: 20px;text-align: left;color: #3d4566;">
<div
style="width: 40px;height: 40px;border-radius: 50%;background: #5778ff;display: flex;align-items: center;justify-content: center;">
<img loading="lazy" src="@/assets/home/equipment.png" alt="" style="width: 18px;height: 15px;" />
<CustomDialog
:title="$t('addAgentDialog.title')"
:visible.sync="visible"
width="420px"
@confirm="confirm"
@cancel="cancel"
@close="handleClose"
:confirmText="$t('addAgentDialog.confirm')"
:cancelText="$t('addAgentDialog.cancel')"
@open="handleOpen"
>
<div class="add-agent-body">
<div class="add-agent-label">
<span class="required">*</span>
{{ $t('addAgentDialog.agentName') }}
</div>
{{ $t('addAgentDialog.title') }}
<el-input
maxLength="64"
ref="inputRef"
:placeholder="$t('addAgentDialog.placeholder')"
v-model="wisdomBodyName"
class="add-agent-input"
@keyup.enter.native="confirm"
/>
</div>
<div style="height: 1px;background: #e8f0ff;" />
<div style="margin: 22px 15px;">
<div style="font-weight: 400;text-align: left;color: #3d4566;">
<div style="color: red;display: inline-block;">*</div> {{ $t('addAgentDialog.agentName') }}:
</div>
<div class="input-46" style="margin-top: 12px;">
<el-input maxLength="64" ref="inputRef" :placeholder="$t('addAgentDialog.placeholder')" v-model="wisdomBodyName" @keyup.enter.native="confirm" />
</div>
</div>
<div style="display: flex;margin: 15px 15px;gap: 7px;">
<div class="dialog-btn" @click="confirm">
{{ $t('addAgentDialog.confirm') }}
</div>
<div class="dialog-btn" style="background: #e6ebff;border: 1px solid #adbdff;color: #5778ff;" @click="cancel">
{{ $t('addAgentDialog.cancel') }}
</div>
</div>
</el-dialog>
</CustomDialog>
</template>
<script>
import Api from '@/apis/api';
import CustomDialog from './CustomDialog.vue';
export default {
name: 'AddWisdomBodyDialog',
components: { CustomDialog },
props: {
visible: { type: Boolean, required: true }
},
data() {
return {
wisdomBodyName: "",
inputRef: null
wisdomBodyName: ""
}
},
methods: {
handleOpen() {
this.$nextTick(() => {
this.$refs.inputRef.focus();
if (this.$refs.inputRef && this.$refs.inputRef.focus) {
this.$refs.inputRef.focus();
}
});
},
confirm() {
@ -64,50 +66,37 @@ export default {
});
},
cancel() {
this.$emit('update:visible', false)
this.wisdomBodyName = ""
},
handleClose() {
this.wisdomBodyName = "";
this.$emit('update:visible', false);
},
handleClose() {
this.cancel();
}
}
}
</script>
<style scoped>
.input-46 {
border: 1px solid #e4e6ef;
background: #f6f8fb;
border-radius: 15px;
.add-agent-body {
padding: 6px 4px 4px;
}
.dialog-btn {
cursor: pointer;
flex: 1;
border-radius: 23px;
background: #5778ff;
.add-agent-label {
font-size: 14px;
color: #475569;
text-align: left;
margin-bottom: 12px;
}
.add-agent-label .required {
color: #f56c6c;
margin-right: 2px;
}
.add-agent-input ::v-deep(.el-input__inner) {
height: 40px;
font-weight: 500;
font-size: 12px;
color: #fff;
line-height: 40px;
text-align: center;
}
::v-deep .el-dialog {
border-radius: 15px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
::v-deep .el-dialog__headerbtn {
display: none;
}
::v-deep .el-dialog__body {
padding: 4px 6px;
}
::v-deep .el-dialog__header {
padding: 10px;
border-radius: 8px;
border-color: #e2e8f0;
font-size: 14px;
}
</style>

View file

@ -2115,17 +2115,18 @@ export default {
display: flex;
flex-direction: column;
overflow: hidden;
margin: 32px auto !important;
margin: 10px auto !important;
border-radius: 10px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
max-height: calc(100vh - 64px);
height: calc(100vh - 20px);
max-height: calc(100vh - 20px);
}
::v-deep .el-dialog__wrapper {
display: flex;
align-items: center;
align-items: stretch;
justify-content: center;
overflow: auto;
overflow: hidden;
}
::v-deep .el-dialog__header {
@ -2282,9 +2283,7 @@ export default {
}
.snapshot-table-wrapper {
max-height: 62vh;
overflow: auto;
@include scrollbar-style;
min-height: 420px;
}
.version-cell {
@ -2328,11 +2327,8 @@ export default {
}
.snapshot-diff {
min-height: 220px;
max-height: 68vh;
overflow: auto;
min-height: 420px;
padding-right: 2px;
@include scrollbar-style;
}
.restore-risk-alert {

View file

@ -2,7 +2,7 @@
<el-dialog
:title="$t('cache.dialogTitle')"
:visible.sync="visible"
width="70%"
width="80%"
:before-close="handleClose"
>
<div v-if="isLoading" class="loading-container">
@ -204,4 +204,24 @@ h3 {
margin-bottom: 10px;
font-weight: 500;
}
::v-deep .el-dialog {
margin: 10px auto !important;
height: calc(100vh - 20px);
max-height: calc(100vh - 20px);
border-radius: 10px;
display: flex;
flex-direction: column;
max-width: 1280px;
}
::v-deep .el-dialog__wrapper {
align-items: stretch;
}
::v-deep .el-dialog__body {
flex: 1;
max-height: calc(100vh - 20px - 130px);
overflow-y: auto;
}
</style>

View file

@ -3,6 +3,7 @@
:title="$t('chatHistory.with') + agentName + $t('chatHistory.dialogTitle')"
:visible.sync="dialogVisible"
width="80%"
size="large"
:footer="false"
:close-on-click-modal="false"
custom-class="chat-history-dialog">
@ -413,7 +414,8 @@ export default {
<style scoped>
.chat-container {
display: flex;
height: 100%;
flex: 1;
min-height: 0;
}
.session-list {
@ -610,10 +612,6 @@ export default {
display: flex;
gap: 10px;
border-top: 1px solid #eee;
position: absolute;
bottom: 0;
left: 0;
right: 0;
background-color: white;
}
@ -624,24 +622,18 @@ export default {
<style>
.chat-history-dialog {
display: flex;
flex-direction: column;
min-width: 700px;
margin: 0 !important;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: 98vh;
max-width: 85vw;
border-radius: 12px;
overflow: hidden;
/* 兜底,防止 size="large" 那个 height 没有生效时弹框缩成内容高度 */
height: calc(100vh - 20px) !important;
}
.chat-history-dialog .el-dialog__body {
padding: 0;
overflow: hidden;
height: calc(90vh - 54px);
/* 减去标题栏的高度 */
display: flex;
flex-direction: column;
/* 顶开 size="large" 默认的 100vh - 130px,让 body 真正撑到弹框底部,flex: 1 会自动填满 */
max-height: calc(100vh - 74px) !important;
}
</style>

View file

@ -1,11 +1,14 @@
<template>
<el-dialog
:visible.sync="dialogVisible"
width="900px"
<CustomDialog
:title="$t('contextProviderDialog.title')"
:close-on-click-modal="false"
custom-class="context-provider-dialog"
append-to-body
:visible.sync="dialogVisible"
width="960px"
size="large"
class="context-provider-dialog"
:closeOnClickModal="false"
:confirmText="$t('contextProviderDialog.confirm')"
:cancelText="$t('contextProviderDialog.cancel')"
@confirm="handleConfirm"
>
<div class="dialog-content">
<el-empty v-if="localProviders.length === 0" :description="$t('contextProviderDialog.noContextApi')">
@ -51,7 +54,7 @@
size="small"
class="flex-1"
></el-input>
<div class="row-controls">
<el-button
type="primary"
@ -104,17 +107,15 @@
</div>
</div>
</div>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">{{ $t('contextProviderDialog.cancel') }}</el-button>
<el-button type="primary" @click="handleConfirm">{{ $t('contextProviderDialog.confirm') }}</el-button>
</span>
</el-dialog>
</CustomDialog>
</template>
<script>
import CustomDialog from './CustomDialog.vue';
export default {
name: 'ContextProviderDialog',
components: { CustomDialog },
props: {
visible: {
type: Boolean,
@ -157,7 +158,7 @@ export default {
headers: Object.entries(headers).map(([key, value]) => ({ key, value }))
};
});
// 如果为空,添加一个默认块
if (this.localProviders.length === 0) {
this.localProviders.push({ url: '', headers: [{ key: '', value: '' }] });
@ -193,19 +194,22 @@ export default {
headers: headersObj
};
});
this.$emit('confirm', result);
this.dialogVisible = false;
this.$emit('update:visible', false);
}
}
};
</script>
<style scoped>
.context-provider-dialog ::v-deep .el-dialog__body {
padding: 16px 20px;
}
.dialog-content {
max-height: 60vh;
max-height: calc(100vh - 280px);
overflow-y: auto;
padding: 20px 25px;
padding: 0 5px;
}
.dialog-content::-webkit-scrollbar {
@ -230,7 +234,7 @@ export default {
flex: 1;
border-radius: 12px;
border: 1px solid #e4e7ed;
border-left: 4px solid #409EFF; /* 左侧强调色 */
border-left: 4px solid #409EFF;
background-color: #fff;
transition: all 0.3s ease;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
@ -261,7 +265,7 @@ export default {
text-align: right;
font-size: 13px;
white-space: nowrap;
line-height: 32px; /* 垂直居中对齐 */
line-height: 32px;
}
.flex-1 {
@ -327,3 +331,4 @@ export default {
margin-right: 8px;
}
</style>

View file

@ -7,7 +7,7 @@
:close-on-press-escape="closeOnPressEscape"
:show-close="showClose"
:destroy-on-close="destroyOnClose"
:custom-class="customClass"
:custom-class="dialogCustomClass"
class="custom-dialog"
@close="handleClose"
@open="handleOpen"
@ -54,7 +54,7 @@ export default {
},
width: {
type: String,
default: "600px"
default: "720px"
},
footer: {
type: Boolean,
@ -80,6 +80,11 @@ export default {
type: String,
default: ""
},
size: {
type: String,
default: "small",
validator: (val) => ["small", "large"].includes(val),
},
cancelText: {
type: String,
default: "取消"
@ -94,6 +99,15 @@ export default {
dialogVisible: this.visible
};
},
computed: {
dialogCustomClass() {
const classes = ["custom-dialog"];
if (this.customClass) classes.push(this.customClass);
if (this.size === "large") classes.push("custom-dialog--large");
if (String(this.width).includes("%")) classes.push("custom-dialog--fluid");
return classes.join(" ");
},
},
components: {
CustomButton
},
@ -124,110 +138,134 @@ export default {
</script>
<style lang="scss" scoped>
.custom-dialog {
::v-deep .el-dialog {
border-radius: 10px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
/* 大档与小档通过 .custom-dialog--large 区分 */
::v-deep .el-dialog.custom-dialog {
border-radius: 10px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
margin: 5vh auto !important;
display: flex;
flex-direction: column;
max-height: calc(100vh - 10vh);
}
::v-deep .el-dialog__header {
padding: 16px 20px 12px;
background: linear-gradient(135deg, #e2eeff, #edeafe);
text-align: left;
}
::v-deep .el-dialog__body {
max-height: calc(100vh - 220px);
overflow-y: auto;
padding: 20px;
}
::v-deep .el-dialog__title {
font-size: 16px;
/* .v-modal 样式由 global.scss 全局定义 */
::v-deep .el-dialog__header {
padding: 16px 20px 12px;
background: linear-gradient(135deg, #e2eeff, #edeafe);
text-align: left;
}
::v-deep .el-dialog__title {
font-size: 16px;
font-weight: 500;
color: #1a1a1a;
}
::v-deep .dialog-title {
font-size: 18px;
display: inline-flex;
align-items: center;
> span {
line-height: 18px;
font-weight: 500;
color: #1a1a1a;
}
}
.dialog-title {
::v-deep .title-icon {
width: 24px;
height: 24px;
margin-right: 8px;
}
::v-deep .el-dialog__headerbtn {
top: 12px;
right: 16px;
width: 32px;
height: 32px;
border: none;
border-radius: 50%;
background: #fff;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
display: flex;
align-items: center;
justify-content: center;
.el-dialog__close {
font-size: 18px;
display: inline-flex;
align-items: center;
> span {
line-height: 18px;
font-weight: 500;
}
color: #666;
position: static;
transform: none;
}
.title-icon {
width: 24px;
height: 24px;
margin-right: 8px;
}
::v-deep .el-dialog__headerbtn {
top: 12px;
right: 16px;
width: 32px;
height: 32px;
border: none;
border-radius: 50%;
&:hover {
background: #fff;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
.el-dialog__close {
font-size: 18px;
color: #666;
position: static;
transform: none;
}
&:hover {
background: #fff;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
.el-dialog__close {
color: #333;
}
}
}
::v-deep .el-dialog__body {
padding: 20px;
}
::v-deep .el-dialog__footer {
padding: 12px 20px 16px;
}
.dialog-footer {
display: flex;
justify-content: flex-end;
.el-button {
padding: 10px 20px;
display: flex;
align-items: center;
}
.el-button--primary {
background: linear-gradient(to right, #4a7cfd, #8154fc);
border: none;
&:hover,
&:focus {
background: linear-gradient(to right, #4a7cfd, #8154fc);
opacity: 0.85;
}
}
.confirm-inner {
display: inline-flex;
align-items: center;
}
.confirm-icon {
width: 16px;
height: 16px;
margin-right: 4px;
color: #333;
}
}
}
::v-deep .el-dialog__footer {
padding: 12px 20px 16px;
}
::v-deep .dialog-footer {
display: flex;
justify-content: flex-end;
.el-button {
padding: 10px 20px;
display: flex;
align-items: center;
}
.el-button--primary {
background: linear-gradient(to right, #4a7cfd, #8154fc);
border: none;
&:hover,
&:focus {
background: linear-gradient(to right, #4a7cfd, #8154fc);
opacity: 0.85;
}
}
.confirm-inner {
display: inline-flex;
align-items: center;
}
.confirm-icon {
width: 16px;
height: 16px;
margin-right: 4px;
}
}
/* 大档:上下各留 10px 让边框和圆角可见 */
::v-deep .el-dialog.custom-dialog.custom-dialog--large {
margin: 10px auto !important;
height: calc(100vh - 20px);
max-height: calc(100vh - 20px);
border-radius: 10px;
}
::v-deep .el-dialog.custom-dialog.custom-dialog--large.custom-dialog--fluid {
max-width: var(--dialog-table-max);
}
::v-deep .el-dialog.custom-dialog--large .el-dialog__body {
max-height: calc(100vh - 20px - 110px);
flex: 1;
min-height: 0;
}
</style>

View file

@ -111,6 +111,10 @@ export default {
this.saving = true
// 提交成功后将关闭对话框的逻辑交给父组件处理
this.$emit('submit', this.form)
// 兜底:父组件若未在回调内重置 saving,3 秒后强制释放加载状态
setTimeout(() => {
this.saving = false
}, 3000)
}
})
},

View file

@ -9,7 +9,7 @@
>
<el-form :model="deviceForm" :rules="rules" ref="deviceForm" label-width="auto">
<el-form-item :label="$t('manualAddDeviceDialog.deviceType')" prop="board">
<el-select v-model="deviceForm.board" :placeholder="$t('manualAddDeviceDialog.deviceTypePlaceholder')" style="width: 100%">
<el-select v-model="deviceForm.board" :placeholder="$t('manualAddDeviceDialog.deviceTypePlaceholder')" style="width: 100%" filterable>
<el-option
v-for="item in firmwareTypes"
:key="item.key"

View file

@ -2,14 +2,14 @@
<CustomDialog
:title="$t('modelConfigDialog.editModel')"
:visible.sync="dialogVisible"
width="57%"
width="960px"
size="large"
class="model-edit-dialog"
:confirmLoading="saving"
@confirm="handleSave"
@close="handleClose"
@open="handleOpen"
>
<div class="dialog-scroll-body">
<div class="header-row">
<div class="section-title">{{ $t("modelConfigDialog.modelInfo") }}</div>
<div class="switch-group">
@ -81,6 +81,11 @@
"></el-input>
</template>
<el-select v-else-if="field.type === 'select'" v-model="form.configJson[field.prop]"
:placeholder="field.placeholder" style="width: 100%">
<el-option v-for="opt in field.options" :key="opt" :label="opt" :value="opt"></el-option>
</el-select>
<el-input v-else v-model="form.configJson[field.prop]" :placeholder="field.placeholder" :type="field.type"
:show-password="field.type === 'password'" @focus="
isSensitiveField(field.prop)
@ -93,7 +98,6 @@
</div>
</template>
</el-form>
</div>
</CustomDialog>
</template>
@ -313,7 +317,10 @@ export default {
? "json-textarea"
: f.type === "password"
? "password"
: "text",
: f.type === "select"
? "select"
: "text",
options: f.options || [],
placeholder: `请输入${f.key}`,
}));
@ -331,6 +338,17 @@ export default {
if (!configJson.hasOwnProperty(field.prop)) {
configJson[field.prop] = "";
} else if (field.type === "json-textarea") {
// 兼容已保存为 JSON 字符串的字典,避免再次序列化后无法编辑。
if (typeof configJson[field.prop] === "string") {
try {
const parsed = JSON.parse(configJson[field.prop]);
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
configJson[field.prop] = parsed;
}
} catch {
// 保留非法值的显示,由现有校验提示用户修正。
}
}
this.$set(
this.fieldJsonMap,
field.prop,
@ -466,19 +484,16 @@ export default {
<style lang="scss" scoped>
@import '@/styles/global.scss';
::v-deep .el-dialog {
margin-top: 6vh !important;
}
::v-deep .el-dialog__body {
max-height: 60vh;
overflow-y: auto;
@include scrollbar-style;
}
.model-edit-dialog {
::v-deep .el-dialog__body {
padding: 24px 40px;
}
.header-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 4px;
}
.section-title {
@ -511,7 +526,7 @@ export default {
.section-divider {
height: 1px;
background: #e9e9e9;
margin-bottom: 16px;
margin-bottom: 18px;
}
.form-row {
@ -521,10 +536,13 @@ export default {
}
::v-deep .el-input__inner {
height: 32px;
height: 38px;
}
::v-deep .el-form-item {
margin-bottom: 10px;
margin-bottom: 14px;
}
::v-deep .el-form-item__label {
line-height: 38px;
}
}
</style>

View file

@ -2,11 +2,13 @@
<CustomDialog
:title="title"
:visible.sync="visible"
width="600px"
width="720px"
class="param-dialog-wrapper"
@confirm="submit"
@close="cancel"
:confirmLoading="saving"
:confirmText="$t('button.ok')"
:cancelText="$t('button.cancel')"
>
<div class="dialog-container">
<el-form :model="form" :rules="rules" ref="form" label-width="auto" label-position="left" class="param-form">
@ -147,6 +149,7 @@ export default {
cancel() {
this.saving = false; // 取消时重置状态
this.dialogKey = Date.now();
this.$emit('update:visible', false);
this.$emit('cancel');
},
@ -183,36 +186,19 @@ export default {
};
</script>
<style>
.custom-param-dialog {
border-radius: 16px !important;
overflow: hidden;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15) !important;
border: none !important;
.el-dialog__header {
display: none;
}
.el-dialog__body {
padding: 0 !important;
border-radius: 16px;
}
}
</style>
<style scoped lang="scss">
.param-dialog-wrapper {
.param-form {
.form-item {
margin-bottom: 20px;
margin-bottom: 28px;
:deep(.el-form-item__label) {
color: #475569;
font-weight: 500;
padding-right: 12px;
padding-right: 14px;
text-align: right;
font-size: 14px;
font-size: 15px;
letter-spacing: 0.2px;
line-height: 44px;
}
}
@ -221,7 +207,7 @@ export default {
background-color: #ffffff;
border-radius: 8px;
border: 1px solid #e2e8f0;
height: 42px;
height: 44px;
padding: 0 14px;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
font-size: 14px;
@ -248,7 +234,7 @@ export default {
background-color: #ffffff;
border-radius: 8px;
border: 1px solid #e2e8f0;
height: 42px;
height: 44px;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
font-size: 14px;
color: #334155;
@ -272,7 +258,7 @@ export default {
background-color: #ffffff;
border-radius: 8px;
border: 1px solid #e2e8f0;
padding: 12px 14px;
padding: 10px 14px;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
font-size: 14px;
color: #334155;
@ -291,10 +277,6 @@ export default {
}
}
}
.remark-item :deep(.el-form-item__label) {
margin-top: -4px;
}
}
}
</style>

View file

@ -2,7 +2,8 @@
<CustomDialog
:title="title"
:visible.sync="visible"
width="57%"
width="960px"
size="large"
class="provider-dialog-wrapper"
@confirm="submit"
@close="handleClose"
@ -308,6 +309,11 @@ export default {
this.resetForm();
}
});
// 兜底:父组件若未在回调内清 saving,3 秒后强制释放加载状态
setTimeout(() => {
this.saving = false;
}, 3000);
}
});
},

View file

@ -75,6 +75,8 @@
<el-select
v-model="replacementWordIds"
multiple
filterable
collapse-tags
:placeholder="$t('replacementDialog.selectPlaceholder')"
class="replacement-word-select"
>

View file

@ -1,5 +1,5 @@
<template>
<CustomDialog :visible.sync="localVisible" :title="$t('modelConfig.voiceManagement')" width="90%"
<CustomDialog :visible.sync="localVisible" :title="$t('modelConfig.voiceManagement')" width="80%" size="large"
:close-on-click-modal="true" :destroy-on-close="false" :footer="false" :append-to-body="true"
@close="handleClose">
<div class="scroll-wrapper">

View file

@ -2,7 +2,8 @@
<CustomDialog
:title="$t('voiceClone.dialogTitle')"
:visible.sync="innerVisible"
width="900px"
width="960px"
size="large"
:footer="false"
@close="handleDialogClose"
>

View file

@ -9,7 +9,7 @@
>
<el-form :model="form" :rules="rules" ref="form" label-width="auto" label-position="left" class="param-form">
<el-form-item :label="$t('voicePrintDialog.voicePrintVector')" prop="audioId" class="form-item">
<el-select v-model="form.audioId" :placeholder="$t('voicePrintDialog.selectVoiceMessage')" class="custom-select">
<el-select v-model="form.audioId" :placeholder="$t('voicePrintDialog.selectVoiceMessage')" class="custom-select" filterable>
<el-option v-for="item in valueTypeOptions" :key="item.audioId" :label="item.content" :value="item.audioId">
<span style="float: left">{{ item.content }}</span>
<span style="float: right; color: #8492a6; font-size: 13px">

View file

@ -477,8 +477,8 @@ export default {
'device.type': 'Gerätetyp',
'device.status': 'Gerätestatus',
'device.dialogTitle': 'Gerät hinzufügen',
'device.verificationCode': 'Bestätigungscode:',
'device.verificationCodePlaceholder': 'Bitte den 6-stelligen Bestätigungscode eingeben, der vom Gerät gesendet wird..',
'device.verificationCode': 'Bestätigungscode',
'device.verificationCodePlaceholder': 'Bitte den 6-stelligen Bestätigungscode eingeben, der vom Gerät gesendet wird…',
'device.confirmButton': 'Bestätigen',
'device.cancelButton': 'Abbrechen',
'device.input6DigitCode': 'Bitte 6-stelligen Bestätigungscode eingeben',
@ -820,7 +820,7 @@ export default {
// Add agent dialog text
'addAgentDialog.title': 'Agent hinzufügen',
'addAgentDialog.agentName': 'Agent-Name',
'addAgentDialog.placeholder': 'Bitte Agent-Namen eingeben..',
'addAgentDialog.placeholder': 'Bitte Agent-Namen eingeben…',
'addAgentDialog.confirm': 'Bestätigen',
'addAgentDialog.cancel': 'Abbrechen',
'addAgentDialog.nameRequired': 'Bitte Agent-Namen eingeben',

View file

@ -477,8 +477,8 @@ export default {
'device.type': 'Device Type',
'device.status': 'Device Status',
'device.dialogTitle': 'Add Device',
'device.verificationCode': 'Verification Code:',
'device.verificationCodePlaceholder': 'Please enter the 6-digit verification code broadcasted by the device..',
'device.verificationCode': 'Verification Code',
'device.verificationCodePlaceholder': 'Please enter the 6-digit verification code broadcasted by the device…',
'device.confirmButton': 'Confirm',
'device.cancelButton': 'Cancel',
'device.input6DigitCode': 'Please enter a 6-digit verification code',
@ -820,7 +820,7 @@ export default {
// Add agent dialog text
'addAgentDialog.title': 'Add Agent',
'addAgentDialog.agentName': 'Agent Name',
'addAgentDialog.placeholder': 'Please enter agent name..',
'addAgentDialog.placeholder': 'Please enter agent name…',
'addAgentDialog.confirm': 'Confirm',
'addAgentDialog.cancel': 'Cancel',
'addAgentDialog.nameRequired': 'Please enter agent name',

View file

@ -477,8 +477,8 @@ export default {
'device.type': 'Tipo de Dispositivo',
'device.status': 'Status do Dispositivo',
'device.dialogTitle': 'Adicionar Dispositivo',
'device.verificationCode': 'Código de Verificação:',
'device.verificationCodePlaceholder': 'Por favor, insira o código de verificação de 6 dígitos transmitido pelo dispositivo..',
'device.verificationCode': 'Código de Verificação',
'device.verificationCodePlaceholder': 'Por favor, insira o código de verificação de 6 dígitos transmitido pelo dispositivo…',
'device.confirmButton': 'Confirmar',
'device.cancelButton': 'Cancelar',
'device.input6DigitCode': 'Por favor, insira um código de verificação de 6 dígitos',
@ -820,7 +820,7 @@ export default {
// Diálogo de adicionar agente
'addAgentDialog.title': 'Adicionar Agente',
'addAgentDialog.agentName': 'Nome do Agente',
'addAgentDialog.placeholder': 'Por favor, insira o nome do agente..',
'addAgentDialog.placeholder': 'Por favor, insira o nome do agente…',
'addAgentDialog.confirm': 'Confirmar',
'addAgentDialog.cancel': 'Cancelar',
'addAgentDialog.nameRequired': 'Por favor, insira o nome do agente',

View file

@ -477,8 +477,8 @@ export default {
'device.type': 'Loại thiết bị',
'device.status': 'Trạng thái thiết bị',
'device.dialogTitle': 'Thêm thiết bị',
'device.verificationCode': 'Mã xác minh:',
'device.verificationCodePlaceholder': 'Vui lòng nhập mã xác minh 6 chữ số được phát từ thiết bị..',
'device.verificationCode': 'Mã xác minh',
'device.verificationCodePlaceholder': 'Vui lòng nhập mã xác minh 6 chữ số được phát từ thiết bị…',
'device.confirmButton': 'Xác nhận',
'device.cancelButton': 'Hủy bỏ',
'device.input6DigitCode': 'Vui lòng nhập mã xác minh 6 chữ số',
@ -820,7 +820,7 @@ export default {
// Add agent dialog text
'addAgentDialog.title': 'Thêm tác nhân',
'addAgentDialog.agentName': 'Tên tác nhân',
'addAgentDialog.placeholder': 'Vui lòng nhập tên tác nhân..',
'addAgentDialog.placeholder': 'Vui lòng nhập tên tác nhân…',
'addAgentDialog.confirm': 'Xác nhận',
'addAgentDialog.cancel': 'Hủy bỏ',
'addAgentDialog.nameRequired': 'Vui lòng nhập tên tác nhân',

View file

@ -477,8 +477,8 @@ export default {
'device.type': '设备类型',
'device.status': '设备状态',
'device.dialogTitle': '添加设备',
'device.verificationCode': '验证码:',
'device.verificationCodePlaceholder': '请输入设备播报的6位数验证码..',
'device.verificationCode': '验证码',
'device.verificationCodePlaceholder': '请输入设备播报的6位数验证码…',
'device.confirmButton': '确定',
'device.cancelButton': '取消',
'device.input6DigitCode': '请输入6位数字验证码',
@ -820,7 +820,7 @@ export default {
// 添加智能体对话框文本
'addAgentDialog.title': '添加智能体',
'addAgentDialog.agentName': '智能体名称',
'addAgentDialog.placeholder': '请输入智能体名称..',
'addAgentDialog.placeholder': '请输入智能体名称…',
'addAgentDialog.confirm': '确定',
'addAgentDialog.cancel': '取消',
'addAgentDialog.nameRequired': '请输入智能体名称',

View file

@ -477,8 +477,8 @@ export default {
'device.type': '設備類型',
'device.status': '設備狀態',
'device.dialogTitle': '添加設備',
'device.verificationCode': '驗證碼:',
'device.verificationCodePlaceholder': '請輸入設備播報的6位數驗證碼..',
'device.verificationCode': '驗證碼',
'device.verificationCodePlaceholder': '請輸入設備播報的6位數驗證碼…',
'device.confirmButton': '確定',
'device.cancelButton': '取消',
'device.input6DigitCode': '請輸入6位數字驗證碼',
@ -820,7 +820,7 @@ export default {
// 添加智能體對話框文本
'addAgentDialog.title': '添加智能體',
'addAgentDialog.agentName': '智能體名稱',
'addAgentDialog.placeholder': '請輸入智能體名稱..',
'addAgentDialog.placeholder': '請輸入智能體名稱…',
'addAgentDialog.confirm': '確定',
'addAgentDialog.cancel': '取消',
'addAgentDialog.nameRequired': '請輸入智能體名稱',

View file

@ -22,6 +22,13 @@ Vue.config.productionTip = false
// 注册Service Worker
registerServiceWorker();
// 应用启动时把 localStorage 里的 token 同步进 store,避免守卫放行后首次请求时
// httpRequest 读到 state.token=null 而漏带 Authorization 头触发 401 跳登录
const cachedToken = localStorage.getItem('token')
if (cachedToken) {
store.commit('setToken', cachedToken)
}
// 创建Vue实例
new Vue({
router,

View file

@ -81,10 +81,6 @@ const routes = [
name: 'ParamsManagement',
component: function () {
return import('../views/ParamsManagement.vue')
},
meta: {
requiresAuth: true,
title: '参数管理'
}
},
{
@ -92,10 +88,6 @@ const routes = [
name: 'KnowledgeBaseManagement',
component: function () {
return import('../views/KnowledgeBaseManagement.vue')
},
meta: {
requiresAuth: true,
title: '知识库管理'
}
},
{
@ -103,10 +95,6 @@ const routes = [
name: 'ServerSideManager',
component: function () {
return import('../views/ServerSideManager.vue')
},
meta: {
requiresAuth: true,
title: '服务端管理'
}
},
{
@ -114,10 +102,6 @@ const routes = [
name: 'OtaManagement',
component: function () {
return import('../views/OtaManagement.vue')
},
meta: {
requiresAuth: true,
title: 'OTA管理'
}
},
{
@ -125,10 +109,6 @@ const routes = [
name: 'VoiceResourceManagement',
component: function () {
return import('../views/VoiceResourceManagement.vue')
},
meta: {
requiresAuth: true,
title: '音色资源开通'
}
},
{
@ -136,10 +116,6 @@ const routes = [
name: 'VoiceCloneManagement',
component: function () {
return import('../views/VoiceCloneManagement.vue')
},
meta: {
requiresAuth: true,
title: '音色克隆管理'
}
},
{
@ -178,10 +154,6 @@ const routes = [
name: 'FeatureManagement',
component: function () {
return import('../views/FeatureManagement.vue')
},
meta: {
requiresAuth: true,
title: '功能配置'
}
},
// 替换词管理
@ -190,10 +162,6 @@ const routes = [
name: 'ReplacementWordManagement',
component: function () {
return import('../views/ReplacementWordManagement.vue')
},
meta: {
requiresAuth: true,
title: '替换词管理'
}
},
// 通讯录管理页面路由
@ -202,10 +170,6 @@ const routes = [
name: 'AddressBookManagement',
component: function () {
return import('../views/AddressBookManagement.vue')
},
meta: {
requiresAuth: true,
title: '通讯录管理'
}
},
]
@ -228,21 +192,27 @@ VueRouter.prototype.push = function push(location) {
})
}
// 需要登录才能访问的路由
const protectedRoutes = ['home', 'RoleConfig', 'DeviceManagement', 'UserManagement', 'ModelConfig', 'KnowledgeBaseManagement', 'KnowledgeFileUpload', 'AddressBookManagement']
// 匿名可访问的路由白名单
const anonRouteNames = new Set(['login', 'Register', 'RetrievePassword', 'welcome'])
// 路由守卫
router.beforeEach((to, from, next) => {
// 检查是否是需要保护的路由
if (protectedRoutes.includes(to.name)) {
// 从localStorage获取token
const token = localStorage.getItem('token')
if (!token) {
// 未登录,跳转到登录页
next({ name: 'login', query: { redirect: to.fullPath } })
return
}
const token = localStorage.getItem('token');
const isAnonRoute = anonRouteNames.has(to.name);
if (isAnonRoute && token) {
next({ name: 'home', replace: true })
return
}
if (!isAnonRoute && !token) {
next({
name: 'login',
replace: true
})
return
}
next()
})

View file

@ -43,4 +43,31 @@ select:-webkit-autofill:focus {
background: #f0f3fe;
border-radius: 3px;
}
}
// 大弹框宽度档位(表格档使用)
:root {
--dialog-table-max: 1280px;
}
/* 全局弹框遮罩 */
.v-modal {
background: rgba(15, 23, 42, 0.55) !important;
backdrop-filter: blur(2px);
}
/* 全局弹框 wrapper 居中 */
.el-dialog__wrapper.custom-dialog {
display: flex;
align-items: center;
justify-content: center;
overflow: auto;
}
/* 首页删除智能体确认弹框 wrapper 居中(非 CustomDialog,需单独命中) */
.el-dialog__wrapper.delete-agent-dialog {
display: flex;
align-items: center;
justify-content: center;
overflow: auto;
}

View file

@ -74,7 +74,8 @@
:visible.sync="dialogVisible"
:confirm-loading="confirmLoading"
:footer="true"
:width="'1200px'"
:width="'1080px'"
size="large"
@confirm="handleDialogConfirm"
@cancel="dialogVisible = false"
>
@ -92,7 +93,7 @@
:placeholder="$t('templateQuickConfig.agentSettings.systemPromptPlaceholder')"
show-word-limit
maxlength="2000"
:rows="16"
:autosize="{ minRows: 16 }"
/>
</el-form-item>
</el-form>

View file

@ -114,6 +114,7 @@
:title="`${$t('knowledgeFileUpload.viewSlices')} - ${currentDocumentName}`"
:visible.sync="sliceDialogVisible"
width="1200px"
size="large"
:footer="false"
>
<div class="slice-management">
@ -189,14 +190,15 @@
<CustomDialog
:title="$t('knowledgeFileUpload.retrievalTest')"
:visible.sync="retrievalTestDialogVisible"
width="900px"
width="1200px"
size="large"
:close-on-click-modal="false"
:confirm-text="$t('knowledgeFileUpload.executeTest')"
:confirmLoading="retrievalTestLoading"
@confirm="runRetrievalTest"
>
<div class="retrieval-test-form">
<el-form :model="retrievalTestForm" label-width="100px">
<el-form :model="retrievalTestForm" label-width="100px" @submit.native.prevent>
<el-form-item :label="$t('knowledgeFileUpload.testQuestion')" required>
<el-input
v-model="retrievalTestForm.question"
@ -1014,10 +1016,12 @@ export default {
.slice-content-container {
flex: 1;
overflow: hidden;
display: flex;
flex-direction: column;
}
.slice-cards-container {
max-height: 60vh;
flex: 1;
overflow-y: auto;
padding-right: 4px;
@ -1082,6 +1086,7 @@ export default {
}
.no-slice-data {
flex: 1;
min-height: 200px;
display: flex;
align-items: center;
@ -1171,8 +1176,20 @@ export default {
/* ========== Retrieval Test Dialog ========== */
.retrieval-test-form {
display: flex;
flex-direction: column;
height: 100%;
.retrieval-test-result {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
}
.result-chunks {
max-height: 400px;
flex: 1;
min-height: 0;
overflow-y: auto;
}

View file

@ -613,6 +613,8 @@ export default {
.nav-panel {
min-width: 242px;
height: 100%;
box-sizing: border-box;
overflow-y: auto;
border-right: 1px solid #ebeef5;
background: linear-gradient(
120deg,
@ -629,6 +631,7 @@ export default {
.nav-panel .el-menu-item {
height: 50px;
flex-shrink: 0;
background: #e9f0ff;
line-height: 50px;
border-radius: 4px 0 0 4px !important;

View file

@ -68,7 +68,7 @@
</div>
<!-- 新增/编辑固件对话框 -->
<firmware-dialog :title="dialogTitle" :visible.sync="dialogVisible" :form="firmwareForm"
<firmware-dialog ref="firmwareDialog" :title="dialogTitle" :visible.sync="dialogVisible" :form="firmwareForm"
:firmware-types="firmwareTypes" @submit="handleSubmit" @cancel="dialogVisible = false" />
<el-footer>
<version-footer />
@ -210,6 +210,7 @@ export default {
showClose: true
});
}
this.$refs.firmwareDialog?.resetSaving();
});
} else {
Api.ota.saveOta(form, (res) => {
@ -227,6 +228,7 @@ export default {
showClose: true
});
}
this.$refs.firmwareDialog?.resetSaving();
});
}
},

View file

@ -255,7 +255,6 @@ export default {
this.dialogVisible = true;
},
handleSubmit({ form, done }) {
this.loading = true;
if (form.id) {
Api.model.updateModelProvider(form, ({ data }) => {
if (data.code === 0) {
@ -264,7 +263,14 @@ export default {
message: this.$t('common.updateSuccess'),
showClose: true
});
this.dialogVisible = false;
} else {
this.$message.error({
message: data.msg || this.$t('common.updateFailure'),
showClose: true
});
}
done && done();
});
} else {
Api.model.addModelProvider(form, ({ data }) => {
@ -275,12 +281,16 @@ export default {
showClose: true
});
this.total += 1;
this.dialogVisible = false;
} else {
this.$message.error({
message: data.msg || this.$t('common.addFailure'),
showClose: true
});
}
done && done();
});
}
this.loading = false;
this.dialogVisible = false;
done && done();
},
deleteSelectedProviders() {
const selectedRows = this.providersList.filter(row => row.selected);

View file

@ -74,7 +74,7 @@
<template v-else>
<div class="input-box">
<div style="display: flex; align-items: center; width: 100%">
<el-select v-model="form.areaCode" style="width: 220px; margin-right: 10px">
<el-select v-model="form.areaCode" style="width: 220px; margin-right: 10px" filterable>
<el-option v-for="item in mobileAreaList" :key="item.key" :label="`${item.name} (${item.key})`"
:value="item.key" />
</el-select>

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