Merge branch 'main' into yinseyemian

This commit is contained in:
hrz
2025-11-17 17:09:53 +08:00
committed by GitHub
89 changed files with 8922 additions and 6013 deletions
+2 -1
View File
@@ -182,4 +182,5 @@ uploadfile
# Do not ignore env and json files inside manager-mobile
!main/manager-mobile/**/env/
!main/manager-mobile/**/.env*
!main/manager-mobile/**/*.json
!main/manager-mobile/**/*.json
!main/xiaozhi-server/**/*.json
+20 -16
View File
@@ -6,29 +6,24 @@
本项目基于人机共生智能理论和技术研发智能终端软硬件体系<br/>为开源智能硬件项目
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a>提供后端服务<br/>
根据<a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">小智通信协议</a>使用Python、Java、Vue实现<br/>
支持MQTT+UDP协议、Websocket协议、MCP接入点、声纹识别
支持MQTT+UDP协议、Websocket协议、MCP接入点、声纹识别、知识库
</p>
<p align="center">
<a href="./README_en.md">English</a>
· <a href="./docs/FAQ.md">常见问题</a>
<a href="./docs/FAQ.md">常见问题</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">反馈问题</a>
· <a href="./README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3">部署文档</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">更新日志</a>
</p>
<p align="center">
<a href="./README.md"><img alt="简体中文版自述文件" src="https://img.shields.io/badge/简体中文-DBEDFA"></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="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/graphs/contributors">
<img alt="GitHub Contributors" src="https://img.shields.io/github/contributors/xinnan-tech/xiaozhi-esp32-server?logo=github" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">
<img alt="Issues" src="https://img.shields.io/github/issues/xinnan-tech/xiaozhi-esp32-server?color=0088ff" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/pulls">
<img alt="GitHub pull requests" src="https://img.shields.io/github/issues-pr/xinnan-tech/xiaozhi-esp32-server?color=0088ff" />
</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>
@@ -246,8 +241,9 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 声纹识别 | 支持多用户声纹注册、管理和识别,与ASR并行处理,实时识别说话人身份并传递给LLM进行个性化回应 |
| 智能对话 | 支持多种LLM(大语言模型),实现智能对话 |
| 视觉感知 | 支持多种VLLM(视觉大模型),实现多模态交互 |
| 意图识别 | 支持LLM意图识别、Function Call函数调用,提供插件化意图处理机制 |
| 意图识别 | 支持外挂的大模型意图识别、大模型自主函数调用,提供插件化意图处理机制 |
| 记忆系统 | 支持本地短期记忆、mem0ai接口记忆,具备记忆总结功能 |
| 知识库 | 支持RAGFlow知识库,让大模型判断需要调度知识库后再回答 |
| 工具调用 | 支持客户端IOT协议、客户MCP协议、服务端MCP协议、MCP接入点协议、自定义工具函数 |
| 指令下发 | 依托MQTT协议,支持从智控台将MCP指令下发到ESP32设备 |
| 管理后台 | 提供Web管理界面,支持用户管理、系统配置和设备管理;界面支持中文简体、中文繁体、英文显示 |
@@ -273,7 +269,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 使用方式 | 支持平台 | 免费平台 |
|:---:|:---:|:---:|
| openai 接口调用 | 阿里百炼、火山引擎豆包、深度求索、智谱ChatGLM、Gemini | 智谱ChatGLM、Gemini |
| openai 接口调用 | 阿里百炼、火山引擎、DeepSeek、智谱、Gemini、科大讯飞 | 智谱、Gemini |
| ollama 接口调用 | Ollama | - |
| dify 接口调用 | Dify | - |
| fastgpt 接口调用 | Fastgpt | - |
@@ -299,7 +295,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 使用方式 | 支持平台 | 免费平台 |
|:---:|:---:|:---:|
| 接口调用 | EdgeTTS、火山引擎豆包TTS、腾讯云、阿里云TTS、阿里云流式TTS、CosyVoiceSiliconflow、TTS302AI、CozeCnTTS、GizwitsTTS、ACGNTTS、OpenAITTS、灵犀流式TTS、MinimaxTTS、火山双流式TTS | 灵犀流式TTS、EdgeTTS、CosyVoiceSiliconflow(部分) |
| 接口调用 | 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 |
---
@@ -317,7 +313,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
| 使用方式 | 支持平台 | 免费平台 |
|:---:|:---:|:---:|
| 本地使用 | FunASR、SherpaASR | FunASR、SherpaASR |
| 接口调用 | DoubaoASR、Doubao流式ASR、FunASRServer、TencentASR、AliyunASR、Aliyun流式ASR、百度ASR、OpenAI ASR | FunASRServer |
| 接口调用 | FunASRServer、火山引擎、科大讯飞、腾讯云、阿里云、百度云、OpenAI ASR | FunASRServer |
---
@@ -349,6 +345,14 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
---
### Rag 检索增强生成
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|:------:|:-------------:|:----:|:-------:|:---------------------:|
| Rag | ragflow | 接口调用 | 根据切片、分词消耗的token收费 | 借助RagFlow的检索增强生成功能,提供更准确的对话回复 |
---
## 鸣谢 🙏
| Logo | 项目/公司 | 说明 |
+374
View File
@@ -0,0 +1,374 @@
[![Banners](docs/images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server)
<h1 align="center">Xiaozhi Backend-Service xiaozhi-esp32-server</h1>
<p align="center">
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
</p>
<p align="center">
<a href="./docs/FAQ.md">Häufige Fragen</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">Probleme melden</a>
· <a href="./README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3">Deployment-Dokumentation</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">Release-Hinweise</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-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">
Geleitet vom Team von Professor Siyuan Liu (South China University of Technology)
</br>
刘思源教授团队主导研发(华南理工大学)
</br>
<img src="./docs/images/hnlg.jpg" alt="South China University of Technology" width="50%">
</p>
---
## Zielgruppe 👥
Dieses Projekt erfordert ESP32-Hardware-Geräte zum Betrieb. Wenn Sie ESP32-bezogene Hardware erworben haben, erfolgreich eine Verbindung zu Brother Xias bereitgestelltem Backend-Service hergestellt haben und Ihren eigenen `xiaozhi-esp32`-Backend-Service unabhängig aufbauen möchten, dann ist dieses Projekt perfekt für Sie.
Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
<table>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture>
<img alt="响应速度感受" src="docs/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>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture>
<img alt="复杂医疗场景" src="docs/images/demo1.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>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture>
<img alt="声纹识别" src="docs/images/demo14.png" />
</picture>
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture>
<img alt="控制家电开关" src="docs/images/demo5.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture>
<img alt="MCP接入点" src="docs/images/demo13.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture>
<img alt="多指令任务" src="docs/images/demo11.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture>
<img alt="播放音乐" src="docs/images/demo7.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Z8XuYZEAS" target="_blank">
<picture>
<img alt="天气插件" src="docs/images/demo8.png" />
</picture>
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture>
<img alt="实时打断" src="docs/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>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture>
<img alt="自定义音色" src="docs/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>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV17LXWYvENb" target="_blank">
<picture>
<img alt="播报新闻" src="docs/images/demo0.png" />
</picture>
</a>
</td>
</tr>
</table>
---
## Warnungen ⚠️
1. Dieses Projekt ist Open-Source-Software. Diese Software hat keine kommerzielle Partnerschaft mit Drittanbieter-API-Dienstleistern (einschließlich, aber nicht beschränkt auf Spracherkennung, große Modelle, Sprachsynthese und andere Plattformen), mit denen sie sich verbindet, und bietet keine Garantie für deren Servicequalität oder finanzielle Sicherheit. Es wird empfohlen, dass Benutzer Dienstleister mit entsprechenden Geschäftslizenzen bevorzugen und deren Servicevereinbarungen und Datenschutzrichtlinien sorgfältig lesen. Diese Software hostet keine Kontoschlüssel, nimmt nicht an Geldströmen teil und trägt nicht das Risiko von Verlusten bei Guthaben-Aufladungen.
2. Die Funktionalität dieses Projekts ist nicht vollständig und hat keine Netzwerksicherheitsbewertung bestanden. Bitte verwenden Sie es nicht in Produktionsumgebungen. Wenn Sie dieses Projekt zu Lernzwecken in einer öffentlichen Netzwerkumgebung bereitstellen, stellen Sie bitte sicher, dass notwendige Schutzmaßnahmen vorhanden sind.
---
## Deployment-Dokumentation
![Banners](docs/images/banner2.png)
Dieses Projekt bietet zwei Bereitstellungsmethoden. Bitte wählen Sie basierend auf Ihren spezifischen Anforderungen:
#### 🚀 Auswahl der Bereitstellungsmethode
| Bereitstellungsmethode | Funktionen | Anwendungsszenarien | Deployment-Dokumente | Konfigurationsanforderungen | Video-Tutorials |
|---------|------|---------|---------|---------|---------|
| **Vereinfachte Installation** | Intelligenter Dialog, IOT, MCP, visuelle Wahrnehmung | Umgebungen mit geringer Konfiguration, Daten in Konfigurationsdateien gespeichert, keine Datenbank erforderlich | [①Docker-Version](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Quellcode-Deployment](./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)| 2 Kerne 4GB bei Verwendung von `FunASR`, 2 Kerne 2GB bei allen APIs | - |
| **Vollständige Modulinstallation** | Intelligenter Dialog, IOT, MCP-Endpunkte, Stimmabdruckerkennung, visuelle Wahrnehmung, OTA, intelligente Steuerkonsole | Vollständige Funktionserfahrung, Daten in Datenbank gespeichert |[①Docker-Version](./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) / [②Quellcode-Deployment](./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) / [③Quellcode-Deployment Auto-Update-Tutorial](./docs/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) |
Häufige Fragen und entsprechende Tutorials finden Sie unter [diesem Link](./docs/FAQ.md)
> 💡 Hinweis: Unten ist eine Testplattform, die mit dem neuesten Code bereitgestellt wurde. Sie können bei Bedarf brennen und testen. Gleichzeitige Benutzer: 6, Daten werden täglich gelöscht.
```
Adresse der intelligenten Steuerkonsole: https://2662r3426b.vicp.fun
Adresse der intelligenten Steuerkonsole (H5): https://2662r3426b.vicp.fun/h5/index.html
Service-Testtool: https://2662r3426b.vicp.fun/test/
OTA-Schnittstellenadresse: https://2662r3426b.vicp.fun/xiaozhi/ota/
Websocket-Schnittstellenadresse: wss://2662r3426b.vicp.fun/xiaozhi/v1/
```
#### 🚩 Konfigurationsbeschreibung und Empfehlungen
> [!Note]
> Dieses Projekt bietet zwei Konfigurationsschemata:
>
> 1. `Einstiegslevel Kostenlose Einstellungen`: Geeignet für den persönlichen und privaten Gebrauch, alle Komponenten verwenden kostenlose Lösungen, keine zusätzliche Zahlung erforderlich.
>
> 2. `Streaming-Konfiguration`: Geeignet für Demonstrationen, Schulungen, Szenarien mit mehr als 2 gleichzeitigen Benutzern usw. Verwendet Streaming-Verarbeitungstechnologie für schnellere Reaktionsgeschwindigkeit und bessere Erfahrung.
>
> Ab Version `0.5.2` unterstützt das Projekt Streaming-Konfiguration. Im Vergleich zu früheren Versionen ist die Reaktionsgeschwindigkeit um ca. `2,5 Sekunden` verbessert, was die Benutzererfahrung erheblich verbessert.
| Modulname | Einstiegslevel Kostenlose Einstellungen | Streaming-Konfiguration |
|:---:|:---:|:---:|
| ASR (Spracherkennung) | FunASR (Lokal) | 👍FunASR (Lokaler GPU-Modus) |
| LLM (Großes Modell) | ChatGLMLLM (Zhipu glm-4-flash) | 👍AliLLM (qwen3-235b-a22b-instruct-2507) oder 👍DoubaoLLM (doubao-1-5-pro-32k-250115) |
| VLLM (Vision Large Model) | ChatGLMVLLM (Zhipu glm-4v-flash) | 👍QwenVLVLLM (Qwen qwen2.5-vl-3b-instructh) |
| TTS (Sprachsynthese) | ✅LinkeraiTTS (Lingxi-Streaming) | 👍HuoshanDoubleStreamTTS (Volcano Dual-Stream-Sprachsynthese) oder 👍AliyunStreamTTS (Alibaba Cloud Streaming-Sprachsynthese) |
| Intent (Absichtserkennung) | function_call (Funktionsaufruf) | function_call (Funktionsaufruf) |
| Memory (Gedächtnisfunktion) | mem_local_short (Lokales Kurzzeitgedächtnis) | mem_local_short (Lokales Kurzzeitgedächtnis) |
Wenn Sie sich um die Latenz jeder Komponente kümmern, lesen Sie bitte den [Xiaozhi-Komponenten-Leistungstestbericht](https://github.com/xinnan-tech/xiaozhi-performance-research). Sie können gemäß den Testmethoden im Bericht in Ihrer Umgebung tatsächlich testen.
#### 🔧 Testwerkzeuge
Dieses Projekt bietet die folgenden Testwerkzeuge, um Ihnen bei der Überprüfung des Systems und der Auswahl geeigneter Modelle zu helfen:
| Werkzeugname | Standort | Verwendungsmethode | Funktionsbeschreibung |
|:---:|:---|:---:|:---:|
| Audio-Interaktionstesttool | main》xiaozhi-server》test》test_page.html | Direkt mit Google Chrome ö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 |
> 💡 Hinweis: Beim Testen der Modellgeschwindigkeit werden nur Modelle mit konfigurierten Schlüsseln getestet.
---
## Funktionsliste ✨
### Implementiert ✅
![请参考-全模块安装架构图](docs/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 |
| Sprachinteraktion | Unterstützt Streaming-ASR (Spracherkennung), Streaming-TTS (Sprachsynthese), VAD (Sprachaktivitätserkennung), unterstützt mehrsprachige Erkennung und Sprachverarbeitung |
| 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 |
| Gedächtnissystem | Unterstützt lokales Kurzzeitgedächtnis, mem0ai-Schnittstellengedä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 |
| 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 |
| 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 |
### In Entwicklung 🚧
Um über spezifische Entwicklungsplanfortschritte zu erfahren, [klicken Sie hier](https://github.com/users/xinnan-tech/projects/3). Häufige Fragen und entsprechende Tutorials finden Sie unter [diesem Link](./docs/FAQ.md)
Wenn Sie ein Softwareentwickler sind, finden Sie hier einen [Offenen Brief an Entwickler](docs/contributor_open_letter.md). Willkommen beim Beitritt!
---
## Produktökosystem 👬
Xiaozhi ist ein Ökosystem. Wenn Sie dieses Produkt verwenden, können Sie sich auch andere [hervorragende Projekte](https://github.com/78/xiaozhi-esp32?tab=readme-ov-file#%E7%9B%B8%E5%85%B3%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE) in diesem Ökosystem ansehen
---
## Liste der von diesem Projekt unterstützten Plattformen/Komponenten 📋
### LLM-Sprachmodelle
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:|
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Volcano Engine Doubao, DeepSeek, Zhipu ChatGLM, Gemini | Zhipu ChatGLM, Gemini |
| Ollama-Schnittstellenaufrufe | Ollama | - |
| Dify-Schnittstellenaufrufe | Dify | - |
| FastGPT-Schnittstellenaufrufe | FastGPT | - |
| Coze-Schnittstellenaufrufe | Coze | - |
| Xinference-Schnittstellenaufrufe | Xinference | - |
| HomeAssistant-Schnittstellenaufrufe | HomeAssistant | - |
Tatsächlich kann jedes LLM, das OpenAI-Schnittstellenaufrufe unterstützt, integriert und verwendet werden.
---
### VLLM-Vision-Modelle
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:|
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, integriert und verwendet werden.
---
### TTS-Sprachsynthese
| 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 |
---
### VAD-Sprachaktivitätserkennung
| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
|:---:|:---------:|:----:|:----:|:--:|
| VAD | SileroVAD | Lokale Verwendung | Kostenlos | |
---
### ASR-Spracherkennung
| 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 |
---
### Voiceprint-Stimmabdruckerkennung
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:|
| Lokale Verwendung | 3D-Speaker | 3D-Speaker |
---
### Memory-Gedächtnisspeicher
| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
|:------:|:---------------:|:----:|:---------:|:--:|
| Memory | mem0ai | Schnittstellenaufrufe | 1000 Mal/Monat Kontingent | |
| Memory | mem_local_short | Lokale Zusammenfassung | Kostenlos | |
| Memory | nomem | Kein Gedächtnismodus | Kostenlos | |
---
### Intent-Absichtserkennung
| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
|:------:|:-------------:|:----:|:-------:|:---------------------:|
| Intent | intent_llm | Schnittstellenaufrufe | Basierend auf LLM-Preisen | Erkennt Absicht durch große Modelle, starke Allgemeingültigkeit |
| Intent | function_call | Schnittstellenaufrufe | Basierend auf LLM-Preisen | Vervollständigt Absicht durch Funktionsaufruf großer Modelle, schnelle Geschwindigkeit, guter Effekt |
| Intent | nointent | Kein Absichtsmodus | Kostenlos | Führt keine Absichtserkennung durch, gibt direkt Dialogergebnis zurück |
---
### Rag Retrieval Augmented Generation
| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
|:------:|:-------------:|:----:|:-------:|:---------------------:|
| Rag | ragflow | Schnittstellenaufrufe | Gebühren basierend auf Token-Verbrauch für Segmentierung und Tokenisierung | Nutzt RAGFlow's Retrieval-Augmented-Generation-Funktion für präzisere Dialogantworten |
---
## Danksagungen 🙏
| Logo | Projekt/Unternehmen | Beschreibung |
|:---:|:---:|:---|
| <img src="./docs/images/logo_bailing.png" width="160"> | [Bailing Voice Dialogue Robot](https://github.com/wwbin2017/bailing) | Dieses Projekt wurde von [Bailing Voice Dialogue Robot](https://github.com/wwbin2017/bailing) inspiriert und auf dessen Basis implementiert |
| <img src="./docs/images/logo_tenclass.png" width="160"> | [Tenclass](https://www.tenclass.com/) | Dank an [Tenclass](https://www.tenclass.com/) für die Formulierung von Standardkommunikationsprotokollen, Multi-Geräte-Kompatibilitätslösungen und High-Concurrency-Szenario-Praxisdemonstrationen für das Xiaozhi-Ökosystem; für die Bereitstellung vollständiger technischer Dokumentationsunterstützung für dieses Projekt |
| <img src="./docs/images/logo_xuanfeng.png" width="160"> | [Xuanfeng Technology](https://github.com/Eric0308) | Dank an [Xuanfeng Technology](https://github.com/Eric0308) für den Beitrag des Funktionsaufruf-Frameworks, des MCP-Kommunikationsprotokolls und der plugin-basierten Aufrufmechanismus-Implementierungscode. Durch standardisiertes Befehlsplanungssystem und dynamische Erweiterungsfähigkeiten wird die Interaktionseffizienz und funktionale Erweiterbarkeit von Frontend-Geräten (IoT) erheblich verbessert |
| <img src="./docs/images/logo_junsen.png" width="160"> | [huangjunsen](https://github.com/huangjunsen0406) | Dank an [huangjunsen](https://github.com/huangjunsen0406) für den Beitrag des `Smart Control Console Mobile`-Moduls, das eine effiziente Steuerung und Echtzeit-Interaktion über mobile Geräte ermöglicht und die Betriebsbequemlichkeit und Verwaltungseffizienz des Systems in mobilen Szenarien erheblich verbessert |
| <img src="./docs/images/logo_huiyuan.png" width="160"> | [Huiyuan Design](http://ui.kwd988.net/) | Dank an [Huiyuan Design](http://ui.kwd988.net/) für die Bereitstellung professioneller visueller Lösungen für dieses Projekt, unter Verwendung ihrer Design-Praxiserfahrung im Dienst von über tausend Unternehmen, um die Produktbenutzererfahrung dieses Projekts zu stärken |
| <img src="./docs/images/logo_qinren.png" width="160"> | [Xi'an Qinren Information Technology](https://www.029app.com/) | Dank an [Xi'an Qinren Information Technology](https://www.029app.com/) für die Vertiefung des visuellen Systems dieses Projekts und die Sicherstellung der Konsistenz und Erweiterbarkeit des Gesamtdesignstils in Multi-Szenario-Anwendungen |
| <img src="./docs/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">
<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" />
</picture>
</a>
+19 -15
View File
@@ -6,29 +6,24 @@
This project is based on human-machine symbiotic intelligence theory and technology to develop intelligent terminal hardware and software systems<br/>providing backend services for the open-source intelligent hardware project
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
Implemented using Python, Java, and Vue according to the <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">Xiaozhi Communication Protocol</a><br/>
Supports MCP endpoints and voiceprint recognition
Support for MQTT+UDP protocol, Websocket protocol, MCP access point, voiceprint recognition, and knowledge base
</p>
<p align="center">
<a href="./README.md">中文</a>
· <a href="./docs/FAQ.md">FAQ</a>
<a href="./docs/FAQ.md">FAQ</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">Report Issues</a>
· <a href="./README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3">Deployment Docs</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">Release Notes</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-DBEDFA"></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="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/graphs/contributors">
<img alt="GitHub Contributors" src="https://img.shields.io/github/contributors/xinnan-tech/xiaozhi-esp32-server?logo=github" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">
<img alt="Issues" src="https://img.shields.io/github/issues/xinnan-tech/xiaozhi-esp32-server?color=0088ff" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/pulls">
<img alt="GitHub pull requests" src="https://img.shields.io/github/issues-pr/xinnan-tech/xiaozhi-esp32-server?color=0088ff" />
</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>
@@ -244,6 +239,7 @@ This project provides the following testing tools to help you verify the system
| 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 |
| Memory System | Supports local short-term memory, mem0ai interface 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 |
| Command Delivery | Supports MCP command delivery to ESP32 devices via MQTT protocol from Smart Console |
| Tool Calling | Supports client IOT protocol, client MCP protocol, server MCP protocol, MCP endpoint protocol, custom tool functions |
| Management Backend | Provides Web management interface, supports user management, system configuration and device management; Supports Simplified Chinese, Traditional Chinese and English display |
@@ -275,7 +271,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 Doubao, DeepSeek, Zhipu ChatGLM, Gemini | Zhipu ChatGLM, Gemini |
| OpenAI interface calls | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK | Zhipu, Gemini |
| Ollama interface calls | Ollama | - |
| Dify interface calls | Dify | - |
| FastGPT interface calls | FastGPT | - |
@@ -299,7 +295,7 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
| Usage Method | Supported Platforms | Free Platforms |
|:---:|:---:|:---:|
| Interface calls | EdgeTTS, Volcano Engine Doubao TTS, Tencent Cloud, Alibaba Cloud TTS, AliYun Stream TTS, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow(partial) |
| 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, MinimaxTTS | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, MinimaxTTS |
---
@@ -317,7 +313,7 @@ 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 | DoubaoASR, FunASRServer, TencentASR, AliyunASR | FunASRServer |
| Interface calls | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
---
@@ -347,6 +343,14 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
---
### Rag Retrieval-Augmented Generation
| Type | Platform Name | Usage Method | Pricing Model | Notes |
|:------:|:-------------:|:----:|:-------:|:---------------------:|
| Rag | ragflow | Interface calls | Charged based on tokens consumed for slicing and word segmentation | Utilizes RagFlow's retrieval-augmented generation feature to provide more accurate dialog responses |
---
## Acknowledgments 🙏
| Logo | Project/Company | Description |
+375
View File
@@ -0,0 +1,375 @@
[![Banners](docs/images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server)
<h1 align="center">Dịch vụ Backend Xiaozhi xiaozhi-esp32-server</h1>
<p align="center">
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
</p>
<p align="center">
<a href="./docs/FAQ.md">Câu hỏi thường gặp</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">Báo cáo vấn đề</a>
· <a href="./README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3">Tài liệu triển khai</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">Nhật ký cập nhật</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-DBEDFA"></a>
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-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>
<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">
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="./docs/images/hnlg.jpg" alt="华南理工大学" width="50%">
</p>
---
## Người dùng phù hợp 👥
Dự án này cần được sử dụng cùng với thiết bị phần cứng ESP32. Nếu bạn đã mua phần cứng liên quan đến ESP32, đã thành công kết nối với dịch vụ backend do anh Xia triển khai, và muốn xây dựng dịch vụ backend `xiaozhi-esp32` riêng của mình, thì dự án này rất phù hợp với bạn.
Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
<table>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture>
<img alt="响应速度感受" src="docs/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>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture>
<img alt="复杂医疗场景" src="docs/images/demo1.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>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture>
<img alt="声纹识别" src="docs/images/demo14.png" />
</picture>
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture>
<img alt="控制家电开关" src="docs/images/demo5.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture>
<img alt="MCP接入点" src="docs/images/demo13.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture>
<img alt="多指令任务" src="docs/images/demo11.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture>
<img alt="播放音乐" src="docs/images/demo7.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Z8XuYZEAS" target="_blank">
<picture>
<img alt="天气插件" src="docs/images/demo8.png" />
</picture>
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture>
<img alt="实时打断" src="docs/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>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture>
<img alt="自定义音色" src="docs/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>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV17LXWYvENb" target="_blank">
<picture>
<img alt="播报新闻" src="docs/images/demo0.png" />
</picture>
</a>
</td>
</tr>
</table>
---
## Cảnh báo ⚠️
1. Dự án này là phần mềm mã nguồn mở, phần mềm này không có quan hệ hợp tác thương mại với bất kỳ nhà cung cấp dịch vụ API bên thứ ba nào (bao gồm nhưng không giới hạn ở các nền tảng nhận dạng giọng nói, mô hình lớn, tổng hợp giọng nói, v.v.), và không đảm bảo chất lượng dịch vụ cũng như an toàn tài chính của họ.
Khuyến nghị người dùng ưu tiên lựa chọn nhà cung cấp dịch vụ có giấy phép kinh doanh liên quan và đọc kỹ thỏa thuận dịch vụ và chính sách bảo mật của họ. Phần mềm này không lưu trữ bất kỳ khóa tài khoản nào, không tham gia vào luồng tiền và không chịu rủi ro mất tiền nạp.
2. Chức năng của dự án này chưa hoàn thiện và chưa qua đánh giá bảo mật mạng, vui lòng không sử dụng trong môi trường sản xuất. Nếu bạn triển khai dự án này trong môi trường mạng công cộng để học tập, vui lòng thực hiện các biện pháp bảo vệ cần thiết.
---
## Tài liệu triển khai
![Banners](docs/images/banner2.png)
Dự án này cung cấp hai phương pháp triển khai, vui lòng chọn theo nhu cầu cụ thể của bạn:
#### 🚀 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, IOT, MCP, cảm nhận thị giác | 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](./docs/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](./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)| 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, IOT, điểm truy cập MCP, nhận dạng giọng nói, cảm nhận thị giác, OTA, 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](./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) / [②Triển khai mã nguồn](./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) / [③Hướng dẫn tự động cập nhật triển khai mã nguồn](./docs/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â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](./docs/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,
```
Địa chỉ bảng điều khiển thông minh: https://2662r3426b.vicp.fun
Bảng điều khiển thông minh (phiên bản h5): https://2662r3426b.vicp.fun/h5/index.html
Công cụ kiểm tra dịch vụ: https://2662r3426b.vicp.fun/test/
Địa chỉ giao diện OTA: https://2662r3426b.vicp.fun/xiaozhi/ota/
Địa chỉ giao diện Websocket: wss://2662r3426b.vicp.fun/xiaozhi/v1/
```
#### 🚩 Mô tả và khuyến nghị cấu hình
> [!Note]
> Dự án này cung cấp hai phương án cấu hình:
>
> 1. Cấu hình `Miễn phí hoàn toàn cho người mới`: Phù hợp với sử dụng gia đình cá nhân, tất cả các thành phần đều sử dụng phương án miễn phí, không cần thanh toán thêm.
>
> 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ên module | Cài đặt miễn phí cho người mới | Cấu hình streaming |
|:---:|:---:|:---:|
| ASR(Nhận dạng giọng nói) | FunASR(Local) | 👍FunASR(Chế độ GPU cục bộ) |
| LLM(Mô hình lớn) | ChatGLMLLM(Zhipu glm-4-flash) | 👍AliLLM(qwen3-235b-a22b-instruct-2507) hoặc 👍DoubaoLLM(doubao-1-5-pro-32k-250115) |
| VLLM(Mô hình lớn thị giác) | ChatGLMVLLM(Zhipu glm-4v-flash) | 👍QwenVLVLLM(Qwen qwen2.5-vl-3b-instructh) |
| TTS(Tổng hợp giọng nói) | ✅LinkeraiTTS(Lingxi streaming) | 👍HuoshanDoubleStreamTTS(Tổng hợp giọng nói streaming kép Volcano) hoặc 👍AliyunStreamTTS(Tổng hợp giọng nói streaming Alibaba Cloud) |
| Intent(Nhận dạng ý định) | function_call(Gọi hàm) | function_call(Gọi hàm) |
| Memory(Chức năng bộ nhớ) | mem_local_short(Bộ nhớ ngắn hạn cục bộ) | mem_local_short(Bộ nhớ ngắn hạn cục bộ) |
Nếu bạn quan tâm đến thời gian của từng thành phần, vui lòng xem [Báo cáo kiểm tra hiệu suất các thành phần Xiaozhi](https://github.com/xinnan-tech/xiaozhi-performance-research), có thể kiểm tra thực tế trong môi trường của bạn theo phương pháp kiểm tra trong báo cáo.
#### 🔧 Công cụ kiểm tra
Dự án này cung cấp các công cụ kiểm tra sau để giúp bạn xác minh hệ thống và chọn mô hình phù hợp:
| 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》xiaozhi-server》test》test_page.html | Mở trực tiếp bằng trình duyệt Google Chrome | 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) |
> 💡 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 ✅
![请参考-全模块安装架构图](docs/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 |
| Tương tác giọng nói | Hỗ trợ ASR streaming(Nhận dạng giọng nói), TTS streaming(Tổng hợp giọng nói), VAD(Phát hiện hoạt động giọng nói), hỗ trợ nhận dạng đa ngôn ngữ và xử lý giọng nói |
| Nhận dạng vân giọng | Hỗ trợ đăng ký, quản lý và nhận dạng vân giọng đa người dùng, xử lý song song với ASR, nhận dạng danh tính người nói theo thời gian thực và truyền cho LLM để phản hồi cá nhân hóa |
| Đối thoại thông minh | Hỗ trợ nhiều LLM(Mô hình ngôn ngữ lớn), thực hiện đối thoại thông minh |
| Cảm nhận thị giác | Hỗ trợ nhiều VLLM(Mô hình lớn thị giác), thực hiện tương tác đa phương thức |
| Nhận dạng ý định | Hỗ trợ nhận dạng ý định mô hình lớn gắn ngoài, gọi hàm tự chủ mô hình lớn, cung cấp cơ chế xử lý ý định dạng plugin |
| Hệ thống bộ nhớ | Hỗ trợ bộ nhớ ngắn hạn cục bộ, bộ nhớ giao diện mem0ai, có chức năng tóm tắt bộ nhớ |
| 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 |
| 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 |
### Đang phát triển 🚧
Muốn hiểu tiến độ kế hoạch phát triển cụ thể, [vui lòng nhấp vào đây](https://github.com/users/xinnan-tech/projects/3). 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](./docs/FAQ.md)
Nếu bạn là một nhà phát triển phần mềm, đây có một [Lá thư mở gửi các nhà phát triển](docs/contributor_open_letter.md), chào mừng tham gia!
---
## Hệ sinh thái sản phẩm 👬
Xiaozhi là một hệ sinh thái, khi bạn sử dụng sản phẩm này, bạn cũng có thể xem các [dự án xuất sắc](https://github.com/78/xiaozhi-esp32?tab=readme-ov-file#%E7%9B%B8%E5%85%B3%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE) khác trong hệ sinh thái này
---
## Danh sách nền tảng/thành phần được dự án này hỗ trợ 📋
### LLM Mô hình ngôn ngữ
| 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 ollama | Ollama | - |
| Gọi giao diện dify | Dify | - |
| Gọi giao diện fastgpt | Fastgpt | - |
| Gọi giao diện coze | Coze | - |
| 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.
---
### VLLM Mô hình thị giác
| 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 |
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.
---
### TTS Tổng hợp giọng nói
| 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 |
---
### VAD Phát hiện hoạt động giọng nói
| Loại | Tên nền tảng | Phương pháp sử dụng | Mô hình thu phí | Ghi chú |
|:---:|:---------:|:----:|:----:|:--:|
| VAD | SileroVAD | Sử dụng cục bộ | Miễn phí | |
---
### ASR Nhận dạng giọng nói
| 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 |
---
### Voiceprint Nhận dạng vân giọng
| 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 |
---
### Memory Lưu trữ bộ nhớ
| Loại | Tên nền tảng | Phương pháp sử dụng | Mô hình thu phí | Ghi chú |
|:------:|:---------------:|:----:|:---------:|:--:|
| Memory | mem0ai | Gọi giao diện | Hạn mức 1000 lần/tháng | |
| 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í | |
---
### Intent Nhận dạng ý định
| Loại | Tên nền tảng | Phương pháp sử dụng | Mô hình thu phí | Ghi chú |
|:------:|:-------------:|:----:|:-------:|:---------------------:|
| Intent | intent_llm | Gọi giao diện | Thu phí theo LLM | Nhận dạng ý định qua mô hình lớn, tính tổng quát mạnh |
| Intent | function_call | Gọi giao diện | Thu phí theo LLM | Hoàn thành ý định qua gọi hàm mô hình lớn, tốc độ nhanh, hiệu quả tốt |
| Intent | nointent | Chế độ không có ý định | Miễn phí | Không thực hiện nhận dạng ý định, trả về trực tiếp kết quả đối thoại |
---
### Rag Tăng cường truy xuất thông tin
| Loại | Tên nền tảng | Phương pháp sử dụng | Mô hình thu phí | Ghi chú |
|:------:|:-------------:|:----:|:-------:|:---------------------:|
| Rag | ragflow | Gọi giao diện | Thu phí theo token tiêu tốn của phân đoạn, phân từ | Sử dụng chức năng tăng cường truy xuất của RagFlow, cung cấp phản hồi đối thoại chính xác hơn |
---
## Lời cảm ơn 🙏
| Logo | Dự án/Công ty | Mô tả |
|:---:|:---:|:---|
| <img src="./docs/images/logo_bailing.png" width="160"> | [Robot đối thoại giọng nói Bailing](https://github.com/wwbin2017/bailing) | Dự án này được lấy cảm hứng từ [Robot đối thoại giọng nói Bailing](https://github.com/wwbin2017/bailing) và được triển khai trên cơ sở đó |
| <img src="./docs/images/logo_tenclass.png" width="160"> | [Shifang Ronghai](https://www.tenclass.com/) | Cảm ơn [Shifang Ronghai](https://www.tenclass.com/) đã xây dựng giao thức truyền thông tiêu chuẩn, phương án tương thích đa thiết bị và mô phạm thực hành tình huống đồng thời cao cho hệ sinh thái Xiaozhi; cung cấp tài liệu hỗ trợ kỹ thuật toàn diện cho dự án này |
| <img src="./docs/images/logo_xuanfeng.png" width="160"> | [Xuanfeng Technology](https://github.com/Eric0308) | Cảm ơn [Xuanfeng Technology](https://github.com/Eric0308) đã đóng góp khung gọi hàm, giao thức truyền thông MCP và mã triển khai cơ chế gọi dạng plugin, thông qua hệ thống điều phối lệnh tiêu chuẩn hóa và khả năng mở rộng động, đã cải thiện đáng kể hiệu suất tương tác và khả năng mở rộng chức năng của thiết bị front-end(IoT) |
| <img src="./docs/images/logo_junsen.png" width="160"> | [huangjunsen](https://github.com/huangjunsen0406) | Cảm ơn [huangjunsen](https://github.com/huangjunsen0406) đã đóng góp module `Bảng điều khiển thông minh di động`, thực hiện điều khiển hiệu quả và tương tác thời gian thực trên thiết bị di động đa nền tảng, cải thiện đáng kể sự tiện lợi vận hành và hiệu quả quản lý của hệ thống trong tình huống di động |
| <img src="./docs/images/logo_huiyuan.png" width="160"> | [Huiyuan Design](http://ui.kwd988.net/) | Cảm ơn [Huiyuan Design](http://ui.kwd988.net/) đã cung cấp giải pháp thị giác chuyên nghiệp cho dự án này, sử dụng kinh nghiệm thực tế thiết kế phục vụ hơn nghìn doanh nghiệp, trao quyền cho trải nghiệm người dùng sản phẩm của dự án này |
| <img src="./docs/images/logo_qinren.png" width="160"> | [Xi'an Qinren Information Technology](https://www.029app.com/) | Cảm ơn [Xi'an Qinren Information Technology](https://www.029app.com/) đã làm sâu sắc hệ thống thị giác của dự án này, đảm bảo tính nhất quán và khả năng mở rộng của phong cách thiết kế tổng thể trong ứng dụng đa tình huống |
| <img src="./docs/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">
<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" />
</picture>
</a>
+1
View File
@@ -79,6 +79,7 @@ VAD:
6、[MCP方法如何获取设备信息](./mcp-get-device-info.md)<br/>
7、[如何开启声纹识别](./voiceprint-integration.md)<br/>
8、[新闻插件源配置指南](./newsnow_plugin_config.md)<br/>
9、[知识库ragflow集成指南](./ragflow-integration.md)<br/>
### 11、语音克隆、本地语音部署相关教程
1、[如何在智控台克隆音色](./huoshan-streamTTS-voice-cloning.md)<br/>
+1 -1
View File
@@ -97,7 +97,7 @@ http://homeassistant.local:8123
使用管理员账号,登录`智控台`。在`智能体管理`,找到你的智能体,再点击`配置角色`。
将意图识别设置成`函数调用`或`LLM意图识别`。这时你会看到右侧有一个`编辑功能`。点击`编辑功能`按钮,会弹出`功能管理`的框。
将意图识别设置成`外挂的大模型意图识别`或`大模型自主函数调用`。这时你会看到右侧有一个`编辑功能`。点击`编辑功能`按钮,会弹出`功能管理`的框。
在`功能管理`的框里,你需要勾选`HomeAssistant设备状态查询`和`HomeAssistant设备状态修改`。
+259
View File
@@ -0,0 +1,259 @@
# ragflow 集成指南
本教程主要是是两部分
- 一、如何部署ragflow
- 二、如何在智控台配置ragflow接口
如果您对ragflow很熟悉,且已经部署了ragflow,可直接跳过第一部分,直接进入第二部分。但是如果你希望有人指导你部署ragflow,让它能够和`xiaozhi-esp32-server`共同使用`mysql``redis`基础服务,以减少资源成本,你需要从第一部分开始。
# 第一部分 如何部署ragflow
## 第一步, 确认mysql、redis是否可用
ragflow需要依赖`mysql`数据库。如果你之前已经部署`智控台`,说明你已经安装了`mysql`。你可以共用它。
你可以你试一下在宿主机使用`telnet`命令,看看能不能正常访问`mysql``3306`端口。
``` shell
telnet 127.0.0.1 3306
telnet 127.0.0.1 6379
```
如果能访问到`3306`端口和`6379`端口,请忽略以下的内容,直接进入第二步。
如果不能访问,你需要回忆一下,你的`mysql`是怎么安装的。
如果你的mysql是通过自己使用安装包安装的,说明你的`mysql`做了网络隔离。你可能先解决访问`mysql`的`3306`端口这个问题。
如果你`mysql`是通过本项目的`docker-compose_all.yml`安装的。你需要找一下你当时创建数据库的`docker-compose_all.yml`文件,修改以下的内容
修改前
``` yaml
xiaozhi-esp32-server-db:
...
networks:
- default
expose:
- "3306:3306"
xiaozhi-esp32-server-redis:
...
expose:
- 6379
```
修改后
``` yaml
xiaozhi-esp32-server-db:
...
networks:
- default
ports:
- "3306:3306"
xiaozhi-esp32-server-redis:
...
ports:
- "6379:6379"
```
注意是将`xiaozhi-esp32-server-db`和`xiaozhi-esp32-server-redis`下面的`expose`改成`ports`。改完后,需要重新启动。以下是重启mysql的命令:
``` shell
# 进入你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
```
启动完后,在宿主机再使用`telnet`命令,看看能不能正常访问`mysql`的`3306`端口。
``` shell
telnet 127.0.0.1 3306
telnet 127.0.0.1 6379
```
正常来说这样就可以访问的了。
## 第二步, 创建数据库和表
如果你的宿主机,能正常访问mysql数据库,那就在mysql上创建一个名字为`rag_flow`的数据库和`rag_flow`用户,密码为`infini_rag_flow`。
``` sql
-- 创建数据库
CREATE DATABASE IF NOT EXISTS rag_flow CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- 创建用户并授权
CREATE USER IF NOT EXISTS 'rag_flow'@'%' IDENTIFIED BY 'infini_rag_flow';
GRANT ALL PRIVILEGES ON rag_flow.* TO 'rag_flow'@'%';
-- 刷新权限
FLUSH PRIVILEGES;
```
## 第三步, 下载ragflow项目
你需要在你电脑找一个文件夹,用来存放ragflow项目。例如我在`/home/system/xiaozhi`文件夹。
你可以使用`git`命令,将ragflow项目下载到这个文件夹,本教程使用的是`v0.22.0`版本进行安装部署。
```
git clone https://ghfast.top/https://github.com/infiniflow/ragflow.git
cd ragflow
git checkout v0.22.0
```
下载完后,进入`docker`文件夹。
``` shell
cd docker
```
修改`ragflow/docker`文件夹下的`docker-compose.yml`文件,将`ragflow-cpu`和`ragflow-gpu`服务的`depends_on`配置去掉,用于解除`ragflow-cpu`服务对`mysql`的依赖。
这是修改前:
``` yaml
ragflow-cpu:
depends_on:
mysql:
condition: service_healthy
profiles:
- cpu
...
ragflow-gpu:
depends_on:
mysql:
condition: service_healthy
profiles:
- gpu
```
这是修改后:
``` yaml
ragflow-cpu:
profiles:
- cpu
...
ragflow-gpu:
profiles:
- gpu
```
接着,修改`ragflow/docker`文件夹下的`docker-compose-base.yml`文件,去掉`mysql`和`redis`的配置。
例如,删除前:
``` yaml
services:
minio:
image: quay.io/minio/minio:RELEASE.2025-06-13T11-33-47Z
...
mysql:
image: mysql:8.0
...
redis:
image: redis:6.2-alpine
...
```
删除后
``` yaml
services:
minio:
image: quay.io/minio/minio:RELEASE.2025-06-13T11-33-47Z
...
```
## 第四步,修改环境变量配置
编辑`ragflow/docker`文件夹下的`.env`文件,找到以下配置,逐个搜索,逐个修改!逐个搜索,逐个修改!
``` env
# 端口设置
SVR_WEB_HTTP_PORT=8008 # HTTP端口
SVR_WEB_HTTPS_PORT=8009 # HTTPS端口
# MySQL配置 - 修改为您本地MySQL的信息
MYSQL_HOST=host.docker.internal # 使用host.docker.internal让容器访问主机服务
MYSQL_PORT=3306 # 本地MySQL端口
MYSQL_USER=rag_flow # 上面创建的用户名,如果没有这项就增加这一项
MYSQL_PASSWORD=infini_rag_flow # 上面设置的密码
MYSQL_DBNAME=rag_flow # 数据库名称
# Redis配置 - 修改为您本地Redis的信息
REDIS_HOST=host.docker.internal # 使用host.docker.internal让容器访问主机服务
REDIS_PORT=6379 # 本地Redis端口
REDIS_PASSWORD= # 如果你的Redis没有设置密码,就按这样子填写,否则填写密码
```
注意,如果你的Redis没有设置密码,还要修改`ragflow/docker`文件夹下`service_conf.yaml.template`,将`infini_rag_flow`替换成空字符串。
修改前
``` shell
redis:
db: 1
password: '${REDIS_PASSWORD:-infini_rag_flow}'
host: '${REDIS_HOST:-redis}:6379'
```
修改后
``` shell
redis:
db: 1
password: '${REDIS_PASSWORD:-}'
host: '${REDIS_HOST:-redis}:6379'
```
## 第五步,启动ragflow服务
执行命令:
``` shell
docker-compose -f docker-compose.yml up -d
```
执行成功后,你可以使用`docker logs -n 20 -f docker-ragflow-cpu-1`命令,查看`docker-ragflow-cpu-1`服务的日志。
如果日志中没有报错,说明ragflow服务启动成功。
# 第五步,注册账号
你可以在浏览器中访问`http://127.0.0.1:8008`,点击`Sign Up`,注册一个账号。
注册成功后,你可以点击`Sign In`,登录到ragflow服务。如果你想关闭ragflow服务的注册服务,不想让其他人注册账号,你可以在`ragflow/docker`文件夹下的`.env`文件中,将`REGISTER_ENABLED`配置项设置为`0`。
``` dotenv
REGISTER_ENABLED=0
```
修改后,重启启动ragflow服务。
``` shell
docker-compose -f docker-compose.yml down
docker-compose -f docker-compose.yml up -d
```
# 第六步,配置ragflow服务的模型
你可以在浏览器中访问`http://127.0.0.1:8008`,点击`Sign In`,登录到ragflow服务。点击页面右上角的`头像`,进入设置页面。
首先,在左侧导航栏中,点击`模型供应商`,进入到模型配置页面。在右侧的`可选模型`搜索框下,选择`LLM`,在列表选择你使用的模型供应商,点击`添加`,输入你的密钥;
然后,选择`TEXT EMBEDDING`,在列表选择你使用的模型供应商,点击`添加`,输入你的密钥。
最后,刷新一下页面,分别点击`设置默认模型`列表的LLM和Embedding,选择你使用的模型即可。请确认你的密钥开通了相应的服务,比如我是用的Embedding模型是xxx供应商的,需要去这个供应商官网查看这个模型是否需要购买资源包才能使用。
# 第二部分 配置ragflow服务
# 第一步 登录ragflow服务
你可以在浏览器中访问`http://127.0.0.1:8008`,点击`Sign In`,登录到ragflow服务。
然后点击右上角的`头像`,进入设置页面。在左侧导航栏中,点击`API`功能,然后点击"API Key"按钮。出现一个弹框,
在弹框中,点击"Create new Key"按钮,生成一个API Key。复制这个`API Key`,你稍后会用到。
# 第二步 配置到智控台
确保你的智控台版本是`0.8.7`或以上。使用超级管理员账号登录到智控台。在顶部导航栏中,点击`模型配置`,在左侧导航栏中,点击`知识库`。
在列表中找到`RAG_RAGFlow`,点击`编辑`按钮。
在`服务地址`中,填写`http://你的ragflow服务的局域网IP:8008`,例如我的ragflow服务的局域网IP是`192.168.1.100`,那么我就填写`http://192.168.1.100:8008`。
在`API密钥`中,填写之前复制的`API Key`。
最后点击保存按钮。
# 第二步 创建一个知识库
使用超级管理员账号登录到智控台。在顶部导航栏中,点击`知识库`,在列表左下脚,点击`新增`按钮。填写一个知识库的名字和描述。点击保存。
为了提高大模型对知识库的理解和召回能力,建议在创建知识库时,填写一个有意义的名字和描述。例如,如果你要创建一个关于`公司介绍`的知识库,那么知识库的名字可以是`公司介绍`,描述可以是`关于公司的相关信息例如公司基本信息、服务项目、联系电话、地址等。`。
保存后,你可以在知识库列表中看到这个知识库。点击刚才创建的知识库的`查看`按钮,进入知识库详情页面。
在知识库详情页面中,左下角点击`新增`按钮,可以上传文档到知识库。
上传后,你可以在知识库详情页面中,看到上传的文档。此时可以点击文档的`解析`按钮,解析文档。
解析完成后,你可以查看解析后的切片信息。你可以在知识库详情页面中,点击`召回测试`按钮,可以测试知识库的召回/检索功能。
# 第三步 让小智使用ragflow知识库
登录到智控台。在顶部导航栏中,点击`智能体`,找到你要配置的智能体,点击`配置角色`按钮。
在意图识别左侧,点击`编辑功能`按钮,弹出一个弹框。在弹框中选择你要添加的知识库。保存即可。
+1 -1
View File
@@ -28,7 +28,7 @@ telnet 127.0.0.1 3306
如果不能访问,你需要回忆一下,你的`mysql`是怎么安装的。
如果你的mysql是通过自己使用安装包安装的,说明你的`mysql`做了网络隔离。你可能先解访问`mysql``3306`端口这个问题。
如果你的mysql是通过自己使用安装包安装的,说明你的`mysql`做了网络隔离。你可能先解访问`mysql``3306`端口这个问题。
如果你`mysql`是通过本项目的`docker-compose_all.yml`安装的。你需要找一下你当时创建数据库的`docker-compose_all.yml`文件,修改以下的内容
@@ -299,7 +299,7 @@ public interface Constant {
/**
* 版本号
*/
public static final String VERSION = "0.8.7";
public static final String VERSION = "0.8.8";
/**
* 无效固件URL
@@ -205,8 +205,27 @@ public interface ErrorCode {
int RAG_CONFIG_NOT_FOUND = 10164; // RAG配置未找到
int RAG_CONFIG_TYPE_ERROR = 10165; // RAG配置类型错误
int RAG_DEFAULT_CONFIG_NOT_FOUND = 10166; // 默认RAG配置未找到
int RAG_API_ERROR = 10167; // RAG配置缺少必要参数
int RAG_API_ERROR = 10167; // RAG调用失败
int UPLOAD_FILE_ERROR = 10168; // 上传文件失败
int NO_PERMISSION = 10169; // 没有权限
int KNOWLEDGE_BASE_NAME_EXISTS = 10170; // 同名知识库已存在
int RAG_API_ERROR_URL_NULL = 10171; // RAG配置中base_url为空,请完善配置
int RAG_API_ERROR_API_KEY_NULL = 10172; // RAG配置中api_key为空,请完善配置
int RAG_API_ERROR_API_KEY_INVALID = 10173; // RAG配置中api_key包含占位符,请替换为实际的API密钥
int RAG_API_ERROR_URL_INVALID = 10174; // RAG配置中base_url格式不正确,请检查协议是否正确
int RAG_DATASET_ID_NOT_NULL = 10176; // RAG配置中dataset_id不能为空
int RAG_MODEL_ID_NOT_NULL = 10177; // RAG配置中model_id不能为空
int RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL = 10178; // RAG配置中dataset_id和model_id不能为空
int RAG_FILE_NAME_NOT_NULL = 10179; // 文件名称不能为空
int RAG_FILE_CONTENT_EMPTY = 10180; // 文件内容不能为空
// 设备相关错误码(补充)
int MCA_NOT_NULL = 10175; // mac地址不能为空
// 音色克隆(补充)
int VOICE_CLONE_NAME_NOT_NULL = 10181; // 音色克隆名称不能为空
int VOICE_CLONE_AUDIO_NOT_FOUND = 10182; // 音色克隆音频不存在
// 智能体模板相关错误码(补充)
int AGENT_TEMPLATE_NOT_FOUND = 10183; // 默认智能体未找到
}
@@ -139,14 +139,14 @@ public class AgentChatHistoryController {
// 从Redis获取agentId和sessionId
String agentSessionInfo = (String) redisUtils.get(RedisKeys.getChatHistoryKey(uuid));
if (StringUtils.isBlank(agentSessionInfo)) {
throw new RenException("下载链接已过期或无效");
throw new RenException(ErrorCode.DOWNLOAD_LINK_EXPIRED);
}
try {
// 解析agentId和sessionId
String[] parts = agentSessionInfo.split(":");
if (parts.length != 2) {
throw new RenException("下载链接无效");
throw new RenException(ErrorCode.DOWNLOAD_LINK_INVALID);
}
String agentId = parts[0];
String sessionId = parts[1];
@@ -12,6 +12,7 @@ import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import xiaozhi.common.utils.JsonUtils;
import xiaozhi.modules.agent.dao.AgentPluginMappingMapper;
import xiaozhi.modules.agent.entity.AgentPluginMapping;
@@ -27,6 +28,7 @@ import xiaozhi.modules.model.service.ModelConfigService;
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class AgentPluginMappingServiceImpl extends ServiceImpl<AgentPluginMappingMapper, AgentPluginMapping>
implements AgentPluginMappingService {
private final AgentPluginMappingMapper agentPluginMappingMapper;
@@ -85,7 +87,7 @@ public class AgentPluginMappingServiceImpl extends ServiceImpl<AgentPluginMappin
String description = "如果用户询问与【"
+ String.join(",", knowledgeBaseList.stream().map(KnowledgeBaseEntity::getName).toList())
+ "相关的问题应调用本方法,用于查询:" + String.join(",",
+ "涵盖的主体范围相关内容时应调用本方法,用于查询:" + String.join(",",
knowledgeBaseList.stream().map(KnowledgeBaseEntity::getDescription).toList());
paramInfo.put("description", description);
agentPluginMapping.setParamInfo(JsonUtils.toJsonString(paramInfo));
@@ -73,7 +73,7 @@ public class ConfigServiceImpl implements ConfigService {
// 查询默认智能体
AgentTemplateEntity agent = agentTemplateService.getDefaultTemplate();
if (agent == null) {
throw new RenException("默认智能体未找到");
throw new RenException(ErrorCode.AGENT_TEMPLATE_NOT_FOUND);
}
// 构建模块配置
@@ -111,13 +111,13 @@ public class ConfigServiceImpl implements ConfigService {
if (StringUtils.isNotBlank(cachedCode)) {
throw new RenException(ErrorCode.OTA_DEVICE_NEED_BIND, cachedCode);
}
throw new RenException(ErrorCode.OTA_DEVICE_NOT_FOUND, "not found device");
throw new RenException(ErrorCode.OTA_DEVICE_NOT_FOUND);
}
// 获取智能体信息
AgentEntity agent = agentService.getAgentById(device.getAgentId());
if (agent == null) {
throw new RenException("智能体未找到");
throw new RenException(ErrorCode.AGENT_NOT_FOUND);
}
// 获取音色信息
String voice = null;
@@ -69,7 +69,7 @@ public class DeviceController {
public Result<String> registerDevice(@RequestBody DeviceRegisterDTO deviceRegisterDTO) {
String macAddress = deviceRegisterDTO.getMacAddress();
if (StringUtils.isBlank(macAddress)) {
return new Result<String>().error(ErrorCode.NOT_NULL, "mac地址不能为空");
return new Result<String>().error(ErrorCode.MCA_NOT_NULL);
}
// 生成六位验证码
String code = String.valueOf(Math.random()).substring(2, 8);
@@ -1,6 +1,7 @@
package xiaozhi.modules.knowledge.dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import xiaozhi.common.dao.BaseDao;
import xiaozhi.modules.knowledge.entity.KnowledgeBaseEntity;
@@ -11,4 +12,11 @@ import xiaozhi.modules.knowledge.entity.KnowledgeBaseEntity;
@Mapper
public interface KnowledgeBaseDao extends BaseDao<KnowledgeBaseEntity> {
/**
* 根据知识库ID删除相关的插件映射记录
*
* @param knowledgeBaseId 知识库ID
*/
void deletePluginMappingByKnowledgeBaseId(@Param("knowledgeBaseId") String knowledgeBaseId);
}
@@ -71,11 +71,12 @@ public interface KnowledgeBaseService extends BaseService<KnowledgeBaseEntity> {
Map<String, Object> getRAGConfig(String ragModelId);
/**
* 获取默认RAG配置信息
* 根据知识库ID获取对应的RAG配置
*
* @return 默认RAG配置信息
* @param datasetId 知识库ID
* @return RAG配置
*/
Map<String, Object> getDefaultRAGConfig();
Map<String, Object> getRAGConfigByDatasetId(String datasetId);
/**
* 获取RAG模型列表
@@ -74,13 +74,6 @@ public interface KnowledgeFilesService {
*/
Map<String, Object> getRAGConfig(String ragModelId);
/**
* 获取默认RAG配置信息
*
* @return 默认RAG配置信息
*/
Map<String, Object> getDefaultRAGConfig();
/**
* 解析文档(切块)
*
@@ -1,5 +1,6 @@
package xiaozhi.modules.knowledge.service.impl;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
@@ -51,6 +52,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
private final ModelConfigDao modelConfigDao;
private final RedisUtils redisUtils;
private RestTemplate restTemplate = new RestTemplate();
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
public KnowledgeBaseEntity selectById(Serializable datasetId) {
@@ -108,7 +110,10 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
knowledgeBase.getRagModelId());
knowledgeBase.setDocumentCount(documentCount);
} catch (Exception e) {
log.warn("获取知识库 {} 的文档数量失败: {}", knowledgeBase.getDatasetId(), e.getMessage());
// 构建详细的错误信息,包含异常类型和消息
String baseErrorMessage = e.getClass().getSimpleName() + " - 获取知识库文档数量失败";
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
log.warn("知识库 {} {}", knowledgeBase.getDatasetId(), errorMessage);
knowledgeBase.setDocumentCount(0); // 设置默认值
}
}
@@ -149,7 +154,7 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
knowledgeBaseDTO.getDescription(),
ragConfig);
} catch (Exception e) {
// 如果RAG API调用失败,直接抛出异常,无需回滚(因为还没有插入本地数据库)
// 如果RAG API调用失败,直接抛出异常
throw e;
}
@@ -162,7 +167,12 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
Map<String, Object> ragConfig = getValidatedRAGConfig(knowledgeBaseDTO.getRagModelId());
deleteDatasetInRAGFlow(datasetId, ragConfig);
} catch (Exception deleteException) {
log.warn("删除重复datasetId的RAGFlow数据集失败: {}", deleteException.getMessage());
// 提供更详细的错误信息,包括异常类型和消息
String errorMessage = "删除重复datasetId的RAGFlow数据集失败: " + deleteException.getClass().getSimpleName();
if (deleteException.getMessage() != null) {
errorMessage += " - " + deleteException.getMessage();
}
log.warn(errorMessage, deleteException);
}
throw new RenException(ErrorCode.DB_RECORD_EXISTS);
}
@@ -201,6 +211,35 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
}
}
boolean needRagValidation = StringUtils.isNotBlank(knowledgeBaseDTO.getDatasetId())
&& StringUtils.isNotBlank(knowledgeBaseDTO.getRagModelId());
if (needRagValidation) {
try {
// 先校验RAG配置
Map<String, Object> ragConfig = getValidatedRAGConfig(knowledgeBaseDTO.getRagModelId());
// 调用RAGFlow API更新数据集
updateDatasetInRAGFlow(
knowledgeBaseDTO.getDatasetId(),
knowledgeBaseDTO.getName(),
knowledgeBaseDTO.getDescription(),
ragConfig);
log.info("RAGFlow API更新成功,datasetId: {}", knowledgeBaseDTO.getDatasetId());
} catch (Exception e) {
// 提供更详细的错误信息,包括异常类型和消息
String errorMessage = "更新RAGFlow数据集失败: " + e.getClass().getSimpleName();
if (e.getMessage() != null) {
errorMessage += " - " + e.getMessage();
}
log.error(errorMessage, e);
throw e;
}
} else {
log.warn("datasetId或ragModelId为空,跳过RAGFlow更新");
}
KnowledgeBaseEntity entity = ConvertUtils.sourceToTarget(knowledgeBaseDTO, KnowledgeBaseEntity.class);
knowledgeBaseDao.updateById(entity);
@@ -209,22 +248,6 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
redisUtils.delete(RedisKeys.getKnowledgeBaseCacheKey(entity.getId()));
}
// 调用RAGFlow API更新数据集
if (StringUtils.isNotBlank(knowledgeBaseDTO.getDatasetId())) {
try {
Map<String, Object> ragConfig = getValidatedRAGConfig(knowledgeBaseDTO.getRagModelId());
updateDatasetInRAGFlow(
knowledgeBaseDTO.getDatasetId(),
knowledgeBaseDTO.getName(),
knowledgeBaseDTO.getDescription(),
ragConfig);
} catch (Exception e) {
// 如果RAG API调用失败,回滚本地数据库操作
knowledgeBaseDao.updateById(existingEntity);
throw e;
}
}
return ConvertUtils.sourceToTarget(entity, KnowledgeBaseDTO.class);
}
@@ -265,22 +288,40 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
log.info("找到记录: ID={}, datasetId={}, ragModelId={}",
entity.getId(), entity.getDatasetId(), entity.getRagModelId());
// 先删除本地数据库记录
int deleteCount = knowledgeBaseDao.deleteById(entity.getId());
log.info("本地数据库删除结果: {}", deleteCount > 0 ? "成功" : "失败");
// 调用RAGFlow API删除数据集
// 先调用RAGFlow API删除数据集
boolean apiDeleteSuccess = false;
if (StringUtils.isNotBlank(entity.getDatasetId()) && StringUtils.isNotBlank(entity.getRagModelId())) {
try {
log.info("开始调用RAGFlow API删除数据集");
// 在删除前进行RAG配置校验
Map<String, Object> ragConfig = getValidatedRAGConfig(entity.getRagModelId());
deleteDatasetInRAGFlow(entity.getDatasetId(), ragConfig);
log.info("RAGFlow API删除调用完成");
apiDeleteSuccess = true;
} catch (Exception e) {
log.warn("删除RAGFlow数据集失败: {}", e.getMessage());
// 提供更详细的错误信息,包括异常类型和消息
String errorMessage = "删除RAGFlow数据集失败: " + e.getClass().getSimpleName();
if (e.getMessage() != null) {
errorMessage += " - " + e.getMessage();
}
log.error(errorMessage, e);
throw e;
}
} else {
log.warn("datasetId或ragModelId为空,跳过RAGFlow删除");
apiDeleteSuccess = true; // 没有RAG数据集,视为成功
}
// API删除成功后再删除本地记录
if (apiDeleteSuccess) {
log.info("开始删除ai_agent_plugin_mapping表中与知识库ID '{}' 相关的映射记录", entity.getId());
// 先删除相关的插件映射记录
knowledgeBaseDao.deletePluginMappingByKnowledgeBaseId(entity.getId());
log.info("插件映射记录删除完成");
int deleteCount = knowledgeBaseDao.deleteById(entity.getId());
log.info("本地数据库删除结果: {}", deleteCount > 0 ? "成功" : "失败");
}
log.info("=== 通过datasetId删除操作结束 ===");
@@ -313,29 +354,27 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
}
@Override
public Map<String, Object> getDefaultRAGConfig() {
// 获取默认RAG模型配置
QueryWrapper<ModelConfigEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("model_type", Constant.RAG_CONFIG_TYPE)
.eq("is_default", 1)
.eq("is_enabled", 1);
List<ModelConfigEntity> modelConfigs = modelConfigDao.selectList(queryWrapper);
if (modelConfigs == null || modelConfigs.isEmpty()) {
throw new RenException(ErrorCode.RAG_DEFAULT_CONFIG_NOT_FOUND);
public Map<String, Object> getRAGConfigByDatasetId(String datasetId) {
if (StringUtils.isBlank(datasetId)) {
throw new RenException(ErrorCode.RAG_DATASET_ID_NOT_NULL);
}
ModelConfigEntity defaultConfig = modelConfigs.get(0);
if (defaultConfig.getConfigJson() == null) {
// 根据datasetId查询知识库信息
KnowledgeBaseDTO knowledgeBase = getByDatasetId(datasetId);
if (knowledgeBase == null) {
log.warn("未找到datasetId为{}的知识库", datasetId);
throw new RenException(ErrorCode.Knowledge_Base_RECORD_NOT_EXISTS);
}
// 如果知识库指定了ragModelId,使用该配置
String ragModelId = knowledgeBase.getRagModelId();
if (StringUtils.isBlank(ragModelId)) {
log.warn("知识库datasetId为{}未配置ragModelId", datasetId);
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND);
}
Map<String, Object> config = defaultConfig.getConfigJson();
// 验证必要的配置参数
validateRagConfig(config);
return config;
// 获取并返回RAG配置
return getRAGConfig(ragModelId);
}
@Override
@@ -373,7 +412,22 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
// 验证base_url是否存在且非空
if (StringUtils.isBlank(baseUrl)) {
throw new RenException(ErrorCode.RAG_API_ERROR);
throw new RenException(ErrorCode.RAG_API_ERROR_URL_NULL);
}
// 验证api_key是否存在且非空
if (StringUtils.isBlank(apiKey)) {
throw new RenException(ErrorCode.RAG_API_ERROR_API_KEY_NULL);
}
// 检查api_key是否包含占位符
if (apiKey.contains("")) {
throw new RenException(ErrorCode.RAG_API_ERROR_API_KEY_INVALID);
}
// 验证base_url格式
if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) {
throw new RenException(ErrorCode.RAG_API_ERROR_URL_INVALID);
}
}
@@ -410,14 +464,22 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
// 发送POST请求
log.info("发送POST请求到RAGFlow API...");
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
ResponseEntity<String> response;
try {
response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
} catch (Exception e) {
String errorMessage = url + e.getMessage();
log.error(errorMessage, e);
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
}
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
log.debug("RAGFlow API响应内容: {}", response.getBody());
if (!response.getStatusCode().is2xxSuccessful()) {
log.error("RAGFlow API调用失败,状态码: {}, 响应内容: {}", response.getStatusCode(), response.getBody());
throw new RenException(ErrorCode.RAG_API_ERROR, response.getStatusCode().toString());
String errorMessage = response.getStatusCode() + ", 响应内容: " + response.getBody();
log.error(errorMessage);
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
}
// 解析响应体,提取datasetId
@@ -448,22 +510,36 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
}
} else {
// 如果响应码不为0,说明API调用失败
log.error("RAGFlow API调用失败,响应码: {}, 响应内容: {}", code, message);
throw new RenException(ErrorCode.RAG_API_ERROR,
"RAGFlow API调用失败,响应码: " + code + ", 消息: " + message);
String errorMessage = code + (message != null ? message : "null");
log.error(errorMessage);
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
}
log.info("从RAGFlow API响应中解析出datasetId: {}", datasetId);
log.debug("完整响应内容: {}", responseBody);
} catch (IOException e) {
// 构建详细的错误信息,包含异常类型和消息
String baseErrorMessage = e.getClass().getSimpleName();
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
log.error(errorMessage, e);
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} catch (Exception e) {
log.error("解析RAGFlow API响应失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "解析响应失败: " + e.getMessage());
// 构建详细的错误信息,包含异常类型和消息
String baseErrorMessage = e.getClass().getSimpleName();
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
log.error(errorMessage, e);
// 如果解析失败,但响应体不为空,尝试直接使用响应体作为错误信息
String finalErrorMessage = responseBody;
if (e.getMessage() != null) {
finalErrorMessage += errorMessage;
}
throw new RenException(ErrorCode.RAG_API_ERROR, finalErrorMessage);
}
}
if (StringUtils.isBlank(datasetId)) {
log.error("无法从RAGFlow API响应中获取datasetId,响应内容: {}", responseBody);
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API响应中未包含datasetId");
throw new RenException(ErrorCode.RAG_DATASET_ID_NOT_NULL);
}
log.info("RAGFlow数据集创建成功,datasetId: {}", datasetId);
@@ -503,14 +579,55 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
// 发送PUT请求
log.info("发送PUT请求到RAGFlow API...");
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class);
ResponseEntity<String> response;
try {
response = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class);
} catch (Exception e) {
String errorMessage = url + e.getMessage();
log.error(errorMessage, e);
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
}
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
log.debug("RAGFlow API响应内容: {}", response.getBody());
if (!response.getStatusCode().is2xxSuccessful()) {
log.error("RAGFlow API调用失败,状态码: {}, 响应内容: {}", response.getStatusCode(), response.getBody());
throw new RenException(ErrorCode.RAG_API_ERROR);
String errorMessage = response.getStatusCode() + ", 响应内容: " + response.getBody();
log.error(errorMessage);
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
}
// 解析响应体,验证操作是否真正成功
String responseBody = response.getBody();
if (responseBody != null) {
try {
Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
Integer code = (Integer) responseMap.get("code");
String message = (String) responseMap.get("message");
if (code != null && code != 0) {
String errorMessage = code + (message != null ? message : "null");
log.error(errorMessage);
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
}
} catch (IOException e) {
// 构建详细的错误信息,包含异常类型和消息
String baseErrorMessage = e.getClass().getSimpleName();
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
log.error(errorMessage, e);
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} catch (Exception e) {
// 构建详细的错误信息,包含异常类型和消息
String baseErrorMessage = e.getClass().getSimpleName();
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
log.error(errorMessage, e);
// 如果解析失败,但响应体不为空,尝试直接使用响应体作为错误信息
String finalErrorMessage = responseBody;
if (e.getMessage() != null) {
finalErrorMessage += errorMessage;
}
throw new RenException(ErrorCode.RAG_API_ERROR, finalErrorMessage);
}
}
log.info("RAGFlow数据集更新成功,datasetId: {}", datasetId);
@@ -545,16 +662,57 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
// 发送DELETE请求
log.info("发送DELETE请求到RAGFlow API...");
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity,
String.class);
ResponseEntity<String> response;
try {
response = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, String.class);
} catch (Exception e) {
String errorMessage = url + e.getMessage();
log.error(errorMessage, e);
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
}
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
log.debug("RAGFlow API响应内容: {}", response.getBody());
if (!response.getStatusCode().is2xxSuccessful()) {
log.error("RAGFlow API调用失败,状态码: {}, 响应内容: {}", response.getStatusCode(), response.getBody());
throw new RenException(ErrorCode.RAG_API_ERROR);
String errorMessage = response.getStatusCode() + response.getBody();
log.error(errorMessage);
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
}
// 解析响应体,验证操作是否真正成功
String responseBody = response.getBody();
if (responseBody != null) {
try {
Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
Integer code = (Integer) responseMap.get("code");
String message = (String) responseMap.get("message");
if (code != null && code != 0) {
String errorMessage = code + (message != null ? message : "null");
log.error(errorMessage);
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
}
} catch (IOException e) {
// 构建详细的错误信息,包含异常类型和消息
String baseErrorMessage = e.getClass().getSimpleName();
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
log.error(errorMessage, e);
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} catch (Exception e) {
// 构建详细的错误信息,包含异常类型和消息
String baseErrorMessage = e.getClass().getSimpleName();
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
log.error(errorMessage, e);
// 如果解析失败,但响应体不为空,尝试直接使用响应体作为错误信息
String finalErrorMessage = responseBody;
if (e.getMessage() != null) {
finalErrorMessage += errorMessage;
}
throw new RenException(ErrorCode.RAG_API_ERROR, finalErrorMessage);
}
}
log.info("RAGFlow数据集删除成功,datasetId: {}", datasetId);
}
@@ -563,48 +721,18 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
* 获取RAG配置并验证
*/
private Map<String, Object> getValidatedRAGConfig(String ragModelId) {
Map<String, Object> ragConfig;
if (StringUtils.isNotBlank(ragModelId)) {
ragConfig = getRAGConfig(ragModelId);
} else {
ragConfig = getDefaultRAGConfig();
if (StringUtils.isBlank(ragModelId)) {
throw new RenException(ErrorCode.RAG_MODEL_ID_NOT_NULL);
}
// 验证baseUrl和apiKey
validateRAGConfigParameters(ragConfig);
Map<String, Object> ragConfig = getRAGConfig(ragModelId);
// 验证RAG配置参数
validateRagConfig(ragConfig);
return ragConfig;
}
/**
* 验证RAG配置参数
*/
private void validateRAGConfigParameters(Map<String, Object> ragConfig) {
if (ragConfig == null) {
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND, "RAG配置为空,请检查配置");
}
// 从配置中提取必要的参数
String baseUrl = (String) ragConfig.get("base_url");
String apiKey = (String) ragConfig.get("api_key");
if (StringUtils.isBlank(baseUrl)) {
throw new RenException(ErrorCode.RAG_API_ERROR, "RAG配置中base_url为空,请完善配置");
}
if (StringUtils.isBlank(apiKey)) {
throw new RenException(ErrorCode.RAG_API_ERROR, "RAG配置中api_key为空,请完善配置");
}
if (apiKey.contains("")) {
throw new RenException(ErrorCode.RAG_API_ERROR, "RAG配置中api_key包含占位符'你',请替换为实际的API密钥");
}
if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) {
throw new RenException(ErrorCode.RAG_API_ERROR, "RAG配置中base_url格式不正确,必须以http://或https://开头");
}
}
/**
* 检查是否存在同名知识库
*
@@ -660,7 +788,14 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
// 发送GET请求
log.info("发送GET请求到RAGFlow API获取文档数量...");
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
ResponseEntity<String> response;
try {
response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
} catch (Exception e) {
String errorMessage = url + e.getMessage();
log.error(errorMessage, e);
return 0;
}
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
@@ -696,8 +831,16 @@ public class KnowledgeBaseServiceImpl extends BaseServiceImpl<KnowledgeBaseDao,
} else {
log.error("RAGFlow API调用失败,响应码: {}, 响应内容: {}", code, responseBody);
}
} catch (IOException e) {
// 构建详细的错误信息,包含异常类型和消息
String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应时发生IO异常";
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
log.error(errorMessage, e);
} catch (Exception e) {
log.error("解析RAGFlow API响应失败: {}", e.getMessage(), e);
// 构建详细的错误信息,包含异常类型和消息
String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应失败";
String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : "");
log.error(errorMessage, e);
}
return 0;
}
@@ -16,43 +16,39 @@ import org.springframework.core.io.AbstractResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import xiaozhi.common.constant.Constant;
import xiaozhi.common.exception.ErrorCode;
import xiaozhi.common.exception.RenException;
import xiaozhi.common.page.PageData;
import xiaozhi.modules.knowledge.dto.KnowledgeFilesDTO;
import xiaozhi.modules.knowledge.service.KnowledgeBaseService;
import xiaozhi.modules.knowledge.service.KnowledgeFilesService;
import xiaozhi.modules.model.dao.ModelConfigDao;
import xiaozhi.modules.model.entity.ModelConfigEntity;
import xiaozhi.modules.model.service.ModelConfigService;
@Service
@AllArgsConstructor
@Slf4j
public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
private final ModelConfigService modelConfigService;
private final ModelConfigDao modelConfigDao;
private final KnowledgeBaseService knowledgeBaseService;
private RestTemplate restTemplate = new RestTemplate();
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public Map<String, Object> getRAGConfig(String ragModelId) {
return knowledgeBaseService.getRAGConfig(ragModelId);
}
@Override
public PageData<KnowledgeFilesDTO> getPageList(KnowledgeFilesDTO knowledgeFilesDTO, Integer page, Integer limit) {
try {
@@ -64,17 +60,17 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
knowledgeFilesDTO != null ? knowledgeFilesDTO.getStatus() : null,
page, limit);
// 获取RAG配置
Map<String, Object> ragConfig = getDefaultRAGConfig();
String baseUrl = (String) ragConfig.get("base_url");
String apiKey = (String) ragConfig.get("api_key");
// 构建请求URL - 根据RAGFlow API文档,获取文档列表的接口
String datasetId = knowledgeFilesDTO != null ? knowledgeFilesDTO.getDatasetId() : null;
if (StringUtils.isBlank(datasetId)) {
throw new RenException(ErrorCode.PARAMS_GET_ERROR, "datasetId不能为空");
throw new RenException(ErrorCode.RAG_DATASET_ID_NOT_NULL);
}
// 获取RAG配置
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
String baseUrl = (String) ragConfig.get("base_url");
String apiKey = (String) ragConfig.get("api_key");
String url = baseUrl + "/api/v1/datasets/" + datasetId + "/documents";
// 添加查询参数
@@ -112,8 +108,8 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
if (!response.getStatusCode().is2xxSuccessful()) {
log.error("RAGFlow API调用失败,状态码: {}, 响应内容: {}", response.getStatusCode(), response.getBody());
throw new RenException(ErrorCode.RAG_API_ERROR);
log.error("RAGFlow API调用失败,状态码: {}", response.getStatusCode());
throw new RenException(ErrorCode.RAG_API_ERROR, response.getStatusCode().toString());
}
String responseBody = response.getBody();
@@ -127,27 +123,22 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
Object dataObj = responseMap.get("data");
return parseDocumentListResponse(dataObj, page, limit);
} else {
log.error("RAGFlow API调用失败,响应码: {}, 响应内容: {}", code, responseBody);
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API调用失败,响应码: " + code);
log.error("RAGFlow API调用失败,响应码: {}", code);
// 获取错误消息,如果存在的话
String apiMessage = (String) responseMap.get("message");
String errorDetail = apiMessage != null ? apiMessage : "无详细错误信息";
log.error("RAGFlow API调用失败,响应码: {}, 错误详情: {}", errorDetail);
throw new RenException(ErrorCode.RAG_API_ERROR, responseBody);
}
} catch (IOException e) {
log.error("解析RAGFlow API响应失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "解析RAGFlow响应失败: " + e.getMessage());
} catch (HttpClientErrorException e) {
log.error("RAGFlow API调用失败 - HTTP错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "获取RAGFlow文档列表失败: " + e.getMessage());
} catch (HttpServerErrorException e) {
log.error("RAGFlow API调用失败 - 服务器错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "获取RAGFlow文档列表失败: " + e.getMessage());
} catch (ResourceAccessException e) {
log.error("RAGFlow API调用失败 - 网络连接错误: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "获取RAGFlow文档列表失败: 网络连接错误 - " + e.getMessage());
} catch (Exception e) {
log.error("获取文档列表失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "获取文档列表失败: " + e.getMessage());
String errorMessage = e.getMessage() != null ? e.getMessage() : "null";
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} finally {
log.info("=== 获取文档列表操作结束 ===");
}
@@ -238,7 +229,7 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
} catch (Exception e) {
log.error("获取文档列表响应失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "获取文档列表响应失败: " + e.getMessage());
throw new RenException(ErrorCode.RAG_API_ERROR, e.getMessage());
}
}
@@ -262,7 +253,8 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
long currentTime = System.currentTimeMillis();
// 调用RAGFlow API获取文档切片信息
Map<String, Object> ragConfig = getDefaultRAGConfig();
String datasetId = dto.getDatasetId();
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
String baseUrl = (String) ragConfig.get("base_url");
String apiKey = (String) ragConfig.get("api_key");
@@ -450,7 +442,7 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
@Override
public KnowledgeFilesDTO getByDocumentId(String documentId, String datasetId) {
if (StringUtils.isBlank(documentId) || StringUtils.isBlank(datasetId)) {
throw new RenException(ErrorCode.PARAMS_GET_ERROR, "documentId和datasetId不能为空");
throw new RenException(ErrorCode.RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL);
}
log.info("=== 开始根据documentId获取文档 ===");
@@ -458,7 +450,7 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
try {
// 获取RAG配置
Map<String, Object> ragConfig = getDefaultRAGConfig();
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
String baseUrl = (String) ragConfig.get("base_url");
String apiKey = (String) ragConfig.get("api_key");
@@ -480,8 +472,10 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
if (!response.getStatusCode().is2xxSuccessful()) {
log.error("RAGFlow API调用失败,状态码: {}, 响应内容: {}", response.getStatusCode(), response.getBody());
throw new RenException(ErrorCode.RAG_API_ERROR);
log.error("RAGFlow API调用失败,状态码: {}", response.getStatusCode());
String responseBody = response.getBody();
throw new RenException(ErrorCode.RAG_API_ERROR,
response.getStatusCode() + (responseBody != null ? responseBody : "null"));
}
String responseBody = response.getBody();
@@ -502,32 +496,21 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
}
throw new RenException(ErrorCode.Knowledge_Base_RECORD_NOT_EXISTS);
} else {
log.error("RAGFlow API调用失败,响应码: {}, 响应内容: {}", code, responseBody);
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API调用失败,响应码: " + code);
log.error("RAGFlow API调用失败,响应码: {}", code);
// 获取错误消息,如果存在的话
String apiMessage = (String) responseMap.get("message");
String errorDetail = apiMessage != null ? apiMessage : "无详细错误信息";
log.error("RAGFlow API调用失败详情: {}", errorDetail);
throw new RenException(ErrorCode.RAG_API_ERROR, responseBody);
}
} catch (IOException e) {
log.error("解析RAGFlow API响应失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR,
"解析RAGFlow响应失败: " + e.getMessage());
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
log.warn("文档不存在,documentId: {}, datasetId: {}", documentId, datasetId);
throw new RenException(ErrorCode.Knowledge_Base_RECORD_NOT_EXISTS);
}
log.error("RAGFlow API调用失败 - HTTP错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString());
throw new RenException(ErrorCode.RAG_API_ERROR, "获取RAGFlow文档失败: " + e.getMessage());
} catch (HttpServerErrorException e) {
log.error("RAGFlow API调用失败 - 服务器错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString());
throw new RenException(ErrorCode.RAG_API_ERROR, "获取RAGFlow文档失败: " + e.getMessage());
} catch (ResourceAccessException e) {
log.error("RAGFlow API调用失败 - 网络连接错误: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "获取RAGFlow文档失败: 网络连接错误 - " + e.getMessage());
} catch (Exception e) {
log.error("根据documentId获取文档失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "获取文档失败: " + e.getMessage());
String errorMessage = e.getMessage() != null ? e.getMessage() : "null";
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} finally {
log.info("=== 根据documentId获取文档操作结束 ===");
}
@@ -537,7 +520,7 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
public PageData<KnowledgeFilesDTO> getPageListByStatus(String datasetId, Integer status, Integer page,
Integer limit) {
if (StringUtils.isBlank(datasetId)) {
throw new RenException(ErrorCode.PARAMS_GET_ERROR, "datasetId不能为空");
throw new RenException(ErrorCode.RAG_DATASET_ID_NOT_NULL);
}
log.info("=== 开始根据状态查询文档列表 ===");
@@ -545,7 +528,7 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
try {
// 获取RAG配置
Map<String, Object> ragConfig = getDefaultRAGConfig();
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
String baseUrl = (String) ragConfig.get("base_url");
String apiKey = (String) ragConfig.get("api_key");
@@ -583,8 +566,8 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
if (!response.getStatusCode().is2xxSuccessful()) {
log.error("RAGFlow API调用失败,状态码: {}, 响应内容: {}", response.getStatusCode(), response.getBody());
throw new RenException(ErrorCode.RAG_API_ERROR);
log.error("RAGFlow API调用失败,状态码: {}", response.getStatusCode());
throw new RenException(ErrorCode.RAG_API_ERROR, response.getStatusCode().toString());
}
String responseBody = response.getBody();
@@ -615,28 +598,13 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
datasetId, status, pageData.getList().size());
return pageData;
} else {
log.error("RAGFlow API调用失败,响应码: {}, 响应内容: {}", code, responseBody);
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API调用失败,响应码: " + code);
log.error("RAGFlow API调用失败,响应码: {}", code);
throw new RenException(ErrorCode.RAG_API_ERROR, code.toString());
}
} catch (IOException e) {
log.error("解析RAGFlow API响应失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR,
"解析RAGFlow响应失败: " + e.getMessage());
} catch (HttpClientErrorException e) {
log.error("RAGFlow API调用失败 - HTTP错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString());
throw new RenException(ErrorCode.RAG_API_ERROR, "获取RAGFlow文档列表失败: " + e.getMessage());
} catch (HttpServerErrorException e) {
log.error("RAGFlow API调用失败 - 服务器错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString());
throw new RenException(ErrorCode.RAG_API_ERROR, "获取RAGFlow文档列表失败: " + e.getMessage());
} catch (ResourceAccessException e) {
log.error("RAGFlow API调用失败 - 网络连接错误: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "获取RAGFlow文档列表失败: 网络连接错误 - " + e.getMessage());
} catch (Exception e) {
log.error("根据状态查询文档列表失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "查询文档列表失败: " + e.getMessage());
throw new RenException(ErrorCode.RAG_API_ERROR, e.getMessage());
} finally {
log.info("=== 根据状态查询文档列表操作结束 ===");
}
@@ -666,12 +634,12 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
// 检查文件基本信息
if (StringUtils.isBlank(fileName)) {
log.error("文件名为空");
throw new RenException(ErrorCode.PARAMS_GET_ERROR, "文件名不能为空");
throw new RenException(ErrorCode.RAG_FILE_NAME_NOT_NULL);
}
if (fileSize == 0) {
log.error("文件大小为0");
throw new RenException(ErrorCode.PARAMS_GET_ERROR, "文件内容为空");
throw new RenException(ErrorCode.RAG_FILE_CONTENT_EMPTY);
}
log.info("2. 开始流式上传到RAGFlow");
@@ -707,7 +675,7 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
@Override
public void deleteByDocumentId(String documentId, String datasetId) {
if (StringUtils.isBlank(documentId) || StringUtils.isBlank(datasetId)) {
throw new RenException(ErrorCode.PARAMS_GET_ERROR, "documentId和datasetId不能为空");
throw new RenException(ErrorCode.RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL);
}
log.info("=== 开始根据documentId删除文档 ===");
@@ -722,7 +690,11 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
} catch (Exception e) {
log.error("删除文档失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "删除文档失败: " + e.getMessage());
String errorMessage = e.getMessage() != null ? e.getMessage() : "null";
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} finally {
log.info("=== 根据documentId删除文档操作结束 ===");
}
@@ -776,58 +748,6 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
}
}
@Override
public Map<String, Object> getRAGConfig(String ragModelId) {
if (StringUtils.isBlank(ragModelId)) {
throw new RenException(ErrorCode.PARAMS_GET_ERROR);
}
// 从缓存获取模型配置
ModelConfigEntity modelConfig = modelConfigService.getModelByIdFromCache(ragModelId);
if (modelConfig == null || modelConfig.getConfigJson() == null) {
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND);
}
// 验证是否为RAG类型配置
if (!Constant.RAG_CONFIG_TYPE.equals(modelConfig.getModelType().toUpperCase())) {
throw new RenException(ErrorCode.RAG_CONFIG_TYPE_ERROR);
}
Map<String, Object> config = modelConfig.getConfigJson();
// 验证必要的配置参数
validateRagConfig(config);
// 返回配置信息
return config;
}
@Override
public Map<String, Object> getDefaultRAGConfig() {
// 获取默认RAG模型配置
QueryWrapper<ModelConfigEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("model_type", Constant.RAG_CONFIG_TYPE)
.eq("is_default", 1)
.eq("is_enabled", 1);
List<ModelConfigEntity> modelConfigs = modelConfigDao.selectList(queryWrapper);
if (modelConfigs == null || modelConfigs.isEmpty()) {
throw new RenException(ErrorCode.RAG_DEFAULT_CONFIG_NOT_FOUND);
}
ModelConfigEntity defaultConfig = modelConfigs.get(0);
if (defaultConfig.getConfigJson() == null) {
throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND);
}
Map<String, Object> config = defaultConfig.getConfigJson();
// 验证必要的配置参数
validateRagConfig(config);
return config;
}
/**
* 验证RAG配置中是否包含必要的参数
*/
@@ -842,7 +762,22 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
// 验证base_url是否存在且非空
if (StringUtils.isBlank(baseUrl)) {
throw new RenException(ErrorCode.RAG_API_ERROR);
throw new RenException(ErrorCode.RAG_API_ERROR_URL_NULL);
}
// 验证api_key是否存在且非空
if (StringUtils.isBlank(apiKey)) {
throw new RenException(ErrorCode.RAG_API_ERROR_API_KEY_NULL);
}
// 检查api_key是否包含占位符
if (apiKey.contains("")) {
throw new RenException(ErrorCode.RAG_API_ERROR_API_KEY_INVALID);
}
// 验证base_url格式
if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) {
throw new RenException(ErrorCode.RAG_API_ERROR_URL_INVALID);
}
}
@@ -854,7 +789,7 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
Map<String, Object> parserConfig) {
try {
// 获取RAG配置
Map<String, Object> ragConfig = getDefaultRAGConfig();
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
String baseUrl = (String) ragConfig.get("base_url");
String apiKey = (String) ragConfig.get("api_key");
@@ -939,44 +874,39 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
log.info("文档上传成功,documentId: {}", documentId);
} else {
// 如果响应码不为0,说明API调用失败
log.error("RAGFlow API调用失败,响应码: {}, 响应内容: {}", code, responseBody);
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API调用失败,响应码: " + code);
log.error("RAGFlow API调用失败,响应码: {}", code);
// 获取错误消息,如果存在的话
String apiMessage = (String) responseMap.get("message");
String errorDetail = apiMessage != null ? apiMessage : "无详细错误信息";
log.error("RAGFlow API调用失败详情: {}", errorDetail);
throw new RenException(ErrorCode.RAG_API_ERROR, responseBody);
}
log.info("从RAGFlow API响应中解析出documentId: {}", documentId);
log.debug("完整响应内容: {}", responseBody);
} catch (Exception e) {
log.error("解析RAGFlow API响应失败: {}, 响应内容: {}", e.getMessage(), responseBody);
throw new RenException(ErrorCode.RAG_API_ERROR, "解析RAGFlow响应失败: " + e.getMessage());
log.error("解析RAGFlow API响应失败: {}", e.getMessage());
throw new RenException(ErrorCode.RAG_API_ERROR, responseBody);
}
} else {
log.error("RAGFlow API调用失败,状态码: {}, 响应内容: {}", response.getStatusCode(), responseBody);
throw new RenException(ErrorCode.RAG_API_ERROR);
log.error("RAGFlow API调用失败,状态码: {}", response.getStatusCode());
throw new RenException(ErrorCode.RAG_API_ERROR, response.getStatusCode().toString());
}
if (StringUtils.isBlank(documentId)) {
log.error("无法从RAGFlow API响应中获取documentId,响应内容: {}", responseBody);
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API响应中未包含documentId");
log.error("无法从RAGFlow API响应中获取documentId");
throw new RenException(ErrorCode.RAG_API_ERROR, responseBody);
}
log.info("RAGFlow文档上传成功,documentId: {},文档已开始自动解析切片", documentId);
return documentId;
} catch (HttpClientErrorException e) {
log.error("RAGFlow API调用失败 - HTTP错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString(), e);
throw new RenException(ErrorCode.RAG_API_ERROR,
"上传RAGFlow文档失败: " + e.getMessage() + ", 响应: " + e.getResponseBodyAsString());
} catch (HttpServerErrorException e) {
log.error("RAGFlow API调用失败 - 服务器错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString(), e);
throw new RenException(ErrorCode.RAG_API_ERROR,
"上传RAGFlow文档失败: " + e.getMessage() + ", 响应: " + e.getResponseBodyAsString());
} catch (ResourceAccessException e) {
log.error("RAGFlow API调用失败 - 网络连接错误: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "上传RAGFlow文档失败: 网络连接错误 - " + e.getMessage());
} catch (Exception e) {
log.error("RAGFlow API调用失败 - 未知错误: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "上传RAGFlow文档失败: " + e.getMessage());
log.error("RAGFlow API调用失败: {}", e.getMessage(), e);
String errorMessage = e.getMessage() != null ? e.getMessage() : "null";
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
}
}
@@ -1048,7 +978,7 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
private void deleteDocumentInRAGFlow(String documentId, String datasetId) {
try {
// 获取RAG配置
Map<String, Object> ragConfig = getDefaultRAGConfig();
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
String baseUrl = (String) ragConfig.get("base_url");
String apiKey = (String) ragConfig.get("api_key");
@@ -1093,8 +1023,9 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
return;
} else {
String message = (String) responseMap.get("message");
log.error("RAGFlow API调用失败,响应码: {}, 消息: {}", code, message);
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API调用失败: " + message);
log.error("RAGFlow API调用失败,响应码: {}", code);
String errorDetail = message != null ? message : "无详细错误信息";
throw new RenException(ErrorCode.RAG_API_ERROR, responseBody);
}
} catch (Exception e) {
log.warn("解析RAGFlow响应失败,但HTTP状态码成功,视为删除成功: {}", e.getMessage());
@@ -1106,26 +1037,18 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
return;
}
} else {
log.error("RAGFlow API调用失败,状态码: {}, 响应内容: {}", response.getStatusCode(), responseBody);
throw new RenException(ErrorCode.RAG_API_ERROR);
log.error("RAGFlow API调用失败,状态码: {}", response.getStatusCode());
throw new RenException(ErrorCode.RAG_API_ERROR,
response.getStatusCode() + (responseBody != null ? responseBody : "null"));
}
} catch (HttpClientErrorException e) {
log.error("RAGFlow API调用失败 - HTTP错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString(), e);
throw new RenException(ErrorCode.RAG_API_ERROR,
"删除RAGFlow文档失败: " + e.getMessage() + ", 响应: " + e.getResponseBodyAsString());
} catch (HttpServerErrorException e) {
log.error("RAGFlow API调用失败 - 服务器错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString(), e);
throw new RenException(ErrorCode.RAG_API_ERROR,
"删除RAGFlow文档失败: " + e.getMessage() + ", 响应: " + e.getResponseBodyAsString());
} catch (ResourceAccessException e) {
log.error("RAGFlow API调用失败 - 网络连接错误: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "删除RAGFlow文档失败: 网络连接错误 - " + e.getMessage());
} catch (Exception e) {
log.error("RAGFlow API调用失败 - 未知错误: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "删除RAGFlow文档失败: " + e.getMessage());
log.error("RAGFlow API调用失败: {}", e.getMessage(), e);
String errorMessage = e.getMessage() != null ? e.getMessage() : "null";
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
}
}
@@ -1170,7 +1093,7 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
@Override
public boolean parseDocuments(String datasetId, List<String> documentIds) {
if (StringUtils.isBlank(datasetId) || documentIds == null || documentIds.isEmpty()) {
throw new RenException(ErrorCode.PARAMS_GET_ERROR, "datasetId和documentIds不能为空");
throw new RenException(ErrorCode.RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL);
}
log.info("=== 开始解析文档(切块) ===");
@@ -1178,7 +1101,7 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
try {
// 获取RAG配置
Map<String, Object> ragConfig = getDefaultRAGConfig();
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
String baseUrl = (String) ragConfig.get("base_url");
String apiKey = (String) ragConfig.get("api_key");
@@ -1204,14 +1127,15 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
if (!response.getStatusCode().is2xxSuccessful()) {
log.error("RAGFlow API调用失败,状态码: {}, 响应内容: {}", response.getStatusCode(), response.getBody());
throw new RenException(ErrorCode.RAG_API_ERROR);
}
String responseBody = response.getBody();
log.debug("RAGFlow API响应内容: {}", responseBody);
if (!response.getStatusCode().is2xxSuccessful()) {
log.error("RAGFlow API调用失败,状态码: {}", response.getStatusCode());
String errorDetail = responseBody != null ? responseBody : "无响应内容";
throw new RenException(ErrorCode.RAG_API_ERROR, response.getStatusCode() + errorDetail);
}
// 解析响应
Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
Integer code = (Integer) responseMap.get("code");
@@ -1220,28 +1144,20 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
log.info("文档解析成功,datasetId: {}, documentIds: {}", datasetId, documentIds);
return true;
} else {
// 获取错误消息,如果存在的话
String message = (String) responseMap.get("message");
log.error("RAGFlow API调用失败,响应码: {}, 消息: {}, 响应内容: {}", code, message, responseBody);
throw new RenException(ErrorCode.RAG_API_ERROR, response.getStatusCode().toString());
String errorDetail = message != null ? message : "无详细错误信息";
log.error("RAGFlow API调用失败,响应码: {}, 错误信息: {}", code, errorDetail);
throw new RenException(ErrorCode.RAG_API_ERROR, responseBody);
}
} catch (IOException e) {
log.error("解析RAGFlow API响应失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "解析RAGFlow响应失败: " + e.getMessage());
} catch (HttpClientErrorException e) {
log.error("RAGFlow API调用失败 - HTTP错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "解析RAGFlow文档失败: " + e.getMessage());
} catch (HttpServerErrorException e) {
log.error("RAGFlow API调用失败 - 服务器错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "解析RAGFlow文档失败: " + e.getMessage());
} catch (ResourceAccessException e) {
log.error("RAGFlow API调用失败 - 网络连接错误: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "解析RAGFlow文档失败: 网络连接错误 - " + e.getMessage());
} catch (Exception e) {
log.error("解析文档失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "解析文档失败: " + e.getMessage());
String errorMessage = e.getMessage() != null ? e.getMessage() : "null";
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} finally {
log.info("=== 解析文档操作结束 ===");
}
@@ -1251,7 +1167,7 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
public Map<String, Object> listChunks(String datasetId, String documentId, String keywords,
Integer page, Integer pageSize, String chunkId) {
if (StringUtils.isBlank(datasetId) || StringUtils.isBlank(documentId)) {
throw new RenException(ErrorCode.PARAMS_GET_ERROR, "datasetId和documentId不能为空");
throw new RenException(ErrorCode.RAG_DATASET_ID_AND_MODEL_ID_NOT_NULL);
}
log.info("=== 开始列出切片 ===");
@@ -1260,7 +1176,7 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
try {
// 获取RAG配置
Map<String, Object> ragConfig = getDefaultRAGConfig();
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId);
String baseUrl = (String) ragConfig.get("base_url");
String apiKey = (String) ragConfig.get("api_key");
@@ -1308,14 +1224,15 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
if (!response.getStatusCode().is2xxSuccessful()) {
log.error("RAGFlow API调用失败,状态码: {}, 响应内容: {}", response.getStatusCode(), response.getBody());
throw new RenException(ErrorCode.RAG_API_ERROR, "列出切片失败");
}
String responseBody = response.getBody();
log.debug("RAGFlow API响应内容: {}", responseBody);
if (!response.getStatusCode().is2xxSuccessful()) {
log.error("RAGFlow API调用失败,状态码: {}", response.getStatusCode());
String errorDetail = responseBody != null ? responseBody : "无响应内容";
throw new RenException(ErrorCode.RAG_API_ERROR, response.getStatusCode() + errorDetail);
}
// 解析响应
Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
Integer code = (Integer) responseMap.get("code");
@@ -1326,28 +1243,24 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
// 解析切片数据并格式化返回
return parseChunkListResponse(responseMap);
} else {
// 获取错误消息,如果存在的话
String message = (String) responseMap.get("message");
log.error("RAGFlow API调用失败,响应码: {}, 消息: {}, 响应内容: {}", code, message, responseBody);
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API调用失败: " + message);
String errorDetail = message != null ? message : "无详细错误信息";
log.error("RAGFlow API调用失败,响应码: {}, 错误信息: {}", code, errorDetail);
throw new RenException(ErrorCode.RAG_API_ERROR, responseBody);
}
} catch (IOException e) {
log.error("解析RAGFlow API响应失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "解析RAGFlow响应失败: " + e.getMessage());
} catch (HttpClientErrorException e) {
log.error("RAGFlow API调用失败 - HTTP错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "列出切片失败: " + e.getMessage());
} catch (HttpServerErrorException e) {
log.error("RAGFlow API调用失败 - 服务器错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "列出切片失败: " + e.getMessage());
} catch (ResourceAccessException e) {
log.error("RAGFlow API调用失败 - 网络连接错误: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "列出切片失败: 网络连接错误 - " + e.getMessage());
String errorMessage = e.getMessage() != null ? e.getMessage() : "null";
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} catch (Exception e) {
log.error("列出切片失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "列出切片失败: " + e.getMessage());
String errorMessage = e.getMessage() != null ? e.getMessage() : "null";
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} finally {
log.info("=== 列出切片操作结束 ===");
}
@@ -1661,7 +1574,7 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
try {
// 获取RAG配置
Map<String, Object> ragConfig = getDefaultRAGConfig();
Map<String, Object> ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetIds.get(0));
String baseUrl = (String) ragConfig.get("base_url");
String apiKey = (String) ragConfig.get("api_key");
@@ -1736,14 +1649,15 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
log.info("RAGFlow API响应状态码: {}", response.getStatusCode());
if (!response.getStatusCode().is2xxSuccessful()) {
log.error("RAGFlow API调用失败,状态码: {}, 响应内容: {}", response.getStatusCode(), response.getBody());
throw new RenException(ErrorCode.RAG_API_ERROR);
}
String responseBody = response.getBody();
log.debug("RAGFlow API响应内容: {}", responseBody);
if (!response.getStatusCode().is2xxSuccessful()) {
log.error("RAGFlow API调用失败,状态码: {}", response.getStatusCode());
String errorDetail = responseBody != null ? responseBody : "无响应内容";
throw new RenException(ErrorCode.RAG_API_ERROR, response.getStatusCode() + errorDetail);
}
// 解析响应
Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
Integer code = (Integer) responseMap.get("code");
@@ -1755,32 +1669,24 @@ public class KnowledgeFilesServiceImpl implements KnowledgeFilesService {
log.info("召回测试成功,返回 {} 条切片", result.get("total"));
return result;
} else {
log.error("RAGFlow API响应格式错误,data字段不是Map类型: {}", dataObj);
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API响应格式错误");
log.error("RAGFlow API响应格式错误,data字段不是Map类型");
throw new RenException(ErrorCode.RAG_API_ERROR, responseBody);
}
} else {
// 获取错误消息,如果存在的话
String message = (String) responseMap.get("message");
log.error("RAGFlow API调用失败,响应码: {}, 错误信息: {}", code, message);
throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API调用失败: " + message);
String errorDetail = message != null ? message : "无详细错误信息";
log.error("RAGFlow API调用失败,响应码: {}, 错误信息: {}", code, errorDetail);
throw new RenException(ErrorCode.RAG_API_ERROR, responseBody);
}
} catch (IOException e) {
log.error("解析RAGFlow API响应失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "解析RAGFlow响应失败: " + e.getMessage());
} catch (HttpClientErrorException e) {
log.error("RAGFlow API调用失败 - HTTP错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "召回测试失败: " + e.getMessage());
} catch (HttpServerErrorException e) {
log.error("RAGFlow API调用失败 - 服务器错误: {}, 状态码: {}, 响应内容: {}",
e.getMessage(), e.getStatusCode(), e.getResponseBodyAsString(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "召回测试失败: " + e.getMessage());
} catch (ResourceAccessException e) {
log.error("RAGFlow API调用失败 - 网络连接错误: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "召回测试失败: 网络连接错误 - " + e.getMessage());
} catch (Exception e) {
log.error("召回测试失败: {}", e.getMessage(), e);
throw new RenException(ErrorCode.RAG_API_ERROR, "召回测试失败: " + e.getMessage());
String errorMessage = e.getMessage() != null ? e.getMessage() : "null";
if (e instanceof RenException) {
throw (RenException) e;
}
throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage);
} finally {
log.info("=== 召回测试操作结束 ===");
}
@@ -100,7 +100,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
converter.setObjectMapper(mapper);
return converter;
}
/**
* 国际化配置 - 根据请求头中的Accept-Language设置语言环境
*/
@@ -113,14 +113,14 @@ public class WebMvcConfig implements WebMvcConfigurer {
if (acceptLanguage == null || acceptLanguage.isEmpty()) {
return Locale.getDefault();
}
// 解析Accept-Language请求头中的首选语言
String[] languages = acceptLanguage.split(",");
if (languages.length > 0) {
// 提取第一个语言代码,去除可能的质量值(q=...)
String[] parts = languages[0].split(";" + "\\s*");
String primaryLanguage = parts[0].trim();
// 根据前端发送的语言代码直接创建Locale对象
if (primaryLanguage.equals("zh-CN")) {
return Locale.SIMPLIFIED_CHINESE;
@@ -128,15 +128,25 @@ public class WebMvcConfig implements WebMvcConfigurer {
return Locale.TRADITIONAL_CHINESE;
} else if (primaryLanguage.equals("en-US")) {
return Locale.US;
} else if (primaryLanguage.equals("de-DE")) {
return Locale.GERMANY;
} else if (primaryLanguage.equals("vi-VN")) {
return Locale.forLanguageTag("vi-VN");
} else if (primaryLanguage.startsWith("zh")) {
// 对于其他中文变体,默认使用简体中文
return Locale.SIMPLIFIED_CHINESE;
} else if (primaryLanguage.startsWith("en")) {
// 对于其他英文变体,默认使用美式英语
return Locale.US;
} else if (primaryLanguage.startsWith("de")) {
// 对于其他德语变体,默认使用德语
return Locale.GERMANY;
} else if (primaryLanguage.startsWith("vi")) {
// 对于其他越南语变体,默认使用越南语
return Locale.forLanguageTag("vi-VN");
}
}
// 如果没有匹配的语言,使用默认语言
return Locale.getDefault();
}
@@ -107,10 +107,10 @@ public class VoiceCloneController {
String name = params.get("name");
if (id == null || id.isEmpty()) {
return new Result<String>().error(ErrorCode.IDENTIFIER_NOT_NULL, "唯一标识不能为空");
return new Result<String>().error(ErrorCode.IDENTIFIER_NOT_NULL);
}
if (name == null) {
return new Result<String>().error(ErrorCode.NOT_NULL, "名称不能为空");
if (name == null || name.isEmpty()) {
return new Result<String>().error(ErrorCode.VOICE_CLONE_NAME_NOT_NULL);
}
// 检查权限
checkPermission(id);
@@ -119,7 +119,7 @@ public class VoiceCloneController {
redisUtils.delete(RedisKeys.getTimbreNameById(id));
return new Result<String>();
} catch (Exception e) {
return new Result<String>().error(ErrorCode.UPDATE_DATA_FAILED, "更新失败: " + e.getMessage());
return new Result<String>().error(ErrorCode.UPDATE_DATA_FAILED, e.getMessage());
}
}
@@ -131,7 +131,7 @@ public class VoiceCloneController {
checkPermission(id);
byte[] audioData = voiceCloneService.getVoiceData(id);
if (audioData == null) {
return new Result<String>().error(ErrorCode.RESOURCE_NOT_FOUND, "音频不存在");
return new Result<String>().error(ErrorCode.VOICE_CLONE_AUDIO_NOT_FOUND);
}
String uuid = UUID.randomUUID().toString();
redisUtils.set(RedisKeys.getVoiceCloneAudioIdKey(uuid), id);
@@ -100,7 +100,7 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl<VoiceCloneDao, VoiceC
wrapper.eq("model_id", dto.getModelId());
Long count = baseDao.selectCount(wrapper);
if (count > 0) {
throw new RenException(ErrorCode.VOICE_ID_ALREADY_EXISTS, "音色ID " + voiceId + " 已存在");
throw new RenException(ErrorCode.VOICE_ID_ALREADY_EXISTS);
}
}
@@ -0,0 +1,62 @@
UPDATE `ai_model_config` SET
`doc_link` = 'https://github.com/infiniflow/ragflow/blob/main/README_zh.md',
`remark` = '详细部署教程参考:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/ragflow-integration.md
部署成功,注冊登录后,点击右上角头像,获得RAGFlow的API KEY和API服务器地址。使用RAGFlow前请在Model Provider中添加模型和设置默认模型。' WHERE `id` = 'RAG_RAGFlow';
update `ai_model_config` set `model_name` = '外挂的大模型意图识别' where `id` = 'Intent_intent_llm';
update `ai_model_config` set `model_name` = '大模型自主函数调用' where `id` = 'Intent_function_call';
update `ai_model_config` set `model_name` = '百炼智能体应用' where `id` = 'LLM_AliAppLLM';
update `ai_model_provider` set `name` = '外挂的大模型意图识别' , `fields` = '[{"key":"llm","label":"引用的LLM模型","type":"string"}]' where id = 'SYSTEM_Intent_intent_llm';
update `ai_model_provider` set `name` = '大模型自主函数调用' where id = 'SYSTEM_Intent_function_call';
UPDATE ai_model_config set model_name = 'Linkerai(流式)' where id = 'TTS_LinkeraiTTS';
UPDATE ai_model_config set model_name = '火山引擎(流式)' where id = 'TTS_HuoshanDoubleStreamTTS';
UPDATE ai_model_config set model_name = '阿里百炼(流式)' where id = 'TTS_AliBLStreamTTS';
UPDATE ai_model_config set model_name = '科大讯飞(流式)' where id = 'TTS_XunFeiStreamTTS';
UPDATE ai_model_config set model_name = 'Minimax(流式)' where id = 'TTS_MinimaxStreamTTS';
UPDATE ai_model_config set model_name = '阿里云(流式)' where id = 'TTS_AliyunStreamTTS';
UPDATE ai_model_config set model_name = 'PaddleSpeech(流式)' where id = 'TTS_PaddleSpeechTTS';
UPDATE ai_model_config set model_name = 'IndexTTS(流式)' where id = 'TTS_IndexStreamTTS';
update ai_model_config SET sort = 2 where id = 'TTS_LinkeraiTTS';
update ai_model_config SET sort = 3 where id = 'TTS_HuoshanDoubleStreamTTS';
update ai_model_config SET sort = 4 where id = 'TTS_AliBLStreamTTS';
update ai_model_config SET sort = 5 where id = 'TTS_XunFeiStreamTTS';
update ai_model_config SET sort = 6 where id = 'TTS_MinimaxStreamTTS';
update ai_model_config SET sort = 7 where id = 'TTS_AliyunStreamTTS';
update ai_model_config SET sort = 8 where id = 'TTS_IndexStreamTTS';
update ai_model_config SET sort = 9 where id = 'TTS_PaddleSpeechTTS';
update ai_model_config SET sort = 10 where id = 'TTS_DoubaoTTS';
update ai_model_config SET sort = 11 where id = 'TTS_TencentTTS';
update ai_model_config SET sort = 12 where id = 'TTS_AliyunTTS';
update ai_model_config SET sort = 13 where id = 'TTS_OpenAITTS';
update ai_model_config SET sort = 14 where id = 'TTS_CosyVoiceSiliconflow';
update ai_model_config SET sort = 15 where id = 'TTS_CozeCnTTS';
update ai_model_config SET sort = 16 where id = 'TTS_FishSpeech';
update ai_model_config SET sort = 17 where id = 'TTS_GPT_SOVITS_V3';
update ai_model_config SET sort = 18 where id = 'TTS_GPT_SOVITS_V2';
update ai_model_config SET sort = 19 where id = 'TTS_TTS302AI';
update ai_model_config SET sort = 20 where id = 'TTS_GizwitsTTS';
update ai_model_config SET sort = 21 where id = 'TTS_VolcesAiGatewayTTS';
update ai_model_config SET sort = 22 where id = 'TTS_ACGNTTS';
update ai_model_config SET sort = 23 where id = 'TTS_CustomTTS';
UPDATE ai_model_config set model_name = '讯飞语音识别(流式)' where id = 'ASR_XunfeiStream';
UPDATE ai_model_config set model_name = 'Qwen3Flash语音识别' where id = 'ASR_Qwen3Flash';
update ai_model_config SET sort = 2 where id = 'ASR_FunASRServer';
update ai_model_config SET sort = 3 where id = 'ASR_XunfeiStream';
update ai_model_config SET sort = 4 where id = 'ASR_AliyunStreamASR';
update ai_model_config SET sort = 5 where id = 'ASR_DoubaoStreamASR';
update ai_model_config SET sort = 6 where id = 'ASR_TencentASR';
update ai_model_config SET sort = 7 where id = 'ASR_BaiduASR';
update ai_model_config SET sort = 8 where id = 'ASR_DoubaoASR';
update ai_model_config SET sort = 9 where id = 'ASR_AliyunASR';
update ai_model_config SET sort = 10 where id = 'ASR_SherpaASR';
update ai_model_config SET sort = 11 where id = 'ASR_OpenaiASR';
update ai_model_config SET sort = 12 where id = 'ASR_GroqASR';
update ai_model_config SET sort = 13 where id = 'ASR_VoskASR';
update ai_model_config SET sort = 14 where id = 'ASR_Qwen3Flash';
UPDATE ai_model_config SET config_json='{\"type\": \"openai\", \"base_url\": \"https://ark.cn-beijing.volces.com/api/v3\", \"model_name\": \"doubao-1-5-pro-32k-250115\", \"api_key\": \"你的api_key\"}' where id = 'LLM_DoubaoLLM' AND config_json LIKE '%你的api_key"%';
@@ -415,4 +415,11 @@ databaseChangeLog:
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202510251150.sql
path: classpath:db/changelog/202510251150.sql
- changeSet:
id: 202511131023
author: hrz
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202511131023.sql
@@ -160,11 +160,11 @@
10151=\u8BF7\u5148\u4E0A\u4F20\u97F3\u9891\u6587\u4EF6
10152=\u6A21\u578B\u914D\u7F6E\u672A\u627E\u5230
10153=\u6A21\u578B\u7C7B\u578B\u672A\u627E\u5230
10154=\u8BAD\u7EC3\u5931\u8D25
10154=\u8BAD\u7EC3\u5931\u8D25: {0}
10155=\u706B\u5C71\u5F15\u64CE\u7F3A\u5C11\u914D\u7F6E
10156=\u54CD\u5E94\u683C\u5F0F\u9519\u8BEF\uFF0C\u7F3A\u5C11BaseResp\u5B57\u6BB5
10157=\u8BF7\u6C42\u5931\u8D25
10158=\u8BF7\u6C42\u5931\u8D25\uFF0C\u72B6\u6001\u7801{0}
10158=\u514B\u9686\u97F3\u8272:
10159=\u97F3\u8272ID\u5DF2\u5B58\u5728
10160=\u706B\u5C71\u5F15\u64CE\u97F3\u8272ID\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5S_\u5F00\u5934
10161=Mac\u5730\u5740\u5DF2\u5B58\u5728
@@ -173,7 +173,20 @@
10164=RAG\u914D\u7F6E\u672A\u627E\u5230
10165=RAG\u914D\u7F6E\u7C7B\u578B\u9519\u8BEF
10166=\u9ED8\u8BA4RAG\u914D\u7F6E\u672A\u627E\u5230
10167=RAG\u63A5\u53E3\u9519\u8BEF\uFF0C{0}
10167=RAG\u8C03\u7528\u5931\u8D25\uFF0C{0}
10168=\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25
10169=\u60A8\u6CA1\u6709\u6743\u9650\u64CD\u4F5C\u8BE5\u8BB0\u5F55
10170=\u77E5\u8BC6\u5E93\u540D\u79F0\u91CD\u590D
10170=\u77E5\u8BC6\u5E93\u540D\u79F0\u91CD\u590D
10171=RAG\u914D\u7F6E\u4F53\u7684base_url\u4E0D\u80FD\u4E3A\u7A7A
10172=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A
10173=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A\uFF0C\u8BF7\u66F4\u6362\u4E3A\u5728\u53D6\u7684API\u53C2\u6570
10174=RAG\u914D\u7F6E\u4F53\u7684base_url\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934
10175=mac\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A
10176=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u4E0D\u80FD\u4E3A\u7A7A
10177=RAG\u914D\u7F6E\u4F53\u7684model_id\u4E0D\u80FD\u4E3A\u7A7A
10178=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u548Cmodel_id\u4E0D\u80FD\u4E3A\u7A7A
10179=\u6587\u4EF6\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A
10180=\u6587\u4EF6\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A
10181=\u97F3\u8272\u514B\u9686\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A
10182=\u97F3\u8272\u514B\u9686\u97F3\u9891\u4E0D\u5B58\u5728
10183=\u9ED8\u8BA4\u667A\u80FD\u4F53\u672A\u627E\u5230
@@ -0,0 +1,192 @@
#Deutsch
500=Server interne Ausnahme
401=Nicht autorisiert
403=Zugriff verweigert, keine Berechtigungen
10001={0} darf nicht leer sein
10002=Der Datensatz existiert bereits in der Datenbank
10003=Parameter abrufen fehlgeschlagen
10004=Die Kontonummer oder das Passwort ist falsch
10005=Konto wurde deaktiviert
10006=Eindeutige ID darf nicht leer sein
10007=Der Bestätigungscode ist falsch
10008=Zuerst Untermenü oder Schaltfläche löschen
10009=Das ursprüngliche Passwort ist falsch
10010=Das Konto oder Passwort ist falsch, Sie können es noch {0} Mal versuchen
10011=Die übergeordnete Abteilung hat eine falsche Wahl getroffen
10012=Oberes Menü kann nicht sich selbst sein
10013=Datenberechtigungsschnittstelle, die nur ein Map-Typ-Parameter sein kann
10014=Bitte löschen Sie zuerst die untergeordnete Abteilung
10015=Bitte löschen Sie zuerst den Benutzer unter der Abteilung
10016=Bereitstellung fehlgeschlagen, kein Prozess
10017=Das ModellDiagramm ist falsch, bitte überprüfen
10018=Export fehlgeschlagen, Modell-ID ist {0}
10019=Bitte laden Sie eine Datei hoch
10020=Token darf nicht leer sein
10021=Token ist ungültig, bitte melden Sie sich erneut an
10022=Das Konto wurde gesperrt
10023=Bitte laden Sie Dateien im Format zip, bar, bpmn, bpmn20.xml hoch
10024=Datei-Upload fehlgeschlagen {0}
10025=SMS-Sendung fehlgeschlagen {0}
10026=E-Mail-Vorlage existiert nicht
10027=Redis-Dienstausnahme
10028=Zeitgesteuerte Aufgabe fehlgeschlagen
10029=Darf keine illegalen Zeichen enthalten
10030=Das Passwort hat weniger als {0} Ziffern
10031=Das Passwort muss gleichzeitig aus Zahlen, Groß- und Kleinbuchstaben sowie Sonderzeichen bestehen
10032=Ausnahme beim Löschen dieser Daten
10033=Gerätebestätigungscode Fehler
10034=Parameterwert darf nicht leer sein
10035=Parametertyp darf nicht leer sein
10036=Nicht unterstützter Parametertyp
10037=Parameterwert muss eine gültige Zahl sein
10038=Parameterwert muss true oder false sein
10039=Parameterwert muss ein gültiges JSON-Array-Format sein
10040=Parameterwert muss ein gültiges JSON-Format sein
10041=Gerät nicht gefunden
10042={0}
10043=Löschen der Daten fehlgeschlagen
10044=Benutzer nicht angemeldet
10045=WebSocket-Verbindung fehlgeschlagen oder Zeitüberschreitung
10046=Stimmabdruck speichern fehlgeschlagen, bitte Administrator kontaktieren
10047=Tägliches SendeLimit erreicht
10048=Altes Passwort ist falsch
10049=Das eingestellte LLM ist nicht openai oder ollama
10050=Token-Generierung fehlgeschlagen
10051=Ressource nicht gefunden
10052=Standard-Agent nicht gefunden
10053=Agent nicht gefunden
10054=Stimmabdruck-Schnittstelle nicht konfiguriert, bitte konfigurieren Sie zuerst die Stimmabdruck-Schnittstellenadresse (server.voice_print) in der Parameterkonfiguration
10055=SMS-Sendung fehlgeschlagen
10056=SMS-Verbindung konnte nicht hergestellt werden
10057=Stimmabdruck für Agent konnte nicht erstellt werden
10058=Stimmabdruck für Agent konnte nicht aktualisiert werden
10059=Stimmabdruck für Agent konnte nicht gelöscht werden
10060=Sendung zu häufig, bitte versuchen Sie es nach {0} Sekunden erneut
10061=Aktivierungscode darf nicht leer sein
10062=Aktivierungscode Fehler
10063=Gerät bereits aktiviert
10064=Dieses Modell ist das Standardmodell, bitte setzen Sie zuerst ein anderes Modell als Standard
10065=Hinzufügen der Daten fehlgeschlagen
10066=Aktualisieren der Daten fehlgeschlagen
10067=Grafischer Bestätigungscode Fehler
10068=Mobilregistrierung nicht aktiviert, SMS-Bestätigungscode-Funktion kann nicht verwendet werden
10069=Benutzername ist keine Handynummer, bitte erneut eingeben
10070=Diese Handynummer wurde bereits registriert
10071=Die eingegebene Handynummer ist nicht registriert
10072=Normale Benutzerregistrierung derzeit nicht erlaubt
10073=Mobilregistrierung nicht aktiviert, Passwort-Wiederherstellungsfunktion kann nicht verwendet werden
10074=Das Format der eingegebenen Handynummer ist falsch
10075=Der eingegebene SMS-Bestätigungscode ist falsch
10076=Wörterbuchtyp existiert nicht
10077=Wörterbuchtypcode ist dupliziert
10078=Lesen der Ressource fehlgeschlagen
10079=LLM-Modell und Absichtserkennung, Parameterauswahl stimmt nicht überein
10080=Dieser Stimmabdruck gehört zu {0}, der bereits registriert ist, bitte wählen Sie eine andere Stimme
10081=Fehler beim Löschen des Stimmabdrucks aufgetreten
10082=Änderung nicht erlaubt, diese Stimme wurde bereits als Stimmabdruck registriert ({0})
10083=Fehler beim Ändern des Stimmabdrucks, bitte Administrator kontaktieren
10084=Stimmabdruck-Schnittstellenadresse Fehler, bitte gehen Sie zur Parameterverwaltung, um die Stimmabdruck-Schnittstellenadresse zu ändern
10085=Audiodaten gehören nicht zu diesem Agent
10086=Audiodaten sind leer, bitte überprüfen Sie hochgeladene Daten
10087=Stimmabdruck-Registrierung fehlgeschlagen, Anfrage nicht erfolgreich
10088=Stimmabdruck-Registrierung fehlgeschlagen, Anfrageverarbeitung fehlgeschlagen
10089=Stimmabdruck-Stornierung fehlgeschlagen, Anfrage nicht erfolgreich
10090=Stimmabdruck-Stornierung fehlgeschlagen, Anfrageverarbeitung fehlgeschlagen
10091=Modellanbieter existiert nicht
10092=Das konfigurierte LLM existiert nicht
10093=Diese Modellkonfiguration wird von Agent {0} referenziert und kann nicht gelöscht werden
10094=Dieses LLM-Modell wird von der Absichtserkennungskonfiguration referenziert und kann nicht gelöscht werden
10095=Ungültige Serveroperation
10096=Server WebSocket-Adresse nicht konfiguriert
10097=Ziel-WebSocket-Adresse existiert nicht
10098=WebSocket-Adressliste darf nicht leer sein
10099=WebSocket-Adresse darf nicht localhost oder 127.0.0.1 verwenden
10100=WebSocket-Adressformat ist falsch
10101=WebSocket-Verbindungstest fehlgeschlagen
10102=OTA-Adresse darf nicht leer sein
10103=OTA-Adresse darf nicht localhost oder 127.0.0.1 verwenden
10104=OTA-Adresse muss mit http oder https beginnen
10105=OTA-Adresse muss mit /ota/ enden
10106=OTA-Schnittstellenzugriff fehlgeschlagen
10107=OTA-Schnittstelle Rückgabeinhaltformat ist falsch
10108=OTA-Schnittstellenvalidierung fehlgeschlagen
10109=MCP-Adresse darf nicht leer sein
10110=MCP-Adresse darf nicht localhost oder 127.0.0.1 verwenden
10111=Keine gültige MCP-Adresse
10112=MCP-Schnittstellenzugriff fehlgeschlagen
10113=MCP-Schnittstelle Rückgabeinhaltformat ist falsch
10114=MCP-Schnittstellenvalidierung fehlgeschlagen
10115=Stimmabdruck-Schnittstellenadresse darf nicht leer sein
10116=Stimmabdruck-Schnittstellenadresse darf nicht localhost oder 127.0.0.1 verwenden
10117=Keine gültige Stimmabdruck-Schnittstellenadresse
10118=Stimmabdruck-Schnittstellenadresse muss mit http oder https beginnen
10119=Stimmabdruck-Schnittstellenzugriff fehlgeschlagen
10120=Stimmabdruck-Schnittstelle Rückgabeinhaltformat ist falsch
10121=Stimmabdruck-Schnittstellenvalidierung fehlgeschlagen
10122=MQTT-Geheimnis darf nicht leer sein
10123=Ihr MQTT-Geheimnis ist nicht sicher, es muss mindestens 8 Zeichen lang sein und muss sowohl Groß- als auch Kleinbuchstaben enthalten
10124=Ihr MQTT-Geheimnis ist nicht sicher, MQTT-Geheimnis muss sowohl Groß- als auch Kleinbuchstaben enthalten
10125=Ihr MQTT-Geheimnis enthält schwaches Passwort
10128=Wörterbuchlabel ist dupliziert
10129=SM2-Schlüssel nicht konfiguriert
10130=SM2-Entschlüsselung fehlgeschlagen
10131=modelType und provideCode dürfen nicht leer sein
10132=Keine Berechtigung, den Chat-Verlauf dieses Agents anzuzeigen
10133=Sitzungs-ID darf nicht leer sein
10134=Agent-ID darf nicht leer sein
10135=Chat-Verlauf-Download fehlgeschlagen
10136=Download-Link abgelaufen oder ungültig
10137=Download-Link ungültig
10138=Benutzer
10139=Agent
10140=Audio-Datei darf nicht leer sein
10141=Nur Audio-Dateien werden unterstützt
10142=Audio-Dateigröße darf 10MB nicht überschreiten
10143=Upload fehlgeschlagen
10144=Stimmenklon-Datensatz existiert nicht
10145=Stimmressourceninformationen dürfen nicht leer sein
10146=TTS-Plattformname darf nicht leer sein
10147=Stimmen-ID darf nicht leer sein
10148=Kontoinhaber darf nicht leer sein
10149=Zu löschende Stimmressourcen-ID darf nicht leer sein
10150=Sie haben keine Berechtigung, diesen Datensatz zu bearbeiten
10151=Bitte laden Sie zuerst eine Audio-Datei hoch
10152=Modellkonfiguration nicht gefunden
10153=Modelltyp nicht gefunden
10154=Training fehlgeschlagen: {0}
10155=Huoshan Engine-Konfiguration fehlt
10156=Antwortformat Fehler, BaseResp-Feld fehlt
10157=Anfrage fehlgeschlagen
10158=Stimme klonen:
10159=Stimmen-ID existiert bereits
10160=Huoshan Engine-Stimmen-ID-Formatfehler, muss mit S_ beginnen
10161=Mac-Adresse existiert bereits
10162=Modellanbieter existiert nicht
10163=Wissensbasis-Datensatz existiert nicht
10164=RAG-Konfiguration nicht gefunden
10165=RAG-Konfigurationstyp Fehler
10166=Standard-RAG-Konfiguration nicht gefunden
10167=RAG-API-Aufruf fehlgeschlagen: {0}
10168=Datei-Upload fehlgeschlagen
10169=Keine Berechtigung, diese Wissensbasis zu bearbeiten
10170=Wissensbasis-Name existiert bereits
10171=RAG-Konfiguration base_url darf nicht leer sein
10172=RAG-Konfiguration api_key darf nicht leer sein
10173=RAG-Konfiguration api_key darf keinen Platzhalter enthalten, bitte ersetzen Sie mit tatsächlichem API-Schlüssel
10174=RAG-Konfiguration base_url-Formatfehler, muss mit http oder https beginnen
10175=Mac-Adresse darf nicht leer sein
10176=RAG-Konfiguration dataset_id darf nicht leer sein
10177=RAG-Konfiguration model_id darf nicht leer sein
10178=RAG-Konfiguration dataset_id und model_id dürfen nicht leer sein
10179=Dateiname darf nicht leer sein
10180=Dateiinhalt darf nicht leer sein
10181=Stimmenklon-Name darf nicht leer sein
10182=Stimmenklon-Audio nicht gefunden
10183=Standard-Agent-Vorlage nicht gefunden
@@ -173,7 +173,20 @@
10164=RAG configuration not found
10165=RAG configuration type error
10166=Default RAG configuration not found
10167=RAG API interface error: {0}
10167=RAG API call failed: {0}
10168=Upload file failed
10169=No permission to operate this knowledge base
10170=Knowledge base name already exists
10170=Knowledge base name already exists
10171=RAG configuration base_url cannot be empty
10172=RAG configuration api_key cannot be empty
10173=RAG configuration api_key cannot contain placeholder, please replace with actual API key
10174=RAG configuration base_url format error, must start with http or https
10175=Mac address cannot be empty
10176=RAG configuration dataset_id cannot be empty
10177=RAG configuration model_id cannot be empty
10178=RAG configuration dataset_id and model_id cannot be empty
10179=File name cannot be empty
10180=File content cannot be empty
10181=Voice clone name cannot be empty
10182=Voice clone audio not found
10183=Default agent template not found
@@ -0,0 +1,192 @@
#Tiếng Việt
500=Ngoại lệ nội bộ máy chủ
401=Không được ủy quyền
403=Truy cập bị từ chối, không có quyền
10001={0} không thể để trống
10002=Bản ghi đã tồn tại trong cơ sở dữ liệu
10003=Không thể lấy tham số
10004=Số tài khoản hoặc mật khẩu không chính xác
10005=Tài khoản đã bị vô hiệu hóa
10006=ID duy nhất không thể để trống
10007=Mã xác minh không chính xác
10008=Trước tiên hãy xóa menu con hoặc nút
10009=Mật khẩu gốc không chính xác
10010=Tài khoản hoặc mật khẩu không chính xác, bạn có thể thử thêm {0} lần nữa
10011=Phòng ban cấp trên đã lựa chọn sai
10012=Menu trên không thể là chính nó
10013=Giao diện quyền dữ liệu, chỉ có thể là tham số kiểu Map
10014=Vui lòng xóa phòng ban cấp dưới trước
10015=Vui lòng xóa người dùng thuộc phòng ban trước
10016=Triển khai thất bại, không có quy trình
10017=Biểu đồ mô hình không chính xác, vui lòng kiểm tra
10018=Xuất thất bại, ID mô hình là {0}
10019=Vui lòng tải lên tệp
10020=Token không thể để trống
10021=Token không hợp lệ, vui lòng đăng nhập lại
10022=Tài khoản đã bị khóa
10023=Vui lòng tải lên tệp ở định dạng zip, bar, bpmn, bpmn20.xml
10024=Tải lên tệp {0} thất bại
10025=Gửi SMS {0} thất bại
10026=Mẫu email không tồn tại
10027=Ngoại lệ dịch vụ Redis
10028=Tác vụ hẹn giờ thất bại
10029=Không thể chứa ký tự không hợp lệ
10030=Mật khẩu ít hơn {0} chữ số
10031=Mật khẩu phải bao gồm số, chữ hoa, chữ thường và ký tự đặc biệt cùng một lúc
10032=Ngoại lệ khi xóa dữ liệu này
10033=Lỗi mã xác minh thiết bị
10034=Giá trị tham số không thể để trống
10035=Loại tham số không thể để trống
10036=Loại tham số không được hỗ trợ
10037=Giá trị tham số phải là số hợp lệ
10038=Giá trị tham số phải là true hoặc false
10039=Giá trị tham số phải là định dạng mảng JSON hợp lệ
10040=Giá trị tham số phải là định dạng JSON hợp lệ
10041=Không tìm thấy thiết bị
10042={0}
10043=Xóa dữ liệu thất bại
10044=Người dùng chưa đăng nhập
10045=Kết nối WebSocket thất bại hoặc hết thời gian chờ
10046=Không thể lưu dấu giọng nói, vui lòng liên hệ quản trị viên
10047=Đạt đến giới hạn gửi hàng ngày
10048=Mật khẩu cũ không chính xác
10049=LLM được đặt không phải là openai hoặc ollama
10050=Không thể tạo token
10051=Không tìm thấy tài nguyên
10052=Không tìm thấy agent mặc định
10053=Không tìm thấy agent
10054=Giao diện dấu giọng nói chưa được cấu hình, vui lòng cấu hình địa chỉ giao diện dấu giọng nói (server.voice_print) trong cấu hình tham số trước
10055=Gửi SMS thất bại
10056=Không thể thiết lập kết nối SMS
10057=Không thể tạo dấu giọng nói cho agent
10058=Không thể cập nhật dấu giọng nói cho agent
10059=Không thể xóa dấu giọng nói cho agent
10060=Gửi quá thường xuyên, vui lòng thử lại sau {0} giây
10061=Mã kích hoạt không thể để trống
10062=Lỗi mã kích hoạt
10063=Thiết bị đã được kích hoạt
10064=Mô hình này là mô hình mặc định, vui lòng đặt mô hình khác làm mặc định trước
10065=Thêm dữ liệu thất bại
10066=Cập nhật dữ liệu thất bại
10067=Lỗi mã xác minh đồ họa
10068=Đăng ký di động không được bật, không thể sử dụng chức năng mã xác minh SMS
10069=Tên người dùng không phải là số điện thoại di động, vui lòng nhập lại
10070=Số điện thoại di động này đã được đăng ký
10071=Số điện thoại di động đã nhập không được đăng ký
10072=Hiện không cho phép đăng ký người dùng thông thường
10073=Đăng ký di động không được bật, không thể sử dụng chức năng truy xuất mật khẩu
10074=Định dạng số điện thoại di động đã nhập không chính xác
10075=Mã xác minh SMS đã nhập không chính xác
10076=Loại từ điển không tồn tại
10077=Mã loại từ điển bị trùng lặp
10078=Đọc tài nguyên thất bại
10079=Mô hình LLM và nhận dạng ý định, lựa chọn tham số không khớp
10080=Dấu giọng nói này thuộc về {0} đã đăng ký, vui lòng chọn giọng nói khác
10081=Đã xảy ra lỗi khi xóa dấu giọng nói
10082=Không cho phép sửa đổi, giọng nói này đã được đăng ký làm dấu giọng nói ({0})
10083=Lỗi sửa đổi dấu giọng nói, vui lòng liên hệ quản trị viên
10084=Lỗi địa chỉ giao diện dấu giọng nói, vui lòng vào quản lý tham số để sửa đổi địa chỉ giao diện dấu giọng nói
10085=Dữ liệu âm thanh không thuộc về agent này
10086=Dữ liệu âm thanh trống, vui lòng kiểm tra dữ liệu đã tải lên
10087=Đăng ký dấu giọng nói thất bại, yêu cầu không thành công
10088=Đăng ký dấu giọng nói thất bại, xử lý yêu cầu thất bại
10089=Hủy dấu giọng nói thất bại, yêu cầu không thành công
10090=Hủy dấu giọng nói thất bại, xử lý yêu cầu thất bại
10091=Nhà cung cấp mô hình không tồn tại
10092=LLM được cấu hình không tồn tại
10093=Cấu hình mô hình này được tham chiếu bởi agent {0} và không thể xóa
10094=Mô hình LLM này được tham chiếu bởi cấu hình nhận dạng ý định và không thể xóa
10095=Thao tác máy chủ không hợp lệ
10096=Địa chỉ WebSocket máy chủ chưa được cấu hình
10097=Địa chỉ WebSocket mục tiêu không tồn tại
10098=Danh sách địa chỉ WebSocket không thể để trống
10099=Địa chỉ WebSocket không thể sử dụng localhost hoặc 127.0.0.1
10100=Định dạng địa chỉ WebSocket không chính xác
10101=Kiểm tra kết nối WebSocket thất bại
10102=Địa chỉ OTA không thể để trống
10103=Địa chỉ OTA không thể sử dụng localhost hoặc 127.0.0.1
10104=Địa chỉ OTA phải bắt đầu bằng http hoặc https
10105=Địa chỉ OTA phải kết thúc bằng /ota/
10106=Truy cập giao diện OTA thất bại
10107=Định dạng nội dung trả về giao diện OTA không chính xác
10108=Xác thực giao diện OTA thất bại
10109=Địa chỉ MCP không thể để trống
10110=Địa chỉ MCP không thể sử dụng localhost hoặc 127.0.0.1
10111=Không phải địa chỉ MCP hợp lệ
10112=Truy cập giao diện MCP thất bại
10113=Định dạng nội dung trả về giao diện MCP không chính xác
10114=Xác thực giao diện MCP thất bại
10115=Địa chỉ giao diện dấu giọng nói không thể để trống
10116=Địa chỉ giao diện dấu giọng nói không thể sử dụng localhost hoặc 127.0.0.1
10117=Không phải địa chỉ giao diện dấu giọng nói hợp lệ
10118=Địa chỉ giao diện dấu giọng nói phải bắt đầu bằng http hoặc https
10119=Truy cập giao diện dấu giọng nói thất bại
10120=Định dạng nội dung trả về giao diện dấu giọng nói không chính xác
10121=Xác thực giao diện dấu giọng nói thất bại
10122=Bí mật MQTT không thể để trống
10123=Bí mật MQTT của bạn không an toàn, cần ít nhất 8 ký tự và phải chứa cả chữ hoa và chữ thường
10124=Bí mật MQTT của bạn không an toàn, bí mật MQTT phải chứa cả chữ hoa và chữ thường
10125=Bí mật MQTT của bạn chứa mật khẩu yếu
10128=Nhãn từ điển bị trùng lặp
10129=Khóa SM2 chưa được cấu hình
10130=Giải mã SM2 thất bại
10131=modelType và provideCode không thể để trống
10132=Không có quyền xem lịch sử trò chuyện của agent này
10133=ID phiên không thể để trống
10134=ID agent không thể để trống
10135=Tải xuống lịch sử trò chuyện thất bại
10136=Liên kết tải xuống đã hết hạn hoặc không hợp lệ
10137=Liên kết tải xuống không hợp lệ
10138=Người dùng
10139=Agent
10140=Tệp âm thanh không thể để trống
10141=Chỉ hỗ trợ tệp âm thanh
10142=Kích thước tệp âm thanh không thể vượt quá 10MB
10143=Tải lên thất bại
10144=Bản ghi nhân bản giọng nói không tồn tại
10145=Thông tin tài nguyên giọng nói không thể để trống
10146=Tên nền tảng TTS không thể để trống
10147=ID giọng nói không thể để trống
10148=Tài khoản chủ sở hữu không thể để trống
10149=ID tài nguyên giọng nói cần xóa không thể để trống
10150=Bạn không có quyền thao tác bản ghi này
10151=Vui lòng tải lên tệp âm thanh trước
10152=Không tìm thấy cấu hình mô hình
10153=Không tìm thấy loại mô hình
10154=Đào tạo thất bại: {0}
10155=Thiếu cấu hình Huoshan Engine
10156=Lỗi định dạng phản hồi, thiếu trường BaseResp
10157=Yêu cầu thất bại
10158=Nhân bản giọng nói:
10159=ID giọng nói đã tồn tại
10160=Lỗi định dạng ID giọng nói Huoshan Engine, phải bắt đầu bằng S_
10161=Địa chỉ Mac đã tồn tại
10162=Nhà cung cấp mô hình không tồn tại
10163=Bản ghi cơ sở kiến thức không tồn tại
10164=Không tìm thấy cấu hình RAG
10165=Lỗi loại cấu hình RAG
10166=Không tìm thấy cấu hình RAG mặc định
10167=Gọi API RAG thất bại: {0}
10168=Tải lên tệp thất bại
10169=Không có quyền thao tác cơ sở kiến thức này
10170=Tên cơ sở kiến thức đã tồn tại
10171=Cấu hình RAG base_url không thể để trống
10172=Cấu hình RAG api_key không thể để trống
10173=Cấu hình RAG api_key không thể chứa trình giữ chỗ, vui lòng thay thế bằng khóa API thực tế
10174=Lỗi định dạng cấu hình RAG base_url, phải bắt đầu bằng http hoặc https
10175=Địa chỉ Mac không thể để trống
10176=Cấu hình RAG dataset_id không thể để trống
10177=Cấu hình RAG model_id không thể để trống
10178=Cấu hình RAG dataset_id và model_id không thể để trống
10179=Tên tệp không thể để trống
10180=Nội dung tệp không thể để trống
10181=Tên nhân bản giọng nói không thể để trống
10182=Không tìm thấy âm thanh nhân bản giọng nói
10183=Không tìm thấy mẫu agent mặc định
@@ -160,11 +160,11 @@
10151=\u8BF7\u5148\u4E0A\u4F20\u97F3\u9891\u6587\u4EF6
10152=\u6A21\u578B\u914D\u7F6E\u672A\u627E\u5230
10153=\u6A21\u578B\u7C7B\u578B\u672A\u627E\u5230
10154=\u8BAD\u7EC3\u5931\u8D25
10154=\u8BAD\u7EC3\u5931\u8D25: {0}
10155=\u706B\u5C71\u5F15\u64CE\u7F3A\u5C11\u914D\u7F6E
10156=\u54CD\u5E94\u683C\u5F0F\u9519\u8BEF\uFF0C\u7F3A\u5C11BaseResp\u5B57\u6BB5
10157=\u8BF7\u6C42\u5931\u8D25
10158=\u514B\u9686\u8272\u97F3:
10158=\u514B\u9686\u97F3\u8272:
10159=\u97F3\u8272ID\u5DF2\u5B58\u5728
10160=\u706B\u5C71\u5F15\u64CE\u97F3\u8272ID\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5S_\u5F00\u5934
10161=Mac\u5730\u5740\u5DF2\u5B58\u5728
@@ -173,7 +173,20 @@
10164=RAG\u914D\u7F6E\u672A\u627E\u5230
10165=RAG\u914D\u7F6E\u7C7B\u578B\u9519\u8BEF
10166=\u9ED8\u8BA4RAG\u914D\u7F6E\u672A\u627E\u5230
10167=RAG\u63A5\u53E3\u9519\u8BEF\uFF0C{0}
10167=RAG\u8C03\u7528\u5931\u8D25\uFF0C{0}
10168=\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25
10169=\u60A8\u6CA1\u6709\u6743\u9650\u64CD\u4F5C\u8BE5\u8BB0\u5F55
10170=\u77E5\u8BC6\u5E93\u540D\u79F0\u91CD\u590D
10170=\u77E5\u8BC6\u5E93\u540D\u79F0\u91CD\u590D
10171=RAG\u914D\u7F6E\u4F53\u7684base_url\u4E0D\u80FD\u4E3A\u7A7A
10172=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A
10173=RAG\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A\uFF0C\u8BF7\u66F4\u6362\u4E3A\u5728\u53D6\u7684API\u53C2\u6570
10174=RAG\u914D\u7F6E\u4F53\u7684base_url\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934
10175=mac\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A
10176=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u4E0D\u80FD\u4E3A\u7A7A
10177=RAG\u914D\u7F6E\u4F53\u7684model_id\u4E0D\u80FD\u4E3A\u7A7A
10178=RAG\u914D\u7F6E\u4F53\u7684dataset_id\u548Cmodel_id\u4E0D\u80FD\u4E3A\u7A7A
10179=\u6587\u4EF6\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A
10180=\u6587\u4EF6\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A
10181=\u97F3\u8272\u514B\u9686\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A
10182=\u97F3\u8272\u514B\u9686\u97F3\u9891\u4E0D\u5B58\u5728
10183=\u9ED8\u8BA4\u667A\u80FD\u4F53\u672A\u627E\u5230
@@ -164,7 +164,7 @@
10155=\u706B\u5C71\u5F15\u64CE\u7F3A\u5C11appid\u6216access_token
10156=\u97FF\u61C9\u683C\u5F0F\u932F\u8AA4\uFF0C\u7F3A\u5C11BaseResp\u5B57\u6BB5
10157=\u8ACB\u6C42\u5931\u6557
10158=\u514B\u9686\u8A9E\u97F3:
10158=\u514b\u9686\u97f3\u8272:
10159=\u97F3\u8272ID\u5DF2\u5B58\u5728
10160=\u706B\u5C71\u5F15\u64CE\u97F3\u8272ID\u683C\u5F0F\u932F\u8AA4\uFF0C\u5FC5\u9808\u4EE5S_\u958B\u982D
10161=Mac\u5730\u5740\u5DF2\u5B58\u5728
@@ -173,7 +173,20 @@
10164=RAG\u914D\u7F6E\u672A\u627E\u5230
10165=RAG\u914D\u7F6E\u985E\u578B\u932F\u8AA4
10166=\u9810\u8A2DRAG\u914D\u7F6E\u672A\u627E\u5230
10167=RAG\u63A5\u53E3\u932F\u8AA4\uFF0C{0}
10167=\u0052\u0041\u0047\u8abf\u7528\u5931\u6557\uFF0C{0}
10168=\u4E0A\u50B3\u6587\u4EF6\u5931\u6557
10169=\u60A8\u6C92\u6709\u6B0A\u9650\u64CD\u4F5C\u8A72\u8A18\u9304
10170=\u77E5\u8B58\u5EAB\u540D\u7A31\u91CD\u8907
10171=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684base_url\u4E0D\u80FD\u4E3A\u7A7A
10172=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A
10173=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684api_key\u4E0D\u80FD\u4E3A\u7A7A\uFF0C\u8BF7\u66F4\u6362\u4E3A\u5728\u53D6\u7684API\u53C2\u6570
10174=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684base_url\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5http\u6216https\u5F00\u5934
10175=mac\u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A
10176=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684dataset_id\u4E0D\u80FD\u4E3A\u7A7A
10177=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684model_id\u4E0D\u80FD\u4E3A\u7A7A
10178=\u0052\u0041\u0047\u914D\u7F6E\u4F53\u7684dataset_id\u548Cmodel_id\u4E0D\u80FD\u4E3A\u7A7A
10179=\u6587\u4ef6\u540d\u7a31\u4e0d\u80fd\u70ba\u7a7a
10180=\u6587\u4ef6\u5185\u5bb9\u4e0d\u80fd\u70ba\u7a7a
10181=\u97f3\u8272\u514b\u9686\u540d\u7a31\u4e0d\u80fd\u70ba\u7a7a
10182=\u97f3\u8272\u514b\u9686\u97f3\u983b\u4e0d\u5b58\u5728
10183=\u9ed8\u8ba4\u667a\u80fd\u4f53\u672a\u627e\u5230
@@ -0,0 +1,34 @@
#Deutsch
id.require=ID darf nicht leer sein
id.null=ID muss leer sein
sort.number=Der Sortierwert darf nicht kleiner als 0 sein
page.number=Der Seitenwert darf nicht kleiner als 0 sein
limit.number=Der Limit-Wert darf nicht kleiner als 0 sein
sysdict.type.require=Der Wörterbuchtyp darf nicht leer sein
sysdict.name.require=Der Wörterbuchname darf nicht leer sein
sysdict.label.require=Wörterbuch-Label darf nicht leer sein
sysparams.paramcode.require=Parameter-Code darf nicht leer sein
sysparams.paramvalue.require=Parameter-Werte dürfen nicht leer sein
sysparams.valuetype.require=Werttyp darf nicht leer sein
sysparams.valuetype.pattern=Werttyp muss string, number, boolean oder array sein
sysuser.username.require=Der Benutzername darf nicht leer sein
sysuser.password.require=Das Passwort darf nicht leer sein
sysuser.realname.require=Der echte Name darf nicht leer sein
sysuser.gender.range=Geschlecht liegt im Bereich von 0 bis 2
sysuser.email.error=Falsches E-Mail-Format
sysuser.deptId.require=Abteilungen dürfen nicht leer sein
sysuser.status.range=Status liegt im Bereich von 0 bis 1
sysuser.captcha.require=Das Captcha darf nicht leer sein
sysuser.uuid.require=Der eindeutige Identifikator darf nicht leer sein
timbre.languages.require=Die Sprache des Klangs darf nicht leer sein
timbre.name.require=Der Name des Klangs darf nicht leer sein
timbre.ttsModelId.require=Die TTS-Modell-ID des Klangs darf nicht leer sein
timbre.ttsVoice.require=Die TTS-Stimme des Klangs darf nicht leer sein
ota.device.not.found=Gerät nicht gefunden
ota.device.need.bind={0}
@@ -0,0 +1,34 @@
# Tiếng Việt
id.require=ID không được để trống
id.null=ID phải để trống
sort.number=Giá trị sắp xếp không thể nhỏ hơn 0
page.number=Giá trị trang không thể nhỏ hơn 0
limit.number=Giá trị giới hạn không thể nhỏ hơn 0
sysdict.type.require=Loại từ điển không được để trống
sysdict.name.require=Tên từ điển không được để trống
sysdict.label.require=Thẻ từ điển không được để trống
sysparams.paramcode.require=Mã tham số không được để trống
sysparams.paramvalue.require=Giá trị tham số không được để trống
sysparams.valuetype.require=Loại giá trị không được để trống
sysparams.valuetype.pattern=Loại giá trị phải là chuỗi, số, boolean hoặc mảng
sysuser.username.require=Tên người dùng không được để trống
sysuser.password.require=Mật khẩu không được để trống
sysuser.realname.require=Tên thật không được để trống
sysuser.gender.range=Giới tính phải từ 0 đến 2
sysuser.email.error=Định dạng email không chính xác
sysuser.deptId.require=Phòng ban không được để trống
sysuser.status.range=Trạng thái phải từ 0 đến 1
sysuser.captcha.require=Mã xác thực không được để trống
sysuser.uuid.require=Định danh duy nhất không được để trống
timbre.languages.require=Ngôn ngữ của âm sắc không được để trống
timbre.name.require=Tên âm sắc không được để trống
timbre.ttsModelId.require=ID mô hình TTS của âm sắc không được để trống
timbre.ttsVoice.require=Giọng TTS của âm sắc không được để trống
ota.device.not.found=Không tìm thấy thiết bị
ota.device.need.bind={0}
@@ -3,8 +3,8 @@ id.require=ID\u4E0D\u80FD\u4E3A\u7A7A
id.null=ID\u5FC5\u987B\u4E3A\u7A7A
sort.number=\u6392\u5E8F\u503C\u4E0D\u80FD\u5C0F\u4E8E0
page.number=\u9801\u6578\u4E0D\u80FD\u5C0F\u4E8E0
limit.number=\u5217\u6578\u4E0D\u80FD\u5C0F\u4E8E0
page.number=\u9875\u6570\u4E0D\u80FD\u5C0F\u4E8E0
limit.number=\u5217\u6570\u4E0D\u80FD\u5C0F\u4E8E0
sysdict.type.require=\u5B57\u5178\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A
sysdict.name.require=\u5B57\u5178\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A
@@ -25,10 +25,10 @@ sysuser.status.range=\u72B6\u6001\u53D6\u503C\u8303\u56F40~1
sysuser.captcha.require=\u9A8C\u8BC1\u7801\u4E0D\u80FD\u4E3A\u7A7A
sysuser.uuid.require=\u552F\u4E00\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A
timbre.languages.require=\u97F3\u8272\u7684\u8A9E\u8A00\u4E0D\u53EF\u4EE5\u70BA\u7A7A
timbre.name.require=\u97F3\u8272\u7684\u540D\u7A31\u4E0D\u53EF\u4EE5\u70BA\u7A7A
timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u9375\u4E0D\u53EF\u4EE5\u70BA\u7A7A
timbre.ttsVoice.require=\u97F3\u8272\u7684\u7DE8\u78BC\u4E0D\u53EF\u4EE5\u70BA\u7A7A
timbre.languages.require=\u97F3\u8272\u7684\u8BED\u8A00\u4E0D\u80FD\u4E3A\u7A7A
timbre.name.require=\u97F3\u8272\u7684\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A
timbre.ttsModelId.require=\u97F3\u8272\u7684tts\u4E3B\u952E\u4E0D\u80FD\u4E3A\u7A7A
timbre.ttsVoice.require=\u97F3\u8272\u7684\u7F16\u7801\u4E0D\u80FD\u4E3A\u7A7A
ota.device.not.found=\u8A2D\u5099\u672A\u627E\u5230
ota.device.not.found=\u8BBE\u5907\u672A\u627E\u5230
ota.device.need.bind={0}
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xiaozhi.modules.knowledge.dao.KnowledgeBaseDao">
<resultMap id="BaseResultMap" type="xiaozhi.modules.knowledge.entity.KnowledgeBaseEntity">
<id property="id" column="id" jdbcType="VARCHAR"/>
<result property="datasetId" column="dataset_id" jdbcType="VARCHAR"/>
<result property="ragModelId" column="rag_model_id" jdbcType="VARCHAR"/>
<result property="name" column="name" jdbcType="VARCHAR"/>
<result property="description" column="description" jdbcType="VARCHAR"/>
<result property="status" column="status" jdbcType="TINYINT"/>
<result property="creator" column="creator" jdbcType="BIGINT"/>
<result property="createdAt" column="created_at" jdbcType="TIMESTAMP"/>
<result property="updater" column="updater" jdbcType="BIGINT"/>
<result property="updatedAt" column="updated_at" jdbcType="TIMESTAMP"/>
</resultMap>
<!-- 根据知识库ID删除相关的插件映射记录 -->
<delete id="deletePluginMappingByKnowledgeBaseId">
DELETE FROM ai_agent_plugin_mapping
WHERE plugin_id = #{knowledgeBaseId}
</delete>
</mapper>
+440
View File
@@ -0,0 +1,440 @@
// Deutsch Sprachpaket
export default {
// TabBar
'tabBar.home': 'Startseite',
'tabBar.deviceConfig': 'Netzwerkkonfig',
'tabBar.settings': 'System',
// Einstellungsseitentitel
'settings.title': 'Einstellungen',
// Anmeldeseite
'login.pageTitle': 'Anmelden',
'login.navigationTitle': 'Anmelden',
'login.fetchConfigError': 'Konfiguration konnte nicht abgerufen werden:',
'login.selectLanguage': 'Sprache auswählen',
'login.selectLanguageTip': 'Vi',
'login.welcomeBack': 'Willkommen zurück',
'login.pleaseLogin': 'Bitte melden Sie sich an',
'login.enterUsername': 'Bitte Benutzernamen eingeben',
'login.enterPassword': 'Bitte Passwort eingeben',
'login.enterCaptcha': 'Bitte Bestätigungscode eingeben',
'login.loginButton': 'Anmelden',
'login.loggingIn': 'Wird angemeldet...',
'login.noAccount': 'Registrieren',
'login.enterPhone': 'Bitte Handynummer eingeben',
'login.selectCountry': 'Land/Region auswählen',
'login.confirm': 'Bestätigen',
'login.serverSetting': 'Server-Einstellungen',
'login.requiredUsername': 'Benutzername darf nicht leer sein',
'login.requiredPassword': 'Passwort darf nicht leer sein',
'login.requiredCaptcha': 'Bestätigungscode darf nicht leer sein',
'login.requiredMobile': 'Bitte gültige Handynummer eingeben',
'login.captchaError': 'Grafischer Bestätigungscode Fehler',
'login.forgotPassword': 'Passwort vergessen',
// Registrierungsseite
'register.pageTitle': 'Registrieren',
'register.createAccount': 'Konto erstellen',
'register.enterUsername': 'Bitte Benutzernamen eingeben',
'register.enterPassword': 'Bitte Passwort eingeben',
'register.confirmPassword': 'Bitte Passwort bestätigen',
'register.enterPhone': 'Bitte Handynummer eingeben',
'register.enterCode': 'Bitte Bestätigungscode eingeben',
'register.getCode': 'Code erhalten',
'register.agreeTerms': 'Ich habe gelesen und stimme zu',
'register.terms': 'Nutzungsbedingungen',
'register.privacy': 'Datenschutzrichtlinie',
'register.registerButton': 'Registrieren',
'register.registering': 'Wird registriert...',
'register.haveAccount': 'Bereits ein Konto?',
'register.loginNow': 'Jetzt anmelden',
'register.selectCountry': 'Land/Region auswählen',
'register.confirm': 'Bestätigen',
'register.captchaSendSuccess': 'Bestätigungscode erfolgreich gesendet',
// Startseite
'home.pageTitle': 'Startseite',
'home.createAgent': 'Agent erstellen',
'home.agentName': 'Agent',
'home.modelInfo': 'Modell-Info',
'home.lastActive': 'Zuletzt aktiv',
'home.greeting': 'Hallo Jarvis',
'home.subtitle': 'Lassen Sie uns',
'home.wonderfulDay': 'einen wunderbaren Tag haben!',
'home.emptyState': 'Keine Agenten verfügbar',
'home.deviceManagement': 'Geräteverwaltung',
'home.lastConversation': 'Letzte Konversation:',
'home.delete': 'Löschen',
'home.createFirstAgent': 'Klicken Sie auf die + Schaltfläche unten rechts, um Ihren ersten Agenten zu erstellen',
'home.dialogTitle': 'Agent erstellen',
'home.inputPlaceholder': 'z.B. Kundenservice-Assistent, Sprachassistent, Wissens-F&A',
'home.createError': 'Bitte Agenten-Namen eingeben',
'home.createNow': 'Jetzt erstellen',
'home.justNow': 'Gerade eben',
'home.minutesAgo': 'Minuten her',
'home.hoursAgo': 'Stunden her',
'home.daysAgo': 'Tage her',
// Agentenseite
'agent.pageTitle': 'Agent',
'agent.roleConfig': 'Rollenkonfiguration',
'agent.deviceManagement': 'Geräteverwaltung',
'agent.chatHistory': 'Chat-Verlauf',
'agent.voiceprintManagement': 'Stimmabdruckverwaltung',
'agent.editTitle': 'Agent bearbeiten',
'agent.toolsTitle': 'Funktionen bearbeiten',
'agent.voiceActivityDetection': 'Sprachaktivitätserkennung',
'agent.speechRecognition': 'Spracherkennung',
'agent.largeLanguageModel': 'Großes Sprachmodell',
'agent.save': 'Speichern',
'agent.cancel': 'Abbrechen',
// Agenten-Bearbeitungsseite
'agent.basicInfo': 'Grundinformationen',
'agent.agentName': 'Agentenname',
'agent.inputAgentName': 'Bitte Agenten-Namen eingeben',
'agent.roleMode': 'Rollenmodus',
'agent.roleDescription': 'Rollenbeschreibung',
'agent.inputRoleDescription': 'Bitte Rollenbeschreibung eingeben',
'agent.modelConfig': 'Modellkonfiguration',
'agent.vad': 'Sprachaktivitätserkennung',
'agent.asr': 'Spracherkennung',
'agent.llm': 'Großes Sprachmodell',
'agent.vllm': 'Vision-Sprachmodell',
'agent.intent': 'Absichtserkennung',
'agent.memory': 'Speicher',
'agent.voiceSettings': 'Stimmeinstellungen',
'agent.tts': 'Text-zu-Sprache',
'agent.voiceprint': 'Agenten-Stimme',
'agent.plugins': 'Plugins',
'agent.editFunctions': 'Funktionen bearbeiten',
'agent.historyMemory': 'Verlaufsspeicher',
'agent.memoryContent': 'Speicherinhalt',
'agent.saving': 'Wird gespeichert...',
'agent.saveSuccess': 'Erfolgreich gespeichert',
'agent.saveFail': 'Speichern fehlgeschlagen',
'agent.loadFail': 'Laden fehlgeschlagen',
'agent.pleaseInputAgentName': 'Bitte Agenten-Namen eingeben',
'agent.pleaseInputRoleDescription': 'Bitte Rollenbeschreibung eingeben',
'agent.pleaseSelect': 'Bitte auswählen',
// Chat-Verlauf Seite
'chatHistory.getChatSessions': 'Chat-Sitzungsliste abrufen',
'chatHistory.noSelectedAgent': 'Kein Agent ausgewählt',
'chatHistory.getChatSessionsFailed': 'Chat-Sitzungsliste konnte nicht abgerufen werden:',
'chatHistory.unknownTime': 'Unbekannte Zeit',
'chatHistory.justNow': 'Gerade eben',
'chatHistory.minutesAgo': 'Vor {minutes} Minuten',
'chatHistory.hoursAgo': 'Vor {hours} Stunden',
'chatHistory.daysAgo': 'Vor {days} Tagen',
'chatHistory.conversationRecord': 'Konversationsaufzeichnung',
'chatHistory.totalChats': 'Insgesamt {count} Chats',
'chatHistory.loading': 'Lädt...',
'chatHistory.noMoreData': 'Keine weiteren Daten',
'chatHistory.noChatRecords': 'Keine Chat-Aufzeichnungen',
'chatHistory.chatRecordsDescription': 'Konversationsaufzeichnungen mit Agenten werden hier angezeigt',
// Chat-Verlauf Detailseite
'chatHistory.pageTitle': 'Chat-Details',
'chatHistory.assistantName': 'Intelligenter Assistent',
'chatHistory.userName': 'Benutzer',
'chatHistory.aiAssistantName': 'KI-Assistent',
'chatHistory.loadFailed': 'Chat-Verlauf konnte nicht geladen werden',
'chatHistory.parameterError': 'Seitenparameter Fehler',
'chatHistory.invalidAudioId': 'Ungültige Audio-ID',
'chatHistory.audioPlayFailed': 'Audio-Wiedergabe fehlgeschlagen',
'chatHistory.playAudioFailed': 'Audio konnte nicht abgespielt werden',
// Geräteverwaltungsseite
'device.pageTitle': 'Geräteverwaltung',
'device.noDevices': 'Keine Geräte verfügbar',
'device.macAddress': 'MAC-Adresse',
'device.firmwareVersion': 'Firmware-Version',
'device.lastConnected': 'Letzte Konversation',
'device.otaUpdate': 'OTA-Update',
'device.unbind': 'Entbinden',
'device.confirmUnbind': 'Bestätigen',
'device.bindDevice': 'Neues Gerät binden',
'device.deviceType': 'Gerätetyp',
'device.loading': 'Lädt...',
'device.neverConnected': 'Nie verbunden',
'device.justNow': 'Gerade eben',
'device.minutesAgo': 'Vor {minutes} Minuten',
'device.hoursAgo': 'Vor {hours} Stunden',
'device.daysAgo': 'Vor {days} Tagen',
'device.otaAutoUpdateEnabled': 'OTA Auto-Update aktiviert',
'device.otaAutoUpdateDisabled': 'OTA Auto-Update deaktiviert',
'device.operationFailed': 'Operation fehlgeschlagen, bitte erneut versuchen',
'device.deviceUnbound': 'Gerät entbunden',
'device.unbindFailed': 'Entbinden fehlgeschlagen, bitte erneut versuchen',
'device.unbindDevice': 'Gerät entbinden',
'device.confirmUnbindDevice': 'Sind Sie sicher, dass Sie Gerät "{macAddress}" entbinden möchten?',
'device.cancel': 'Abbrechen',
'device.noDevice': 'Kein Gerät',
'device.pleaseSelectAgent': 'Bitte wählen Sie zuerst einen Agenten aus',
'device.deviceBindSuccess': 'Gerät erfolgreich gebunden!',
'device.bindFailed': 'Binden fehlgeschlagen, bitte prüfen Sie ob der Bestätigungscode korrekt ist',
'device.enterDeviceCode': 'Bitte Geräte-Bestätigungscode eingeben',
'device.bindNow': 'Jetzt binden',
'device.lastConnection': 'Letzte Verbindung',
'device.clickToBindFirstDevice': 'Klicken Sie auf die + Schaltfläche unten rechts, um Ihr erstes Gerät zu binden',
// Allgemein
'common.success': 'Erfolg',
'common.fail': 'Fehlgeschlagen',
'common.loading': 'Lädt...',
'common.confirm': 'Bestätigen',
'common.cancel': 'Abbrechen',
'common.delete': 'Löschen',
'common.edit': 'Bearbeiten',
'common.add': 'Hinzufügen',
'common.pleaseSelect': 'Bitte auswählen',
'common.unknownError': 'Unbekannter Fehler',
'common.networkError': 'Netzwerkfehler',
// Passwort-Wiederherstellungsseite
'retrievePassword.title': 'Passwort zurücksetzen',
'retrievePassword.subtitle': 'Stellen Sie Ihr Kontopasswort über Handynummer wieder her',
'retrievePassword.mobileRequired': 'Bitte Handynummer eingeben',
'retrievePassword.inputCorrectMobile': 'Bitte gültige Handynummer eingeben',
'retrievePassword.captchaRequired': 'Bitte grafischen Bestätigungscode eingeben',
'retrievePassword.mobileCaptchaRequired': 'Bitte SMS-Bestätigungscode eingeben',
'retrievePassword.newPasswordRequired': 'Bitte neues Passwort eingeben',
'retrievePassword.confirmNewPasswordRequired': 'Bitte neues Passwort bestätigen',
'retrievePassword.passwordsNotMatch': 'Passwörter stimmen nicht überein',
'retrievePassword.mobilePlaceholder': 'Bitte Handynummer eingeben',
'retrievePassword.captchaPlaceholder': 'Bitte grafischen Bestätigungscode eingeben',
'retrievePassword.mobileCaptchaPlaceholder': 'Bitte SMS-Bestätigungscode eingeben',
'retrievePassword.newPasswordPlaceholder': 'Bitte neues Passwort eingeben',
'retrievePassword.confirmNewPasswordPlaceholder': 'Bitte neues Passwort bestätigen',
'retrievePassword.getMobileCaptcha': 'Code erhalten',
'retrievePassword.captchaSendSuccess': 'Bestätigungscode erfolgreich gesendet',
'retrievePassword.passwordUpdateSuccess': 'Passwort erfolgreich zurückgesetzt',
'retrievePassword.resetButton': 'Passwort zurücksetzen',
'retrievePassword.goToLogin': 'Zurück zur Anmeldung',
// SM2-Verschlüsselungsbezogene Fehlermeldungen
'sm2.publicKeyNotConfigured': 'SM2 öffentlicher Schlüssel nicht konfiguriert, bitte Administrator kontaktieren',
'sm2.encryptionFailed': 'Passwortverschlüsselung fehlgeschlagen',
'sm2.keyGenerationFailed': 'Schlüsselpaar-Generierung fehlgeschlagen',
'sm2.invalidPublicKey': 'Ungültiges öffentliches Schlüsselformat',
'sm2.encryptionError': 'Fehler bei der Verschlüsselung aufgetreten',
'sm2.publicKeyRetry': 'Öffentlichen Schlüssel erneut abrufen...',
'sm2.publicKeyRetryFailed': 'Wiederholter Abruf des öffentlichen Schlüssels fehlgeschlagen',
// Stimmabdruckseite
'voiceprint.noSelectedAgent': 'Kein Agent ausgewählt',
'voiceprint.pleaseSelectAgent': 'Bitte wählen Sie zuerst einen Agenten aus',
'voiceprint.fetchHistoryFailed': 'Chat-Verlauf konnte nicht abgerufen werden',
'voiceprint.clickToSelectVector': 'Klicken zum Auswählen des Stimmabdruck-Vektors',
'voiceprint.pleaseInputName': 'Bitte Namen eingeben',
'voiceprint.pleaseSelectVector': 'Bitte Stimmabdruck-Vektor auswählen',
'voiceprint.addSuccess': 'Erfolgreich hinzugefügt',
'voiceprint.addFailed': 'Hinzufügen des Sprechers fehlgeschlagen',
'voiceprint.editSuccess': 'Erfolgreich bearbeitet',
'voiceprint.editFailed': 'Bearbeiten des Sprechers fehlgeschlagen',
'voiceprint.deleteConfirmMsg': 'Sind Sie sicher, dass Sie diesen Sprecher löschen möchten?',
'voiceprint.deleteConfirmTitle': 'Löschen bestätigen',
'voiceprint.deleteSuccess': 'Erfolgreich gelöscht',
'voiceprint.loading': 'Lädt...',
'voiceprint.delete': 'Löschen',
'voiceprint.emptyTitle': 'Keine Stimmabdruck-Daten',
'voiceprint.emptyDesc': 'Klicken Sie auf die + Schaltfläche unten rechts, um Ihren ersten Sprecher hinzuzufügen',
'voiceprint.addSpeaker': 'Sprecher hinzufügen',
'voiceprint.voiceVector': 'Stimmabdruck-Vektor',
'voiceprint.name': 'Name',
'voiceprint.description': 'Beschreibung',
'voiceprint.pleaseInputDescription': 'Bitte Beschreibung eingeben',
'voiceprint.cancel': 'Abbrechen',
'voiceprint.save': 'Speichern',
'voiceprint.editSpeaker': 'Sprecher bearbeiten',
'voiceprint.selectVector': 'Stimmabdruck-Vektor auswählen',
'voiceprint.voiceprintInterfaceNotConfigured': 'Stimmabdruck-Schnittstelle nicht konfiguriert',
// Einstellungsseite
'settings.pageTitle': 'Einstellungen',
'settings.navigationTitle': 'Einstellungen',
'settings.networkSettings': 'Netzwerkeinstellungen',
'settings.serverApiUrl': 'Server-API-URL',
'settings.validServerUrl': 'Bitte gültige Serveradresse eingeben (beginnt mit http oder https und endet mit /xiaozhi)',
'settings.saveSettings': 'Einstellungen speichern',
'settings.resetDefault': 'Auf Standard zurücksetzen',
'settings.restartApp': 'App neu starten',
'settings.restartNow': 'Jetzt neu starten',
'settings.restartLater': 'Später',
// Über uns
'settings.aboutApp': 'Über XiaoZhi Konsole',
'settings.aboutContent': 'XiaoZhi Konsole\n\nEine plattformübergreifende mobile Management-App, erstellt mit Vue.js 3 + uni-app, bietet Geräteverwaltung, Agentenkonfiguration und andere Funktionen für xiaozhi ESP32 Smart Hardware.\n\n© 2025 xiaozhi-esp32-server {version}',
'settings.restartSuccess': 'Gespeichert, Sie können die App später manuell neu starten',
'settings.serverUrlSavedAndCacheCleared': 'Server-URL gespeichert und Cache geleert',
'settings.resetToDefaultAndCacheCleared': 'Auf Standard zurückgesetzt und Cache geleert',
'settings.resetSuccess': 'Zurücksetzen erfolgreich',
'settings.enterServerUrl': 'Bitte Server-URL eingeben',
'settings.clearCacheFailed': 'Cache konnte nicht geleert werden',
'settings.cacheManagement': 'Cache-Verwaltung',
'settings.totalCacheSize': 'Gesamte Cache-Größe',
'settings.appDataSize': 'Gesamte App-Datengröße',
'settings.cacheClear': 'Cache leeren',
'settings.clearAllCache': 'Alle Cache-Daten löschen',
'settings.clearCache': 'Cache leeren',
'settings.modifyWillClearCache': 'Änderungen werden Cache leeren',
'settings.appInfo': 'App-Info',
'settings.aboutUs': 'Über uns',
'settings.appVersion': 'App-Version & Team-Info',
'settings.confirmClear': 'Löschen bestätigen',
'settings.confirmClearMessage': 'Sind Sie sicher, dass Sie den gesamten Cache löschen möchten? Dies löscht alle Daten einschließlich Anmeldestatus und erfordert erneute Anmeldung.',
'settings.cacheCleared': 'Cache erfolgreich geleert, leite zur Anmeldeseite weiter',
'settings.languageSettings': 'Spracheinstellungen',
'settings.language': 'Sprache',
'settings.selectLanguage': 'Sprache auswählen',
'settings.languageChanged': 'Sprache erfolgreich geändert',
// Nachrichten
'message.loginSuccess': 'Anmeldung erfolgreich!',
'message.loginFail': 'Anmeldung fehlgeschlagen',
'message.registerSuccess': 'Registrierung erfolgreich',
'message.registerFail': 'Registrierung fehlgeschlagen',
'message.saveSuccess': 'Erfolgreich gespeichert',
'message.saveFail': 'Speichern fehlgeschlagen',
'message.deleteSuccess': 'Erfolgreich gelöscht',
'message.deleteFail': 'Löschen fehlgeschlagen',
'message.bindSuccess': 'Binden erfolgreich',
'message.bindFail': 'Binden fehlgeschlagen',
'message.unbindSuccess': 'Entbinden erfolgreich',
'message.unbindFail': 'Entbinden fehlgeschlagen',
'message.networkError': 'Netzwerkfehler, bitte Verbindung prüfen',
'message.serverError': 'Serverfehler, bitte später erneut versuchen',
'message.invalidAddress': 'Ungültige Adresse, bitte prüfen ob Server gestartet oder Netzwerkverbindung normal ist',
'message.languageChanged': 'Sprache geändert',
'message.passwordError': 'Konto oder Passwort Fehler',
'message.phoneRegistered': 'Diese Handynummer wurde bereits registriert',
// Agenten-Werkzeuge Seite
'agent.tools.pageTitle': 'Agenten-Werkzeuge',
'agent.tools.unselected': 'Nicht ausgewählt',
'agent.tools.selected': 'Ausgewählt',
'agent.tools.noMorePlugins': 'Keine weiteren Plugins',
'agent.tools.pleaseSelectPlugin': 'Bitte Plugin-Funktion auswählen',
'agent.tools.builtInPlugins': 'Eingebaute Plugins',
'agent.tools.mcpAccessPoint': 'MCP-Zugangspunkt',
'agent.tools.copy': 'Kopieren',
'agent.tools.noTools': 'Keine Werkzeuge verfügbar',
'agent.tools.parameterConfig': 'Parameterkonfiguration',
'agent.tools.noParamsNeeded': 'Keine Parameter benötigt',
'agent.tools.pleaseInput': 'Bitte eingeben',
'agent.tools.inputOneItemPerLine': 'Ein Element pro Zeile eingeben',
'agent.tools.pleaseInputValidJson': 'Bitte gültiges JSON-Format eingeben',
'agent.tools.enableFunction': 'Funktion aktivieren',
'agent.tools.toggleFunction': 'Diese Funktion ein- oder ausschalten',
'agent.tools.jsonFormatError': 'JSON-Format Fehler',
'agent.tools.noMcpAddressToCopy': 'Keine MCP-Adresse zum Kopieren',
'agent.tools.mcpAddressCopied': 'MCP-Adresse in Zwischenablage kopiert',
'agent.tools.copyFailed': 'Kopieren fehlgeschlagen, bitte erneut versuchen',
'agent.tools.defaultValue': 'Standardwert',
'agent.tools.notSelected': 'Nicht ausgewählt',
'agent.tools.clickToConfigure': 'Klicken zum Konfigurieren',
'agent.tools.mcpEndpoint': 'MCP-Endpunkt',
'agent.tools.eachLineOneItem': 'Ein Element pro Zeile eingeben',
// Gerätekonfigurationsseite
'deviceConfig.pageTitle': 'Gerätekonfiguration',
'deviceConfig.wifiConfig': 'WiFi-Konfiguration',
'deviceConfig.ultrasonicConfig': 'Ultraschall-Konfiguration',
'deviceConfig.selectConfigMethod': 'Konfigurationsmethode auswählen',
'deviceConfig.networkConfig': 'Netzwerkkonfiguration',
'deviceConfig.selectedNetwork': 'Ausgewähltes Netzwerk',
'deviceConfig.signal': 'Signal',
'deviceConfig.openNetwork': 'Offenes Netzwerk',
'deviceConfig.encryptedNetwork': 'Verschlüsseltes Netzwerk',
'deviceConfig.password': 'Passwort',
'deviceConfig.pleaseEnterPassword': 'Bitte WiFi-Passwort eingeben',
'deviceConfig.startConfig': 'Konfiguration starten',
'deviceConfig.connectToXiaozhiHotspot': 'Bitte verbinden Sie sich zuerst mit dem xiaozhi Hotspot',
'deviceConfig.detecting': 'Erkennen...',
'deviceConfig.reDetect': 'Erneut erkennen',
'deviceConfig.alreadyConnected': 'Mit xiaozhi Hotspot verbunden',
'deviceConfig.refreshStatus': 'Status aktualisieren',
'deviceConfig.wifiNetworks': 'WiFi-Netzwerke',
'deviceConfig.selectWifiNetwork': 'WiFi-Netzwerk auswählen',
'deviceConfig.refreshScan': 'Scan aktualisieren',
'deviceConfig.noWifiNetworks': 'Keine WiFi-Netzwerke verfügbar',
'deviceConfig.clickToRefreshScan': 'Bitte Scan aktualisieren klicken',
'deviceConfig.signalStrong': 'Starkes Signal',
'deviceConfig.signalGood': 'Gutes Signal',
'deviceConfig.signalFair': 'Mittleres Signal',
'deviceConfig.signalWeak': 'Schwaches Signal',
'deviceConfig.channel': 'Kanal',
'deviceConfig.about': 'ungefähr',
'deviceConfig.seconds': 'Sekunden',
'deviceConfig.generating': 'Wird generiert...',
'deviceConfig.playing': 'Wird abgespielt...',
'deviceConfig.generateAndPlaySoundWave': 'Schallwelle generieren und abspielen',
'deviceConfig.playSoundWave': 'Schallwelle abspielen',
'deviceConfig.stopPlaying': 'Abspielen stoppen',
'deviceConfig.autoLoopPlaySoundWave': 'Schallwelle automatisch wiederholt abspielen',
'deviceConfig.configAudioFile': 'Konfigurations-Audio-Datei',
'deviceConfig.duration': 'Dauer',
'deviceConfig.ultrasonicConfigInstructions': 'Ultraschall-Konfigurationsanleitung',
'deviceConfig.ensureWifiNetworkSelectedAndPasswordEntered': 'Stellen Sie sicher, dass WiFi-Netzwerk ausgewählt und Passwort eingegeben ist',
'deviceConfig.clickGenerateAndPlaySoundWave': 'Klicken Sie auf Schallwelle generieren und abspielen, das System kodiert Konfigurationsinformationen in Audio',
'deviceConfig.bringPhoneCloseToXiaozhiDevice': 'Bringen Sie das Telefon in die Nähe des xiaozhi Geräts (1-2 Meter Entfernung)',
'deviceConfig.duringAudioPlaybackXiaozhiWillReceive': 'Während der Audio-Wiedergabe empfängt xiaozhi und dekodiert Konfigurationsinformationen',
'deviceConfig.afterConfigSuccessDeviceWillConnect': 'Nach erfolgreicher Konfiguration verbindet sich das Gerät automatisch mit dem WiFi-Netzwerk',
'deviceConfig.usesAfskModulation': 'Verwendet AFSK-Modulationstechnologie, überträgt Daten durch 1800Hz und 1500Hz Frequenzen',
'deviceConfig.ensureModeratePhoneVolume': 'Bitte stellen Sie sicher, dass die Telefonlautstärke moderat ist, um Umgebungsgeräuschstörungen zu vermeiden',
'deviceConfig.generatingUltrasonicConfigAudio': 'Ultraschall-Konfigurationsaudio wird generiert',
'deviceConfig.configData': 'Konfigurationsdaten',
'deviceConfig.dataBytesLength': 'Datenbytes-Länge',
'deviceConfig.bitStreamLength': 'Bitstrom-Länge',
'deviceConfig.base64Length': 'Base64-Länge',
'deviceConfig.audioFileTooLarge': 'Audio-Datei zu groß, bitte SSID oder Passwortlänge kürzen',
'deviceConfig.audioGenerationSuccess': 'Audio-Generierung erfolgreich',
'deviceConfig.samplePoints': 'Abtastpunkte',
'deviceConfig.soundWaveGenerationSuccess': 'Schallwellen-Generierung erfolgreich',
'deviceConfig.audioGenerationFailed': 'Audio-Generierung fehlgeschlagen',
'deviceConfig.soundWaveGenerationFailed': 'Schallwellen-Generierung fehlgeschlagen',
'deviceConfig.pleaseGenerateAudioFirst': 'Bitte generieren Sie zuerst Audio',
'deviceConfig.startPlayingUltrasonicConfigAudio': 'Ultraschall-Konfigurationsaudio wird abgespielt',
'deviceConfig.ultrasonicAudioStartedPlaying': 'Ultraschall-Audio wurde gestartet',
'deviceConfig.startPlayingConfigSoundWave': 'Konfigurations-Schallwelle wurde gestartet',
'deviceConfig.ultrasonicAudioPlaybackEnded': 'Ultraschall-Audio-Wiedergabe beendet',
'deviceConfig.audioPlaybackFailed': 'Audio-Wiedergabe fehlgeschlagen',
'deviceConfig.audioResourceBusy': 'Audio-Ressource beschäftigt, bitte später erneut versuchen',
'deviceConfig.audioFormatNotSupported': 'Audio-Format nicht unterstützt, möglicherweise ein Data-URI-Problem',
'deviceConfig.audioFileError': 'Audio-Datei-Fehler',
'deviceConfig.cleaningUpAudioContext': 'Audio-Kontext wird bereinigt',
'deviceConfig.cleaningUpAudioContextFailed': 'Audio-Kontext-Bereinigung fehlgeschlagen',
'deviceConfig.stoppedPlayingUltrasonicAudio': 'Ultraschall-Audio-Wiedergabe gestoppt',
'deviceConfig.stoppedPlaying': 'Wiedergabe gestoppt',
'deviceConfig.configMethod': 'Konfigurationsmethode',
'deviceConfig.enterWifiPassword': 'Bitte WiFi-Passwort eingeben',
'deviceConfig.xiaozhi': 'xiaozhi',
'deviceConfig.connectXiaozhiHotspot': 'Bitte verbinden Sie sich mit dem xiaozhi Hotspot',
'deviceConfig.wifiScanResponse': 'WiFi-Scan-Antwort',
'deviceConfig.scanSuccess': 'Scan erfolgreich',
'deviceConfig.networks': 'Netzwerke',
'deviceConfig.wifiScanFailed': 'WiFi-Scan fehlgeschlagen',
'deviceConfig.scanFailedCheckConnection': 'Scan fehlgeschlagen, bitte Verbindung prüfen',
'deviceConfig.checking': 'Wird geprüft',
'deviceConfig.reCheck': 'Erneut prüfen',
'deviceConfig.connectedXiaozhiHotspot': 'Mit xiaozhi Hotspot verbunden',
'deviceConfig.wifiNetwork': 'WiFi-Netzwerk',
'deviceConfig.scanning': 'Wird gescannt',
'deviceConfig.cancel': 'Abbrechen',
'deviceConfig.clickRefreshScan': 'Bitte Scan aktualisieren klicken',
'deviceConfig.esp32ConnectionCheckFailed': 'ESP32-Verbindungsprüfung fehlgeschlagen',
'deviceConfig.startWifiConfig': 'WiFi-Konfiguration wird gestartet',
'deviceConfig.configSuccess': 'Konfiguration erfolgreich',
'deviceConfig.deviceWillConnectTo': 'Gerät wird sich verbinden mit',
'deviceConfig.deviceWillRestart': 'Gerät wird neu starten',
'deviceConfig.pleaseDisconnectXiaozhiHotspot': 'Bitte trennen Sie sich vom xiaozhi Hotspot',
'deviceConfig.configFailed': 'Konfiguration fehlgeschlagen',
'deviceConfig.wifiConfigFailed': 'WiFi-Konfiguration fehlgeschlagen',
'deviceConfig.pleaseCheckNetworkConnection': 'Bitte Netzwerkverbindung prüfen',
'deviceConfig.startWifiConfigButton': 'Konfiguration starten',
'deviceConfig.wifiConfigInstructions': 'WiFi-Konfigurationsanleitung',
'deviceConfig.phoneConnectXiaozhiHotspot': 'Telefon mit xiaozhi Hotspot verbinden',
'deviceConfig.selectTargetWifiNetwork': 'Ziel-WiFi-Netzwerk auswählen',
'deviceConfig.enterWifiPasswordIfNeeded': 'WiFi-Passwort eingeben falls benötigt',
'deviceConfig.clickStartConfigAndWait': 'Konfiguration starten klicken und warten',
'deviceConfig.afterConfigSuccessDeviceWillRestart': 'Nach erfolgreicher Konfiguration startet Gerät automatisch neu',
'deviceConfig.audioPlaybackError': 'Audio-Wiedergabe-Fehler',
'deviceConfig.playbackFailed': 'Wiedergabe fehlgeschlagen',
}
+11 -5
View File
@@ -3,15 +3,19 @@ import { useLangStore } from '@/store/lang'
import type { Language } from '@/store/lang'
// 导入各个语言的翻译文件
import zhCN from './zh_CN'
import zh_CN from './zh_CN'
import en from './en'
import zhTW from './zh_TW'
import zh_TW from './zh_TW'
import de from './de'
import vi from './vi'
// 语言包映射
const messages = {
zh_CN: zhCN,
zh_CN: zh_CN,
en,
zh_TW: zhTW,
zh_TW: zh_TW,
de,
vi,
}
// 当前使用的语言
@@ -61,10 +65,12 @@ export function getCurrentLanguage(): Language {
}
// 获取支持的语言列表
export function getSupportedLanguages(): {code: Language, name: string}[] {
export function getSupportedLanguages(): { code: Language, name: string }[] {
return [
{ code: 'zh_CN', name: '简体中文' },
{ code: 'en', name: 'English' },
{ code: 'zh_TW', name: '繁體中文' },
{ code: 'de', name: 'Deutsch' },
{ code: 'vi', name: 'Tiếng Việt' },
]
}
+440
View File
@@ -0,0 +1,440 @@
// Gói ngôn ngữ tiếng Việt
export default {
// TabBar
'tabBar.home': 'Trang chủ',
'tabBar.deviceConfig': 'Cấu hình mạng',
'tabBar.settings': 'Hệ thống',
// Tiêu đề trang cài đặt
'settings.title': 'Cài đặt',
// Trang đăng nhập
'login.pageTitle': 'Đăng nhập',
'login.navigationTitle': 'Đăng nhập',
'login.fetchConfigError': 'Không thể tải cấu hình:',
'login.selectLanguage': 'Chọn ngôn ngữ',
'login.selectLanguageTip': 'de',
'login.welcomeBack': 'Chào mừng trở lại',
'login.pleaseLogin': 'Vui lòng đăng nhập vào tài khoản của bạn',
'login.enterUsername': 'Vui lòng nhập tên đăng nhập',
'login.enterPassword': 'Vui lòng nhập mật khẩu',
'login.enterCaptcha': 'Vui lòng nhập mã xác minh',
'login.loginButton': 'Đăng nhập',
'login.loggingIn': 'Đang đăng nhập...',
'login.noAccount': 'Đăng ký',
'login.enterPhone': 'Vui lòng nhập số điện thoại',
'login.selectCountry': 'Chọn quốc gia/vùng',
'login.confirm': 'Xác nhận',
'login.serverSetting': 'Cài đặt máy chủ',
'login.requiredUsername': 'Tên đăng nhập không thể để trống',
'login.requiredPassword': 'Mật khẩu không thể để trống',
'login.requiredCaptcha': 'Mã xác minh không thể để trống',
'login.requiredMobile': 'Vui lòng nhập số điện thoại hợp lệ',
'login.captchaError': 'Lỗi mã xác minh đồ họa',
'login.forgotPassword': 'Quên mật khẩu',
// Trang đăng ký
'register.pageTitle': 'Đăng ký',
'register.createAccount': 'Tạo tài khoản',
'register.enterUsername': 'Vui lòng nhập tên đăng nhập',
'register.enterPassword': 'Vui lòng nhập mật khẩu',
'register.confirmPassword': 'Vui lòng xác nhận mật khẩu',
'register.enterPhone': 'Vui lòng nhập số điện thoại',
'register.enterCode': 'Vui lòng nhập mã xác minh',
'register.getCode': 'Lấy mã',
'register.agreeTerms': 'Tôi đã đọc và đồng ý với',
'register.terms': 'Thỏa thuận người dùng',
'register.privacy': 'Chính sách bảo mật',
'register.registerButton': 'Đăng ký',
'register.registering': 'Đang đăng ký...',
'register.haveAccount': 'Đã có tài khoản?',
'register.loginNow': 'Đăng nhập ngay',
'register.selectCountry': 'Chọn quốc gia/vùng',
'register.confirm': 'Xác nhận',
'register.captchaSendSuccess': 'Đã gửi mã xác minh thành công',
// Trang chủ
'home.pageTitle': 'Trang chủ',
'home.createAgent': 'Tạo đại lý',
'home.agentName': 'Đại lý',
'home.modelInfo': 'Thông tin mô hình',
'home.lastActive': 'Hoạt động lần cuối',
'home.greeting': 'Xin chào Jarvis',
'home.subtitle': 'Hãy cùng có',
'home.wonderfulDay': 'một ngày tuyệt vời!',
'home.emptyState': 'Không có đại lý nào',
'home.deviceManagement': 'Quản lý thiết bị',
'home.lastConversation': 'Cuộc trò chuyện cuối:',
'home.delete': 'Xóa',
'home.createFirstAgent': 'Nhấp vào nút + ở góc dưới bên phải để tạo đại lý đầu tiên của bạn',
'home.dialogTitle': 'Tạo đại lý',
'home.inputPlaceholder': 'ví dụ: Trợ lý chăm sóc khách hàng, Trợ lý giọng nói, Hỏi đáp kiến thức',
'home.createError': 'Vui lòng nhập tên đại lý',
'home.createNow': 'Tạo ngay',
'home.justNow': 'Vừa xong',
'home.minutesAgo': 'phút trước',
'home.hoursAgo': 'giờ trước',
'home.daysAgo': 'ngày trước',
// Trang đại lý
'agent.pageTitle': 'Đại lý',
'agent.roleConfig': 'Cấu hình vai trò',
'agent.deviceManagement': 'Quản lý thiết bị',
'agent.chatHistory': 'Lịch sử trò chuyện',
'agent.voiceprintManagement': 'Quản lý dấu giọng nói',
'agent.editTitle': 'Chỉnh sửa đại lý',
'agent.toolsTitle': 'Chỉnh sửa tính năng',
'agent.voiceActivityDetection': 'Phát hiện hoạt động giọng nói',
'agent.speechRecognition': 'Nhận dạng giọng nói',
'agent.largeLanguageModel': 'Mô hình ngôn ngữ lớn',
'agent.save': 'Lưu',
'agent.cancel': 'Hủy',
// Trang chỉnh sửa đại lý
'agent.basicInfo': 'Thông tin cơ bản',
'agent.agentName': 'Tên đại lý',
'agent.inputAgentName': 'Vui lòng nhập tên đại lý',
'agent.roleMode': 'Chế độ vai trò',
'agent.roleDescription': 'Mô tả vai trò',
'agent.inputRoleDescription': 'Vui lòng nhập mô tả vai trò',
'agent.modelConfig': 'Cấu hình mô hình',
'agent.vad': 'Phát hiện hoạt động giọng nói',
'agent.asr': 'Nhận dạng giọng nói',
'agent.llm': 'Mô hình ngôn ngữ lớn',
'agent.vllm': 'Mô hình ngôn ngữ thị giác',
'agent.intent': 'Nhận dạng ý định',
'agent.memory': 'Bộ nhớ',
'agent.voiceSettings': 'Cài đặt giọng nói',
'agent.tts': 'Văn bản thành giọng nói',
'agent.voiceprint': 'Giọng nói đại lý',
'agent.plugins': 'Plugin',
'agent.editFunctions': 'Chỉnh sửa tính năng',
'agent.historyMemory': 'Bộ nhớ lịch sử',
'agent.memoryContent': 'Nội dung bộ nhớ',
'agent.saving': 'Đang lưu...',
'agent.saveSuccess': 'Lưu thành công',
'agent.saveFail': 'Lưu thất bại',
'agent.loadFail': 'Tải thất bại',
'agent.pleaseInputAgentName': 'Vui lòng nhập tên đại lý',
'agent.pleaseInputRoleDescription': 'Vui lòng nhập mô tả vai trò',
'agent.pleaseSelect': 'Vui lòng chọn',
// Trang lịch sử trò chuyện
'chatHistory.getChatSessions': 'Lấy danh sách phiên trò chuyện',
'chatHistory.noSelectedAgent': 'Chưa chọn đại lý',
'chatHistory.getChatSessionsFailed': 'Không thể lấy danh sách phiên trò chuyện:',
'chatHistory.unknownTime': 'Thời gian không xác định',
'chatHistory.justNow': 'Vừa xong',
'chatHistory.minutesAgo': '{minutes} phút trước',
'chatHistory.hoursAgo': '{hours} giờ trước',
'chatHistory.daysAgo': '{days} ngày trước',
'chatHistory.conversationRecord': 'Bản ghi trò chuyện',
'chatHistory.totalChats': 'Tổng cộng {count} cuộc trò chuyện',
'chatHistory.loading': 'Đang tải...',
'chatHistory.noMoreData': 'Không còn dữ liệu',
'chatHistory.noChatRecords': 'Không có bản ghi trò chuyện',
'chatHistory.chatRecordsDescription': 'Bản ghi trò chuyện với đại lý sẽ hiển thị ở đây',
// Trang chi tiết lịch sử trò chuyện
'chatHistory.pageTitle': 'Chi tiết trò chuyện',
'chatHistory.assistantName': 'Trợ lý thông minh',
'chatHistory.userName': 'Người dùng',
'chatHistory.aiAssistantName': 'Trợ lý AI',
'chatHistory.loadFailed': 'Không thể tải lịch sử trò chuyện',
'chatHistory.parameterError': 'Lỗi tham số trang',
'chatHistory.invalidAudioId': 'ID âm thanh không hợp lệ',
'chatHistory.audioPlayFailed': 'Phát âm thanh thất bại',
'chatHistory.playAudioFailed': 'Không thể phát âm thanh',
// Trang quản lý thiết bị
'device.pageTitle': 'Quản lý thiết bị',
'device.noDevices': 'Không có thiết bị nào',
'device.macAddress': 'Địa chỉ MAC',
'device.firmwareVersion': 'Phiên bản firmware',
'device.lastConnected': 'Cuộc trò chuyện cuối',
'device.otaUpdate': 'Cập nhật OTA',
'device.unbind': 'Hủy liên kết',
'device.confirmUnbind': 'Xác nhận',
'device.bindDevice': 'Liên kết thiết bị mới',
'device.deviceType': 'Loại thiết bị',
'device.loading': 'Đang tải...',
'device.neverConnected': 'Chưa kết nối',
'device.justNow': 'Vừa xong',
'device.minutesAgo': '{minutes} phút trước',
'device.hoursAgo': '{hours} giờ trước',
'device.daysAgo': '{days} ngày trước',
'device.otaAutoUpdateEnabled': 'Đã bật cập nhật OTA tự động',
'device.otaAutoUpdateDisabled': 'Đã tắt cập nhật OTA tự động',
'device.operationFailed': 'Thao tác thất bại, vui lòng thử lại',
'device.deviceUnbound': 'Đã hủy liên kết thiết bị',
'device.unbindFailed': 'Hủy liên kết thất bại, vui lòng thử lại',
'device.unbindDevice': 'Hủy liên kết thiết bị',
'device.confirmUnbindDevice': 'Bạn có chắc chắn muốn hủy liên kết thiết bị "{macAddress}"?',
'device.cancel': 'Hủy',
'device.noDevice': 'Không có thiết bị',
'device.pleaseSelectAgent': 'Vui lòng chọn một đại lý trước',
'device.deviceBindSuccess': 'Liên kết thiết bị thành công!',
'device.bindFailed': 'Liên kết thất bại, vui lòng kiểm tra mã xác minh có đúng không',
'device.enterDeviceCode': 'Vui lòng nhập mã xác minh thiết bị',
'device.bindNow': 'Liên kết ngay',
'device.lastConnection': 'Kết nối cuối',
'device.clickToBindFirstDevice': 'Nhấp vào nút + ở góc dưới bên phải để liên kết thiết bị đầu tiên của bạn',
// Chung
'common.success': 'Thành công',
'common.fail': 'Thất bại',
'common.loading': 'Đang tải...',
'common.confirm': 'Xác nhận',
'common.cancel': 'Hủy',
'common.delete': 'Xóa',
'common.edit': 'Chỉnh sửa',
'common.add': 'Thêm',
'common.pleaseSelect': 'Vui lòng chọn',
'common.unknownError': 'Lỗi không xác định',
'common.networkError': 'Lỗi mạng',
// Trang khôi phục mật khẩu
'retrievePassword.title': 'Đặt lại mật khẩu',
'retrievePassword.subtitle': 'Khôi phục mật khẩu tài khoản qua số điện thoại',
'retrievePassword.mobileRequired': 'Vui lòng nhập số điện thoại',
'retrievePassword.inputCorrectMobile': 'Vui lòng nhập số điện thoại hợp lệ',
'retrievePassword.captchaRequired': 'Vui lòng nhập mã xác minh đồ họa',
'retrievePassword.mobileCaptchaRequired': 'Vui lòng nhập mã xác minh SMS',
'retrievePassword.newPasswordRequired': 'Vui lòng nhập mật khẩu mới',
'retrievePassword.confirmNewPasswordRequired': 'Vui lòng xác nhận mật khẩu mới',
'retrievePassword.passwordsNotMatch': 'Mật khẩu không khớp',
'retrievePassword.mobilePlaceholder': 'Vui lòng nhập số điện thoại',
'retrievePassword.captchaPlaceholder': 'Vui lòng nhập mã xác minh đồ họa',
'retrievePassword.mobileCaptchaPlaceholder': 'Vui lòng nhập mã xác minh SMS',
'retrievePassword.newPasswordPlaceholder': 'Vui lòng nhập mật khẩu mới',
'retrievePassword.confirmNewPasswordPlaceholder': 'Vui lòng xác nhận mật khẩu mới',
'retrievePassword.getMobileCaptcha': 'Lấy mã',
'retrievePassword.captchaSendSuccess': 'Đã gửi mã xác minh thành công',
'retrievePassword.passwordUpdateSuccess': 'Đặt lại mật khẩu thành công',
'retrievePassword.resetButton': 'Đặt lại mật khẩu',
'retrievePassword.goToLogin': 'Quay lại đăng nhập',
// Thông báo lỗi liên quan đến mã hóa SM2
'sm2.publicKeyNotConfigured': 'Khóa công khai SM2 chưa được cấu hình, vui lòng liên hệ quản trị viên',
'sm2.encryptionFailed': 'Mã hóa mật khẩu thất bại',
'sm2.keyGenerationFailed': 'Tạo cặp khóa thất bại',
'sm2.invalidPublicKey': 'Định dạng khóa công khai không hợp lệ',
'sm2.encryptionError': 'Đã xảy ra lỗi khi mã hóa',
'sm2.publicKeyRetry': 'Đang thử lấy lại khóa công khai...',
'sm2.publicKeyRetryFailed': 'Thử lấy lại khóa công khai thất bại',
// Trang dấu giọng nói
'voiceprint.noSelectedAgent': 'Chưa chọn đại lý',
'voiceprint.pleaseSelectAgent': 'Vui lòng chọn một đại lý trước',
'voiceprint.fetchHistoryFailed': 'Không thể tải lịch sử trò chuyện',
'voiceprint.clickToSelectVector': 'Nhấp để chọn vector dấu giọng nói',
'voiceprint.pleaseInputName': 'Vui lòng nhập tên',
'voiceprint.pleaseSelectVector': 'Vui lòng chọn vector dấu giọng nói',
'voiceprint.addSuccess': 'Thêm thành công',
'voiceprint.addFailed': 'Thêm người nói thất bại',
'voiceprint.editSuccess': 'Chỉnh sửa thành công',
'voiceprint.editFailed': 'Chỉnh sửa người nói thất bại',
'voiceprint.deleteConfirmMsg': 'Bạn có chắc chắn muốn xóa người nói này?',
'voiceprint.deleteConfirmTitle': 'Xác nhận xóa',
'voiceprint.deleteSuccess': 'Xóa thành công',
'voiceprint.loading': 'Đang tải...',
'voiceprint.delete': 'Xóa',
'voiceprint.emptyTitle': 'Không có dữ liệu dấu giọng nói',
'voiceprint.emptyDesc': 'Nhấp vào nút + ở góc dưới bên phải để thêm người nói đầu tiên của bạn',
'voiceprint.addSpeaker': 'Thêm người nói',
'voiceprint.voiceVector': 'Vector dấu giọng nói',
'voiceprint.name': 'Tên',
'voiceprint.description': 'Mô tả',
'voiceprint.pleaseInputDescription': 'Vui lòng nhập mô tả',
'voiceprint.cancel': 'Hủy',
'voiceprint.save': 'Lưu',
'voiceprint.editSpeaker': 'Chỉnh sửa người nói',
'voiceprint.selectVector': 'Chọn vector dấu giọng nói',
'voiceprint.voiceprintInterfaceNotConfigured': 'Giao diện dấu giọng nói chưa được cấu hình',
// Trang cài đặt
'settings.pageTitle': 'Cài đặt',
'settings.navigationTitle': 'Cài đặt',
'settings.networkSettings': 'Cài đặt mạng',
'settings.serverApiUrl': 'URL API máy chủ',
'settings.validServerUrl': 'Vui lòng nhập địa chỉ máy chủ hợp lệ (bắt đầu bằng http hoặc https và kết thúc bằng /xiaozhi)',
'settings.saveSettings': 'Lưu cài đặt',
'settings.resetDefault': 'Đặt lại mặc định',
'settings.restartApp': 'Khởi động lại ứng dụng',
'settings.restartNow': 'Khởi động lại ngay',
'settings.restartLater': 'Để sau',
// Về chúng tôi
'settings.aboutApp': 'Về Bảng điều khiển XiaoZhi',
'settings.aboutContent': 'Bảng điều khiển XiaoZhi\n\nỨng dụng quản lý di động đa nền tảng được xây dựng với Vue.js 3 + uni-app, cung cấp quản lý thiết bị, cấu hình đại lý và các chức năng khác cho phần cứng thông minh xiaozhi ESP32.\n\n© 2025 xiaozhi-esp32-server {version}',
'settings.restartSuccess': 'Đã lưu, bạn có thể tự khởi động lại ứng dụng sau',
'settings.serverUrlSavedAndCacheCleared': 'Đã lưu URL máy chủ và xóa bộ nhớ cache',
'settings.resetToDefaultAndCacheCleared': 'Đã đặt lại mặc định và xóa bộ nhớ cache',
'settings.resetSuccess': 'Đặt lại thành công',
'settings.enterServerUrl': 'Vui lòng nhập URL máy chủ',
'settings.clearCacheFailed': 'Không thể xóa bộ nhớ cache',
'settings.cacheManagement': 'Quản lý bộ nhớ cache',
'settings.totalCacheSize': 'Tổng kích thước bộ nhớ cache',
'settings.appDataSize': 'Tổng kích thước dữ liệu ứng dụng',
'settings.cacheClear': 'Xóa bộ nhớ cache',
'settings.clearAllCache': 'Xóa tất cả dữ liệu bộ nhớ cache',
'settings.clearCache': 'Xóa bộ nhớ cache',
'settings.modifyWillClearCache': 'Thay đổi sẽ xóa bộ nhớ cache',
'settings.appInfo': 'Thông tin ứng dụng',
'settings.aboutUs': 'Về chúng tôi',
'settings.appVersion': 'Phiên bản ứng dụng & Thông tin nhóm',
'settings.confirmClear': 'Xác nhận xóa',
'settings.confirmClearMessage': 'Bạn có chắc chắn muốn xóa toàn bộ bộ nhớ cache? Điều này sẽ xóa tất cả dữ liệu bao gồm trạng thái đăng nhập và yêu cầu đăng nhập lại.',
'settings.cacheCleared': 'Đã xóa bộ nhớ cache thành công, đang chuyển hướng đến trang đăng nhập',
'settings.languageSettings': 'Cài đặt ngôn ngữ',
'settings.language': 'Ngôn ngữ',
'settings.selectLanguage': 'Chọn ngôn ngữ',
'settings.languageChanged': 'Đã thay đổi ngôn ngữ thành công',
// Thông báo
'message.loginSuccess': 'Đăng nhập thành công!',
'message.loginFail': 'Đăng nhập thất bại',
'message.registerSuccess': 'Đăng ký thành công',
'message.registerFail': 'Đăng ký thất bại',
'message.saveSuccess': 'Lưu thành công',
'message.saveFail': 'Lưu thất bại',
'message.deleteSuccess': 'Xóa thành công',
'message.deleteFail': 'Xóa thất bại',
'message.bindSuccess': 'Liên kết thành công',
'message.bindFail': 'Liên kết thất bại',
'message.unbindSuccess': 'Hủy liên kết thành công',
'message.unbindFail': 'Hủy liên kết thất bại',
'message.networkError': 'Lỗi mạng, vui lòng kiểm tra kết nối',
'message.serverError': 'Lỗi máy chủ, vui lòng thử lại sau',
'message.invalidAddress': 'Địa chỉ không hợp lệ, vui lòng kiểm tra máy chủ đã khởi động hoặc kết nối mạng bình thường',
'message.languageChanged': 'Đã thay đổi ngôn ngữ',
'message.passwordError': 'Lỗi tài khoản hoặc mật khẩu',
'message.phoneRegistered': 'Số điện thoại này đã được đăng ký',
// Trang công cụ đại lý
'agent.tools.pageTitle': 'Công cụ đại lý',
'agent.tools.unselected': 'Chưa chọn',
'agent.tools.selected': 'Đã chọn',
'agent.tools.noMorePlugins': 'Không còn plugin',
'agent.tools.pleaseSelectPlugin': 'Vui lòng chọn chức năng plugin',
'agent.tools.builtInPlugins': 'Plugin tích hợp',
'agent.tools.mcpAccessPoint': 'Điểm truy cập MCP',
'agent.tools.copy': 'Sao chép',
'agent.tools.noTools': 'Không có công cụ nào',
'agent.tools.parameterConfig': 'Cấu hình tham số',
'agent.tools.noParamsNeeded': 'Không cần tham số',
'agent.tools.pleaseInput': 'Vui lòng nhập',
'agent.tools.inputOneItemPerLine': 'Nhập một mục mỗi dòng',
'agent.tools.pleaseInputValidJson': 'Vui lòng nhập định dạng JSON hợp lệ',
'agent.tools.enableFunction': 'Bật chức năng',
'agent.tools.toggleFunction': 'Bật hoặc tắt chức năng này',
'agent.tools.jsonFormatError': 'Lỗi định dạng JSON',
'agent.tools.noMcpAddressToCopy': 'Không có địa chỉ MCP để sao chép',
'agent.tools.mcpAddressCopied': 'Đã sao chép địa chỉ MCP vào bộ nhớ tạm',
'agent.tools.copyFailed': 'Sao chép thất bại, vui lòng thử lại',
'agent.tools.defaultValue': 'Giá trị mặc định',
'agent.tools.notSelected': 'Chưa chọn',
'agent.tools.clickToConfigure': 'Nhấp để cấu hình',
'agent.tools.mcpEndpoint': 'Điểm cuối MCP',
'agent.tools.eachLineOneItem': 'Nhập một mục mỗi dòng',
// Trang cấu hình thiết bị
'deviceConfig.pageTitle': 'Cấu hình thiết bị',
'deviceConfig.wifiConfig': 'Cấu hình WiFi',
'deviceConfig.ultrasonicConfig': 'Cấu hình siêu âm',
'deviceConfig.selectConfigMethod': 'Chọn phương pháp cấu hình',
'deviceConfig.networkConfig': 'Cấu hình mạng',
'deviceConfig.selectedNetwork': 'Mạng đã chọn',
'deviceConfig.signal': 'Tín hiệu',
'deviceConfig.openNetwork': 'Mạng mở',
'deviceConfig.encryptedNetwork': 'Mạng mã hóa',
'deviceConfig.password': 'Mật khẩu',
'deviceConfig.pleaseEnterPassword': 'Vui lòng nhập mật khẩu WiFi',
'deviceConfig.startConfig': 'Bắt đầu cấu hình',
'deviceConfig.connectToXiaozhiHotspot': 'Vui lòng kết nối với điểm phát sóng xiaozhi trước',
'deviceConfig.detecting': 'Đang phát hiện...',
'deviceConfig.reDetect': 'Phát hiện lại',
'deviceConfig.alreadyConnected': 'Đã kết nối với điểm phát sóng xiaozhi',
'deviceConfig.refreshStatus': 'Làm mới trạng thái',
'deviceConfig.wifiNetworks': 'Mạng WiFi',
'deviceConfig.selectWifiNetwork': 'Chọn mạng WiFi',
'deviceConfig.refreshScan': 'Làm mới quét',
'deviceConfig.noWifiNetworks': 'Không có mạng WiFi nào',
'deviceConfig.clickToRefreshScan': 'Vui lòng nhấp Làm mới quét',
'deviceConfig.signalStrong': 'Tín hiệu mạnh',
'deviceConfig.signalGood': 'Tín hiệu tốt',
'deviceConfig.signalFair': 'Tín hiệu trung bình',
'deviceConfig.signalWeak': 'Tín hiệu yếu',
'deviceConfig.channel': 'Kênh',
'deviceConfig.about': 'khoảng',
'deviceConfig.seconds': 'giây',
'deviceConfig.generating': 'Đang tạo...',
'deviceConfig.playing': 'Đang phát...',
'deviceConfig.generateAndPlaySoundWave': 'Tạo và phát sóng âm',
'deviceConfig.playSoundWave': 'Phát sóng âm',
'deviceConfig.stopPlaying': 'Dừng phát',
'deviceConfig.autoLoopPlaySoundWave': 'Tự động lặp phát sóng âm',
'deviceConfig.configAudioFile': 'Tệp âm thanh cấu hình',
'deviceConfig.duration': 'Thời lượng',
'deviceConfig.ultrasonicConfigInstructions': 'Hướng dẫn cấu hình siêu âm',
'deviceConfig.ensureWifiNetworkSelectedAndPasswordEntered': 'Đảm bảo mạng WiFi được chọn và mật khẩu đã nhập',
'deviceConfig.clickGenerateAndPlaySoundWave': 'Nhấp Tạo và phát sóng âm, hệ thống sẽ mã hóa thông tin cấu hình thành âm thanh',
'deviceConfig.bringPhoneCloseToXiaozhiDevice': 'Đưa điện thoại lại gần thiết bị xiaozhi (khoảng cách 1-2 mét)',
'deviceConfig.duringAudioPlaybackXiaozhiWillReceive': 'Trong khi phát âm thanh, xiaozhi sẽ nhận và giải mã thông tin cấu hình',
'deviceConfig.afterConfigSuccessDeviceWillConnect': 'Sau khi cấu hình thành công, thiết bị sẽ tự động kết nối với mạng WiFi',
'deviceConfig.usesAfskModulation': 'Sử dụng công nghệ điều chế AFSK, truyền dữ liệu qua tần số 1800Hz và 1500Hz',
'deviceConfig.ensureModeratePhoneVolume': 'Vui lòng đảm bảo âm lượng điện thoại vừa phải để tránh nhiễu tiếng ồn môi trường',
'deviceConfig.generatingUltrasonicConfigAudio': 'Đang tạo âm thanh cấu hình siêu âm',
'deviceConfig.configData': 'Dữ liệu cấu hình',
'deviceConfig.dataBytesLength': 'Độ dài byte dữ liệu',
'deviceConfig.bitStreamLength': 'Độ dài luồng bit',
'deviceConfig.base64Length': 'Độ dài base64',
'deviceConfig.audioFileTooLarge': 'Tệp âm thanh quá lớn, vui lòng rút ngắn SSID hoặc độ dài mật khẩu',
'deviceConfig.audioGenerationSuccess': 'Tạo âm thanh thành công',
'deviceConfig.samplePoints': 'Điểm mẫu',
'deviceConfig.soundWaveGenerationSuccess': 'Tạo sóng âm thành công',
'deviceConfig.audioGenerationFailed': 'Tạo âm thanh thất bại',
'deviceConfig.soundWaveGenerationFailed': 'Tạo sóng âm thất bại',
'deviceConfig.pleaseGenerateAudioFirst': 'Vui lòng tạo âm thanh trước',
'deviceConfig.startPlayingUltrasonicConfigAudio': 'Bắt đầu phát âm thanh cấu hình siêu âm',
'deviceConfig.ultrasonicAudioStartedPlaying': 'Đã bắt đầu phát âm thanh siêu âm',
'deviceConfig.startPlayingConfigSoundWave': 'Đã bắt đầu phát sóng âm cấu hình',
'deviceConfig.ultrasonicAudioPlaybackEnded': 'Kết thúc phát âm thanh siêu âm',
'deviceConfig.audioPlaybackFailed': 'Phát âm thanh thất bại',
'deviceConfig.audioResourceBusy': 'Tài nguyên âm thanh bận, vui lòng thử lại sau',
'deviceConfig.audioFormatNotSupported': 'Định dạng âm thanh không được hỗ trợ, có thể là vấn đề URI dữ liệu',
'deviceConfig.audioFileError': 'Lỗi tệp âm thanh',
'deviceConfig.cleaningUpAudioContext': 'Đang dọn dẹp ngữ cảnh âm thanh',
'deviceConfig.cleaningUpAudioContextFailed': 'Không thể dọn dẹp ngữ cảnh âm thanh',
'deviceConfig.stoppedPlayingUltrasonicAudio': 'Đã dừng phát âm thanh siêu âm',
'deviceConfig.stoppedPlaying': 'Đã dừng phát',
'deviceConfig.configMethod': 'Phương pháp cấu hình',
'deviceConfig.enterWifiPassword': 'Vui lòng nhập mật khẩu WiFi',
'deviceConfig.xiaozhi': 'xiaozhi',
'deviceConfig.connectXiaozhiHotspot': 'Vui lòng kết nối với điểm phát sóng xiaozhi',
'deviceConfig.wifiScanResponse': 'Phản hồi quét WiFi',
'deviceConfig.scanSuccess': 'Quét thành công',
'deviceConfig.networks': 'mạng',
'deviceConfig.wifiScanFailed': 'Quét WiFi thất bại',
'deviceConfig.scanFailedCheckConnection': 'Quét thất bại, vui lòng kiểm tra kết nối',
'deviceConfig.checking': 'Đang kiểm tra',
'deviceConfig.reCheck': 'Kiểm tra lại',
'deviceConfig.connectedXiaozhiHotspot': 'Đã kết nối với điểm phát sóng xiaozhi',
'deviceConfig.wifiNetwork': 'Mạng WiFi',
'deviceConfig.scanning': 'Đang quét',
'deviceConfig.cancel': 'Hủy',
'deviceConfig.clickRefreshScan': 'Vui lòng nhấp Làm mới quét',
'deviceConfig.esp32ConnectionCheckFailed': 'Kiểm tra kết nối ESP32 thất bại',
'deviceConfig.startWifiConfig': 'Đang bắt đầu cấu hình WiFi',
'deviceConfig.configSuccess': 'Cấu hình thành công',
'deviceConfig.deviceWillConnectTo': 'Thiết bị sẽ kết nối với',
'deviceConfig.deviceWillRestart': 'Thiết bị sẽ khởi động lại',
'deviceConfig.pleaseDisconnectXiaozhiHotspot': 'Vui lòng ngắt kết nối khỏi điểm phát sóng xiaozhi',
'deviceConfig.configFailed': 'Cấu hình thất bại',
'deviceConfig.wifiConfigFailed': 'Cấu hình WiFi thất bại',
'deviceConfig.pleaseCheckNetworkConnection': 'Vui lòng kiểm tra kết nối mạng',
'deviceConfig.startWifiConfigButton': 'Bắt đầu cấu hình',
'deviceConfig.wifiConfigInstructions': 'Hướng dẫn cấu hình WiFi',
'deviceConfig.phoneConnectXiaozhiHotspot': 'Điện thoại kết nối với điểm phát sóng xiaozhi',
'deviceConfig.selectTargetWifiNetwork': 'Chọn mạng WiFi mục tiêu',
'deviceConfig.enterWifiPasswordIfNeeded': 'Nhập mật khẩu WiFi nếu cần',
'deviceConfig.clickStartConfigAndWait': 'Nhấp Bắt đầu cấu hình và chờ',
'deviceConfig.afterConfigSuccessDeviceWillRestart': 'Sau khi cấu hình thành công, thiết bị sẽ tự động khởi động lại',
'deviceConfig.audioPlaybackError': 'Lỗi phát âm thanh',
'deviceConfig.playbackFailed': 'Phát thất bại',
}
+2 -6
View File
@@ -46,13 +46,9 @@ export default {
'retrievePassword.mobileCaptchaPlaceholder': '請輸入手機驗證碼',
'retrievePassword.newPasswordPlaceholder': '請輸入新密碼',
'retrievePassword.confirmNewPasswordPlaceholder': '請確認新密碼',
'retrievePassword.confirmPasswordPlaceholder': '請確認新密碼',
'retrievePassword.captchaSendSuccess': '驗證碼發送成功',
'retrievePassword.passwordUpdateSuccess': '密碼更新成功',
'retrievePassword.getCaptcha': '獲取驗證碼',
'retrievePassword.getMobileCaptcha': '獲取驗證碼',
'retrievePassword.resend': '重新發送',
'retrievePassword.resetPasswordButton': '重置密碼',
'retrievePassword.captchaSendSuccess': '驗證碼發送成功',
'retrievePassword.passwordUpdateSuccess': '密碼重置成功',
'retrievePassword.resetButton': '重置密碼',
'retrievePassword.goToLogin': '返回登錄',
@@ -235,7 +235,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.8.7'
version: '0.8.8'
}),
showCancel: false,
confirmText: t('common.confirm'),
+1 -2
View File
@@ -1,9 +1,8 @@
import { ref } from 'vue'
import { ref } from 'vue'
import { defineStore } from 'pinia'
// 支持的语言类型
export type Language = 'zh_CN' | 'en' | 'zh_TW'
export type Language = 'zh_CN' | 'en' | 'zh_TW' | 'de' | 'vi'
export interface LangStore {
currentLang: Language
@@ -13,7 +13,9 @@
<div class="function-column">
<div class="column-header">
<h4 class="column-title">{{ $t('functionDialog.unselectedFunctions') }}</h4>
<el-button type="text" @click="selectAll" class="select-all-btn">{{ $t('functionDialog.selectAll') }}</el-button>
<el-button type="text" @click="selectAll" class="select-all-btn">
{{ $t('functionDialog.selectAll') }}
</el-button>
</div>
<div class="function-list">
<div v-if="unselected.length">
@@ -21,7 +23,7 @@
<el-checkbox :label="func.name" v-model="selectedNames" @change="(val) => handleCheckboxChange(func, val)"
@click.native.stop></el-checkbox>
<div class="func-tag" @click="handleFunctionClick(func)">
<div class="color-dot" :style="{ backgroundColor: getFunctionColor(func.name) }"></div>
<div class="color-dot"></div>
<span>{{ func.name }}</span>
</div>
</div>
@@ -36,7 +38,9 @@
<div class="function-column">
<div class="column-header">
<h4 class="column-title">{{ $t('functionDialog.selectedFunctions') }}</h4>
<el-button type="text" @click="deselectAll" class="select-all-btn">{{ $t('functionDialog.selectAll') }}</el-button>
<el-button type="text" @click="deselectAll" class="select-all-btn">
{{ $t('functionDialog.selectAll') }}
</el-button>
</div>
<div class="function-list">
<div v-if="selectedList.length > 0">
@@ -44,7 +48,7 @@
<el-checkbox :label="func.name" v-model="selectedNames" @change="(val) => handleCheckboxChange(func, val)"
@click.native.stop></el-checkbox>
<div class="func-tag" @click="handleFunctionClick(func)">
<div class="color-dot" :style="{ backgroundColor: getFunctionColor(func.name) }"></div>
<div class="color-dot"></div>
<span>{{ func.name }}</span>
</div>
</div>
@@ -57,7 +61,9 @@
<!-- 右侧参数配置 -->
<div class="params-column">
<h4 v-if="currentFunction" class="column-title">{{ $t('functionDialog.paramConfig') }} - {{ currentFunction.name }}</h4>
<h4 v-if="currentFunction" class="column-title">
{{ $t('functionDialog.paramConfig') }} - {{ currentFunction.name }}
</h4>
<div v-if="currentFunction" class="params-container">
<el-form :model="currentFunction" class="param-form">
<!-- 遍历 fieldsMeta而不是 params keys -->
@@ -119,8 +125,8 @@
<el-input v-model="mcpUrl" readonly class="url-input">
<template #suffix>
<el-button @click="copyUrl" class="inner-copy-btn" icon="el-icon-document-copy">
{{ $t('functionDialog.copy') }}
</el-button>
{{ $t('functionDialog.copy') }}
</el-button>
</template>
</el-input>
</div>
@@ -191,10 +197,6 @@ export default {
selectedNames: [],
currentFunction: null,
modifiedFunctions: {},
functionColorMap: [
'#FF6B6B', '#4ECDC4', '#45B7D1',
'#96CEB4', '#FFEEAD', '#D4A5A5', '#A2836E'
],
tempFunctions: {},
// 添加一个标志位来跟踪是否已经保存
hasSaved: false,
@@ -405,10 +407,6 @@ export default {
// 通知父组件对话框已关闭且已保存
this.$emit('dialog-closed', true);
},
getFunctionColor(name) {
const hash = [...name].reduce((acc, char) => acc + char.charCodeAt(0), 0);
return this.functionColorMap[hash % this.functionColorMap.length];
},
fieldRemark(field) {
let description = (field && field.label) ? field.label : '';
if (field.default) {
@@ -527,6 +525,7 @@ export default {
flex-shrink: 0;
width: 8px;
height: 8px;
background-color: #5778ff;
margin-right: 8px;
border-radius: 50%;
}
@@ -238,6 +238,10 @@ export default {
return this.$t("language.zhTW");
case "en":
return this.$t("language.en");
case "de":
return this.$t("language.de");
case "vi":
return this.$t("language.vi");
default:
return this.$t("language.zhCN");
}
@@ -261,6 +265,14 @@ export default {
label: this.$t("language.en"),
value: "en",
},
{
label: this.$t("language.de"),
value: "de",
},
{
label: this.$t("language.vi"),
value: "vi",
},
],
},
{
@@ -6,7 +6,7 @@
</el-form-item>
<el-form-item :label="$t('knowledgeBaseDialog.description')" prop="description">
<el-input v-model="form.description" :placeholder="$t('knowledgeBaseDialog.descriptionPlaceholder')"
type="textarea" :rows="4" maxlength="200" show-word-limit></el-input>
type="textarea" :rows="4" maxlength="300" show-word-limit></el-input>
</el-form-item>
<el-form-item :label="$t('knowledgeBaseDialog.ragModel')" prop="ragModelId">
<el-select v-model="form.ragModelId" :placeholder="$t('knowledgeBaseDialog.ragModelPlaceholder')" clearable
@@ -73,7 +73,12 @@ export default {
],
description: [
{
max: 200,
required: true,
message: this.$t("knowledgeBaseDialog.descriptionRequired"),
trigger: "blur"
},
{
max: 300,
message: this.$t("knowledgeBaseDialog.descriptionLength"),
trigger: "blur"
}
File diff suppressed because it is too large Load Diff
+9 -7
View File
@@ -639,10 +639,12 @@ export default {
'language.zhCN': '中文简体',
'language.zhTW': '中文繁體',
'language.en': 'English',
'language.de': 'Deutsch',
'language.vi': 'Tiếng Việt',
// Home page text
'home.addAgent': 'Add Agent',
'home.greeting': 'Hi Jarvis',
'home.greeting': 'Hi XiaoZhi',
'home.wish': "Let's have a wonderful day!",
'home.languageModel': 'LLM',
'home.voiceModel': 'TTS',
@@ -992,7 +994,6 @@ export default {
'agentTemplateManagement.templateName': 'Template Name',
'agentTemplateManagement.action': 'Action',
'agentTemplateManagement.createTemplate': 'Create Template',
'templateQuickConfig.newTemplate': 'New Template',
'agentTemplateManagement.editTemplate': 'Edit Template',
'agentTemplateManagement.deleteTemplate': 'Delete Template',
'agentTemplateManagement.deleteSuccess': 'Template deleted successfully',
@@ -1011,7 +1012,6 @@ export default {
'agentTemplateManagement.deleteFailed': 'Template deletion failed',
'agentTemplateManagement.batchDeleteFailed': 'Template batch deletion failed',
'agentTemplateManagement.deleteBackendError': 'Deletion failed, please check if the backend service is normal',
'agentTemplateManagement.deleteCancelled': 'Deletion cancelled',
// templateQuickConfig
'templateQuickConfig.title': 'Module Quick Configuration',
@@ -1021,13 +1021,14 @@ export default {
'templateQuickConfig.agentSettings.systemPromptPlaceholder': 'Please enter ntroduction',
'templateQuickConfig.saveConfig': 'Save Configuration',
'templateQuickConfig.resetConfig': 'Reset Configuration',
'templateQuickConfig.configSaved': 'Configuration saved successfully',
'templateQuickConfig.configReset': 'Configuration has been reset',
'templateQuickConfig.saveSuccess': 'Configuration saved successfully',
'templateQuickConfig.resetSuccess': 'Configuration reset successfully',
'templateQuickConfig.confirmReset': 'Are you sure you want to reset the configuration?',
'templateQuickConfig.saveFailed': 'Configuration save failed',
'templateQuickConfig.confirm': 'Confirm',
'templateQuickConfig.cancel': 'Cancel',
'templateQuickConfig.templateNotFound': 'Template not found',
'templateQuickConfig.newTemplate': 'New Template',
'warning': 'Warning',
'info': 'Info',
'common.networkError': 'Network request failed',
@@ -1183,7 +1184,7 @@ export default {
'knowledgeBaseDialog.descriptionLengthLimit': 'Knowledge base description cannot exceed 200 characters',
// Knowledge Base Management page new view button text
'knowledgeBaseManagement.view': 'View',
'knowledgeBaseManagement.view': 'Manage Files',
// Knowledge File Upload page text
'knowledgeFileUpload.back': 'Back',
@@ -1215,7 +1216,7 @@ export default {
'knowledgeFileUpload.statusProcessing': 'Processing',
'knowledgeFileUpload.statusCancelled': 'Cancelled',
'knowledgeFileUpload.statusCompleted': 'Completed',
'knowledgeFileUpload.statusFailed': 'Parse Failed',
'knowledgeFileUpload.statusFailed': 'Failed',
'knowledgeFileUpload.uploadSuccess': 'Document upload successful',
'knowledgeFileUpload.uploadFailed': 'Document upload failed',
'knowledgeFileUpload.parseSuccess': 'Document parse successful',
@@ -1259,4 +1260,5 @@ export default {
'knowledgeFileUpload.comprehensiveSimilarity': 'Comprehensive Similarity',
'knowledgeFileUpload.content': 'Content:',
'knowledgeFileUpload.testQuestionRequired': 'Please enter test question',
'knowledgeBaseDialog.descriptionRequired': 'Please enter knowledge base description',
}
+11 -1
View File
@@ -3,6 +3,8 @@ import VueI18n from 'vue-i18n';
import zhCN from './zh_CN';
import zhTW from './zh_TW';
import en from './en';
import de from './de';
import vi from './vi';
Vue.use(VueI18n);
@@ -19,6 +21,12 @@ const getDefaultLanguage = () => {
}
return 'zh_CN';
}
if (browserLang.indexOf('de') === 0) {
return 'de';
}
if (browserLang.indexOf('vi') === 0) {
return 'vi';
}
return 'en';
};
@@ -28,7 +36,9 @@ const i18n = new VueI18n({
messages: {
'zh_CN': zhCN,
'zh_TW': zhTW,
'en': en
'en': en,
'de': de,
'vi': vi
}
});
File diff suppressed because it is too large Load Diff
+8 -6
View File
@@ -639,6 +639,8 @@ export default {
'language.zhCN': '中文简体',
'language.zhTW': '中文繁體',
'language.en': 'English',
'language.de': 'Deutsch',
'language.vi': 'Tiếng Việt',
// 首页文本
'home.addAgent': '添加智能体',
@@ -991,8 +993,6 @@ export default {
'agentTemplateManagement.title': '默认角色管理',
'agentTemplateManagement.templateName': '模板名称',
'agentTemplateManagement.action': '操作',
'templateQuickConfig.saveSuccess': '配置保存成功',
'templateQuickConfig.saveFailed': '配置保存失败',
'agentTemplateManagement.createTemplate': '创建模板',
'agentTemplateManagement.editTemplate': '编辑模板',
'agentTemplateManagement.deleteTemplate': '删除模板',
@@ -1021,13 +1021,14 @@ export default {
'templateQuickConfig.agentSettings.systemPromptPlaceholder': '请输入角色介绍',
'templateQuickConfig.saveConfig': '保存配置',
'templateQuickConfig.resetConfig': '重置配置',
'templateQuickConfig.saveSuccess': '保存成功',
'templateQuickConfig.resetSuccess': '重置成功',
'templateQuickConfig.confirmReset': '确定要重置配置吗?',
'templateQuickConfig.saveFailed': '配置保存失败',
'templateQuickConfig.confirm': '确定',
'templateQuickConfig.cancel': '取消',
'templateQuickConfig.templateNotFound': '未找到指定模板',
'templateQuickConfig.newTemplate': '新模板',
'templateQuickConfig.saveSuccess': '保存成功',
'templateQuickConfig.resetSuccess': '重置成功',
'warning': '警告',
'info': '提示',
'common.networkError': '网络请求失败',
@@ -1183,7 +1184,7 @@ export default {
'knowledgeBaseDialog.descriptionLengthLimit': '知识库描述不能超过200个字符',
// 知识库管理页面新增查看按钮文本
'knowledgeBaseManagement.view': '查看',
'knowledgeBaseManagement.view': '管理文件',
// 上传文件页面文本
'knowledgeFileUpload.back': '返回',
@@ -1215,7 +1216,7 @@ export default {
'knowledgeFileUpload.statusProcessing': '处理中',
'knowledgeFileUpload.statusCancelled': '已取消',
'knowledgeFileUpload.statusCompleted': '已完成',
'knowledgeFileUpload.statusFailed': '解析失败',
'knowledgeFileUpload.statusFailed': '失败',
'knowledgeFileUpload.uploadSuccess': '文档上传成功',
'knowledgeFileUpload.uploadFailed': '文档上传失败',
'knowledgeFileUpload.parseSuccess': '文档解析成功',
@@ -1259,4 +1260,5 @@ export default {
'knowledgeFileUpload.comprehensiveSimilarity': '综合相似度',
'knowledgeFileUpload.content': '内容:',
'knowledgeFileUpload.testQuestionRequired': '请输入测试问题',
'knowledgeBaseDialog.descriptionRequired': '请输入知识库描述',
}
+6 -3
View File
@@ -639,6 +639,8 @@ export default {
'language.zhCN': '中文简体',
'language.zhTW': '中文繁體',
'language.en': 'English',
'language.de': 'Deutsch',
'language.vi': 'Tiếng Việt',
// 首頁文本
'home.addAgent': '添加智能體',
@@ -992,6 +994,7 @@ export default {
'agentTemplateManagement.templateName': '模板名稱',
'agentTemplateManagement.action': '操作',
'templateQuickConfig.saveSuccess': '配置保存成功',
'templateQuickConfig.resetSuccess': '配置重置成功',
'templateQuickConfig.saveFailed': '配置保存失敗',
'agentTemplateManagement.createTemplate': '建立模板',
'agentTemplateManagement.editTemplate': '編輯模板',
@@ -1021,8 +1024,6 @@ export default {
'templateQuickConfig.agentSettings.systemPromptPlaceholder': '請輸入角色介紹',
'templateQuickConfig.saveConfig': '保存配置',
'templateQuickConfig.resetConfig': '重置配置',
'templateQuickConfig.configSaved': '配置保存成功',
'templateQuickConfig.configReset': '配置已重置',
'templateQuickConfig.confirmReset': '確定要重置配置嗎?',
'templateQuickConfig.confirm': '確定',
'templateQuickConfig.cancel': '取消',
@@ -1183,7 +1184,7 @@ export default {
'knowledgeBaseDialog.descriptionLengthLimit': '知識庫描述不能超過200個字符',
// 知識庫管理頁面查看按鈕文本
'knowledgeBaseManagement.view': '查看',
'knowledgeBaseManagement.view': '管理文件',
// 知識庫文件上傳頁面文本
'knowledgeFileUpload.back': '返回',
@@ -1215,6 +1216,7 @@ export default {
'knowledgeFileUpload.statusProcessing': '處理中',
'knowledgeFileUpload.statusCancelled': '已取消',
'knowledgeFileUpload.statusCompleted': '已完成',
'knowledgeFileUpload.statusFailed': '失敗',
'knowledgeFileUpload.uploadSuccess': '文檔上傳成功',
'knowledgeFileUpload.uploadFailed': '文檔上傳失敗',
'knowledgeFileUpload.parseSuccess': '文檔解析成功',
@@ -1258,4 +1260,5 @@ export default {
'knowledgeFileUpload.comprehensiveSimilarity': '綜合相似度',
'knowledgeFileUpload.content': '內容:',
'knowledgeFileUpload.testQuestionRequired': '請輸入測試問題',
'knowledgeBaseDialog.descriptionRequired': '請輸入知识库描述',
}
@@ -273,11 +273,9 @@ export default {
handleSubmit: function(form) {
console.log('handleSubmit called with form:', form);
if (form.id) {
// - 使dataset_idform
console.log('Editing knowledge base:', form.datasetId);
Api.knowledgeBase.updateKnowledgeBase(form.datasetId, form, (res) => {
console.log('Update response:', res);
// res.data.code res.code
if (res.data && res.data.code === 0) {
this.dialogVisible = false;
this.fetchKnowledgeBaseList();
@@ -285,8 +283,15 @@ export default {
} else {
this.$message.error(res.data?.msg || this.$t('knowledgeBaseManagement.updateFailed'));
}
}, () => {
this.$message.error(this.$t('knowledgeBaseManagement.updateFailed'));
}, (err) => {
console.log('Error callback received:', err);
//
if (err && err.data) {
console.log('后端返回错误消息:', err.data.msg || err.msg);
this.$message.error(err.data.msg || err.msg || this.$t('knowledgeBaseManagement.updateFailed'));
} else {
this.$message.error(this.$t('knowledgeBaseManagement.updateFailed'));
}
});
} else {
// - id
@@ -303,6 +308,8 @@ export default {
this.dialogVisible = false;
this.fetchKnowledgeBaseList();
this.$message.success(this.$t('knowledgeBaseManagement.addSuccess'));
} else {
this.$message.error(res.data?.msg || this.$t('knowledgeBaseManagement.addFailed'));
}
}, (err) => {
console.log('Error callback received:', err);
@@ -338,8 +345,15 @@ export default {
} else {
this.$message.error(res.data?.msg || this.$t('knowledgeBaseManagement.deleteFailed'));
}
}, () => {
this.$message.error(this.$t('knowledgeBaseManagement.deleteFailed'));
}, (err) => {
console.log('Error callback received:', err);
//
if (err && err.data) {
console.log('后端返回错误消息:', err.data.msg || err.msg);
this.$message.error(err.data.msg || err.msg || this.$t('knowledgeBaseManagement.deleteFailed'));
} else {
this.$message.error(this.$t('knowledgeBaseManagement.deleteFailed'));
}
});
}).catch(() => {
this.$message({
@@ -365,8 +379,15 @@ export default {
} else {
this.$message.error(res.data?.msg || this.$t('knowledgeBaseManagement.deleteFailed'));
}
}, () => {
this.$message.error(this.$t('knowledgeBaseManagement.deleteFailed'));
}, (err) => {
console.log('Error callback received:', err);
//
if (err && err.data) {
console.log('后端返回错误消息:', err.data.msg || err.msg);
this.$message.error(err.data.msg || err.msg || this.$t('knowledgeBaseManagement.deleteFailed'));
} else {
this.$message.error(this.$t('knowledgeBaseManagement.deleteFailed'));
}
});
}).catch(() => {
this.$message({
@@ -401,7 +401,13 @@ export default {
},
(err) => {
this.loading = false;
this.$message.error(this.$t('knowledgeFileUpload.getListFailed'));
console.log('Error callback received:', err);
if (err && err.data) {
console.log('后端返回错误消息:', err.data.msg || err.msg);
this.$message.error(err.data.msg || err.msg || this.$t('knowledgeFileUpload.getListFailed'));
} else {
this.$message.error(this.$t('knowledgeFileUpload.getListFailed'));
}
console.error('获取文档列表失败:', err);
this.fileList = [];
this.total = 0;
@@ -657,7 +663,12 @@ export default {
}
},
(err) => {
reject({ success: false, fileName: file.name, error: this.$t('knowledgeFileUpload.uploadFailed') });
//
if (err && err.data) {
reject({ success: false, fileName: file.name, error: err.data.msg || err.msg || this.$t('knowledgeFileUpload.uploadFailed') });
} else {
reject({ success: false, fileName: file.name, error: this.$t('knowledgeFileUpload.uploadFailed') });
}
console.error('上传文档失败:', err);
}
);
@@ -718,7 +729,12 @@ export default {
},
(err) => {
this.uploading = false;
this.$message.error(this.$t('knowledgeFileUpload.uploadFailed'));
//
if (err && err.data) {
this.$message.error(err.data.msg || err.msg || this.$t('knowledgeFileUpload.uploadFailed'));
} else {
this.$message.error(this.$t('knowledgeFileUpload.uploadFailed'));
}
console.error('上传文档失败:', err);
}
);
@@ -751,7 +767,12 @@ export default {
}
},
(err) => {
this.$message.error(this.$t('knowledgeFileUpload.parseFailed'));
//
if (err && err.data) {
this.$message.error(err.data.msg || err.msg || this.$t('knowledgeFileUpload.parseFailed'));
} else {
this.$message.error(this.$t('knowledgeFileUpload.parseFailed'));
}
console.error('解析文档失败:', err);
}
);
@@ -784,7 +805,12 @@ export default {
}
},
(err) => {
this.$message.error(this.$t('knowledgeFileUpload.deleteFailed'));
//
if (err && err.data) {
this.$message.error(err.data.msg || err.msg || this.$t('knowledgeFileUpload.deleteFailed'));
} else {
this.$message.error(this.$t('knowledgeFileUpload.deleteFailed'));
}
console.error('删除文档失败:', err);
}
);
@@ -829,7 +855,12 @@ export default {
}
},
(err) => {
reject(this.$t('knowledgeFileUpload.deleteFailed'));
//
if (err && err.data) {
reject(err.data.msg || err.msg || this.$t('knowledgeFileUpload.deleteFailed'));
} else {
reject(this.$t('knowledgeFileUpload.deleteFailed'));
}
console.error('删除文档失败:', err);
}
);
@@ -938,7 +969,12 @@ export default {
},
(err) => {
this.sliceLoading = false;
this.$message.error('获取切片列表失败');
//
if (err && err.data) {
this.$message.error(err.data.msg || err.msg || '获取切片列表失败');
} else {
this.$message.error('获取切片列表失败');
}
console.error('获取切片列表失败:', err);
this.sliceList = [];
this.sliceTotal = 0;
@@ -1055,7 +1091,12 @@ export default {
},
(err) => {
this.retrievalTestLoading = false;
this.$message.error('召回测试失败');
//
if (err && err.data) {
this.$message.error(err.data.msg || err.msg || '召回测试失败');
} else {
this.$message.error('召回测试失败');
}
console.error('召回测试失败:', err);
}
);
@@ -42,7 +42,7 @@
</template>
</el-table-column>
<el-table-column :label="$t('voiceClone.Details')" align="center" width="80">
<el-table-column :label="$t('voiceClone.Details')" align="center" width="120">
<template slot-scope="scope">
<el-tooltip :content="getTooltipContent(scope.row)" placement="top">
<el-button size="mini" type="text" icon="el-icon-info"
+4 -2
View File
@@ -21,6 +21,8 @@
font-size: 25px;
text-align: left;
color: #3d4566;
white-space: nowrap;
flex-shrink: 0;
}
.login-welcome {
@@ -36,11 +38,11 @@
position: absolute;
top: 50%;
transform: translateY(-50%);
right: 18%;
right: 15%;
background-color: #fff;
border-radius: 20px;
padding: 35px 0;
width: 450px;
width: 550px;
box-sizing: border-box;
}
+10
View File
@@ -49,6 +49,12 @@
<el-dropdown-item @click.native="changeLanguage('en')">
{{ $t("language.en") }}
</el-dropdown-item>
<el-dropdown-item @click.native="changeLanguage('de')">
{{ $t("language.de") }}
</el-dropdown-item>
<el-dropdown-item @click.native="changeLanguage('vi')">
{{ $t("language.vi") }}
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</div>
@@ -177,6 +183,10 @@ export default {
return this.$t("language.zhTW");
case "en":
return this.$t("language.en");
case "de":
return this.$t("language.de");
case "vi":
return this.$t("language.vi");
default:
return this.$t("language.zhCN");
}
+16 -18
View File
@@ -177,11 +177,8 @@
<div slot="content">
<div><strong>功能名称:</strong> {{ func.name }}</div>
</div>
<div
class="icon-dot"
:style="{ backgroundColor: getFunctionColor(func.name) }"
>
{{ func.name.charAt(0) }}
<div class="icon-dot">
{{ getFunctionDisplayChar(func.name) }}
</div>
</el-tooltip>
<el-button
@@ -323,15 +320,6 @@ export default {
voiceDetails: {}, //
showFunctionDialog: false,
currentFunctions: [],
functionColorMap: [
"#FF6B6B",
"#4ECDC4",
"#45B7D1",
"#96CEB4",
"#FFEEAD",
"#D4A5A5",
"#A2836E",
],
allFunctions: [],
originalFunctions: [],
playingVoice: false,
@@ -596,9 +584,18 @@ export default {
}
});
},
getFunctionColor(name) {
const hash = [...name].reduce((acc, char) => acc + char.charCodeAt(0), 0);
return this.functionColorMap[hash % this.functionColorMap.length];
getFunctionDisplayChar(name) {
if (!name || name.length === 0) return '';
for (let i = 0; i < name.length; i++) {
const char = name[i];
if (/[\u4e00-\u9fa5a-zA-Z0-9]/.test(char)) {
return char;
}
}
//
return name.charAt(0);
},
showFunctionIcons(type) {
return type === "Intent" && this.form.model.intentModelId !== "Intent_nointent";
@@ -1228,11 +1225,12 @@ export default {
display: inline-flex;
align-items: center;
justify-content: center;
color: white;
color: #5778ff;
font-weight: bold;
font-size: 12px;
margin-right: 8px;
position: relative;
background-color: #e6ebff;
}
::v-deep .el-form-item__label {
@@ -0,0 +1,10 @@
{
"permissions": {
"allow": [
"Bash(tree:*)",
"Bash(find:*)"
],
"deny": [],
"ask": []
}
}
@@ -63,6 +63,7 @@
- 查询**详细农历信息**(宜忌、八字、节气等)。
- 除上述例外外的**任何其他信息或操作请求**(如查新闻、订闹钟、算数学、查非本地天气等)。
- 我已经给你装了摄像头,如果用户说“拍照”,你需要调用self_camera_take_photo工具说一下你看到了什么。默认question的参数是“描述一下看到的物品”
- 当工具列表包含search_from_ragflow,说明可以使用知识库,你应该结合用户上下文意图并结合知识库的使用描述,推断是否要调用调用知识库。
</tool_calling>
<context>
+1 -1
View File
@@ -5,7 +5,7 @@ from config.config_loader import load_config
from config.settings import check_config_file
from datetime import datetime
SERVER_VERSION = "0.8.7"
SERVER_VERSION = "0.8.8"
_logger_initialized = False
@@ -55,7 +55,6 @@ class IntentProvider(IntentProviderBase):
prompt = (
"【严格格式要求】你必须只能返回JSON格式,绝对不能返回任何自然语言!\n\n"
"你是一个意图识别助手。请分析用户的最后一句话,判断用户意图并调用相应的函数。\n\n"
"【重要规则】以下类型的查询请直接返回result_for_context,无需调用函数:\n"
"- 询问当前时间(如:现在几点、当前时间、查询时间等)\n"
"- 询问今天日期(如:今天几号、今天星期几、今天是什么日期等)\n"
@@ -202,7 +201,7 @@ class IntentProvider(IntentProviderBase):
# 记录LLM调用完成时间
llm_time = time.time() - llm_start_time
logger.bind(tag=TAG).debug(
f"LLM意图识别完成, 模型: {model_info}, 调用耗时: {llm_time:.4f}"
f"外挂的大模型意图识别完成, 模型: {model_info}, 调用耗时: {llm_time:.4f}"
)
# 记录后处理开始时间
@@ -238,8 +237,10 @@ class IntentProvider(IntentProviderBase):
# 处理不同类型的意图
if function_name == "result_for_context":
# 处理基础信息查询,直接从context构建结果
logger.bind(tag=TAG).info("检测到result_for_context意图,将使用上下文信息直接回答")
logger.bind(tag=TAG).info(
"检测到result_for_context意图,将使用上下文信息直接回答"
)
elif function_name == "continue_chat":
# 处理普通对话
# 保留非工具相关的消息
@@ -249,7 +250,7 @@ class IntentProvider(IntentProviderBase):
if msg.role not in ["tool", "function"]
]
conn.dialogue.dialogue = clean_history
else:
# 处理函数调用
logger.bind(tag=TAG).info(f"检测到函数调用意图: {function_name}")
@@ -21,22 +21,22 @@ class LLMProvider(LLMProviderBase):
self.timeout = int(timeout) if timeout else 300
param_defaults = {
"max_tokens": (500, int),
"temperature": (0.7, lambda x: round(float(x), 1)),
"top_p": (1.0, lambda x: round(float(x), 1)),
"frequency_penalty": (0, lambda x: round(float(x), 1)),
"max_tokens": int,
"temperature": lambda x: round(float(x), 1),
"top_p": lambda x: round(float(x), 1),
"frequency_penalty": lambda x: round(float(x), 1),
}
for param, (default, converter) in param_defaults.items():
for param, converter in param_defaults.items():
value = config.get(param)
try:
setattr(
self,
param,
converter(value) if value not in (None, "") else default,
converter(value) if value not in (None, "") else None,
)
except (ValueError, TypeError):
setattr(self, param, default)
setattr(self, param, None)
logger.debug(
f"意图识别参数初始化: {self.temperature}, {self.max_tokens}, {self.top_p}, {self.frequency_penalty}"
@@ -59,17 +59,25 @@ class LLMProvider(LLMProviderBase):
try:
dialogue = self.normalize_dialogue(dialogue)
responses = self.client.chat.completions.create(
model=self.model_name,
messages=dialogue,
stream=True,
max_tokens=kwargs.get("max_tokens", self.max_tokens),
temperature=kwargs.get("temperature", self.temperature),
top_p=kwargs.get("top_p", self.top_p),
frequency_penalty=kwargs.get(
"frequency_penalty", self.frequency_penalty
),
)
request_params = {
"model": self.model_name,
"messages": dialogue,
"stream": True,
}
# 添加可选参数,只有当参数不为None时才添加
optional_params = {
"max_tokens": kwargs.get("max_tokens", self.max_tokens),
"temperature": kwargs.get("temperature", self.temperature),
"top_p": kwargs.get("top_p", self.top_p),
"frequency_penalty": kwargs.get("frequency_penalty", self.frequency_penalty),
}
for key, value in optional_params.items():
if value is not None:
request_params[key] = value
responses = self.client.chat.completions.create(**request_params)
is_active = True
for chunk in responses:
@@ -91,13 +99,29 @@ class LLMProvider(LLMProviderBase):
except Exception as e:
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
def response_with_functions(self, session_id, dialogue, functions=None):
def response_with_functions(self, session_id, dialogue, functions=None, **kwargs):
try:
dialogue = self.normalize_dialogue(dialogue)
stream = self.client.chat.completions.create(
model=self.model_name, messages=dialogue, stream=True, tools=functions
)
request_params = {
"model": self.model_name,
"messages": dialogue,
"stream": True,
"tools": functions,
}
optional_params = {
"max_tokens": kwargs.get("max_tokens", self.max_tokens),
"temperature": kwargs.get("temperature", self.temperature),
"top_p": kwargs.get("top_p", self.top_p),
"frequency_penalty": kwargs.get("frequency_penalty", self.frequency_penalty),
}
for key, value in optional_params.items():
if value is not None:
request_params[key] = value
stream = self.client.chat.completions.create(**request_params)
for chunk in stream:
if getattr(chunk, "choices", None):
@@ -240,7 +240,7 @@ class TTSProvider(TTSProviderBase):
self.conn.sentence_id = uuid.uuid4().hex
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
logger.bind(tag=TAG).debu("开始启动TTS会话...")
logger.bind(tag=TAG).debug("开始启动TTS会话...")
future = asyncio.run_coroutine_threadsafe(
self.start_session(self.conn.sentence_id),
loop=self.conn.loop,
+25 -3
View File
@@ -224,7 +224,10 @@ def check_ffmpeg_installed() -> bool:
error_msg.append("⚠️ 发现缺少依赖库:libiconv.so.2")
error_msg.append("解决方法:在当前 conda 环境中执行:")
error_msg.append(" conda install -c conda-forge libiconv\n")
elif "no such file or directory" in stderr_output and "ffmpeg" in stderr_output.lower():
elif (
"no such file or directory" in stderr_output
and "ffmpeg" in stderr_output.lower()
):
error_msg.append("⚠️ 系统未找到 ffmpeg 可执行文件。")
error_msg.append("解决方法:在当前 conda 环境中执行:")
error_msg.append(" conda install -c conda-forge ffmpeg\n")
@@ -245,7 +248,9 @@ def extract_json_from_string(input_string):
return None
def audio_to_data_stream(audio_file_path, is_opus=True, callback: Callable[[Any], Any]=None) -> None:
def audio_to_data_stream(
audio_file_path, is_opus=True, callback: Callable[[Any], Any] = None
) -> None:
# 获取文件后缀名
file_type = os.path.splitext(audio_file_path)[1]
if file_type:
@@ -262,6 +267,7 @@ def audio_to_data_stream(audio_file_path, is_opus=True, callback: Callable[[Any]
raw_data = audio.raw_data
pcm_to_data_stream(raw_data, is_opus, callback)
def audio_to_data(audio_file_path: str, is_opus: bool = True) -> list[bytes]:
"""
将音频文件转换为Opus/PCM编码的帧列表
@@ -313,7 +319,10 @@ def audio_to_data(audio_file_path: str, is_opus: bool = True) -> list[bytes]:
return datas
def audio_bytes_to_data_stream(audio_bytes, file_type, is_opus, callback: Callable[[Any], Any]) -> None:
def audio_bytes_to_data_stream(
audio_bytes, file_type, is_opus, callback: Callable[[Any], Any]
) -> None:
"""
直接用音频二进制数据转为opus/pcm数据支持wavmp3p3
"""
@@ -357,6 +366,7 @@ def pcm_to_data_stream(raw_data, is_opus=True, callback: Callable[[Any], Any] =
frame_data = chunk if isinstance(chunk, bytes) else bytes(chunk)
callback(frame_data)
def opus_datas_to_wav_bytes(opus_datas, sample_rate=16000, channels=1):
"""
将opus帧列表解码为wav字节流
@@ -383,6 +393,7 @@ def opus_datas_to_wav_bytes(opus_datas, sample_rate=16000, channels=1):
wf.writeframes(pcm_bytes)
return wav_buffer.getvalue()
def check_vad_update(before_config, new_config):
if (
new_config.get("selected_module") is None
@@ -456,6 +467,17 @@ def filter_sensitive_info(config: dict) -> dict:
filtered[k] = _filter_dict(v)
elif isinstance(v, list):
filtered[k] = [_filter_dict(i) if isinstance(i, dict) else i for i in v]
elif isinstance(v, str):
try:
json_data = json.loads(v)
if isinstance(json_data, dict):
filtered[k] = json.dumps(
_filter_dict(json_data), ensure_ascii=False
)
else:
filtered[k] = v
except (json.JSONDecodeError, TypeError):
filtered[k] = v
else:
filtered[k] = v
return filtered
+1 -1
View File
@@ -76,7 +76,7 @@ services:
- MYSQL_INITDB_ARGS="--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci"
# redis模块
xiaozhi-esp32-server-redis:
image: redis
image: redis:8.0
expose:
- 6379
container_name: xiaozhi-esp32-server-redis
@@ -84,11 +84,12 @@ def search_from_ragflow(conn, question=None):
else:
contents.append(str(content))
# 构建适合大模型的上下文内容(每段前加编号,段间两个换行)
context_text = "\n\n".join(
f"{i+1}. {c.strip()}" for i, c in enumerate(contents[:5])
)
if not context_text:
if contents:
# 组织知识库内容为引用模式
context_text = f"# 关于问题【{question}】查到知识库如下\n"
context_text += "```\n\n\n".join(contents[:5])
context_text += "\n```"
else:
context_text = "根据知识库查询结果,没有相关信息。"
return ActionResponse(Action.REQLLM, context_text, None)
+18 -15
View File
@@ -1,27 +1,30 @@
pyyml==0.0.2
#--------- 本项目推荐环境是python3.10,以下暂时不推荐升级的依赖
torch==2.2.2
silero_vad==6.0.0
websockets==14.2
opuslib_next==1.1.2
numpy==1.26.4
pydub==0.25.1
funasr==1.2.3
torchaudio==2.2.2
openai==2.6.1
numpy==1.26.4
#--------- cozepy0.20.0要求websockets<15.0.0,以下暂时不推荐升级的依赖
websockets==14.2
#--------- 以下是可升级的依赖
pyyml==0.0.2
silero_vad==6.1.0
opuslib_next==1.1.5
pydub==0.25.1
funasr==1.2.7
openai==2.7.1
google-generativeai==0.8.5
edge_tts==7.2.3
httpx==0.27.2
aiohttp==3.12.15
aiohttp_cors==0.7.0
ormsgpack==1.11.0
httpx==0.28.1
aiohttp==3.13.2
aiohttp_cors==0.8.1
ormsgpack==1.12.0
ruamel.yaml==0.18.16
loguru==0.7.3
requests==2.32.5
cozepy==0.19.0
cozepy==0.20.0
mem0ai==1.0.0
bs4==0.0.2
modelscope==1.23.2
sherpa_onnx==1.12.11
sherpa_onnx==1.12.15
mcp==1.20.0
cnlunar==0.2.0
PySocks==1.7.1
@@ -35,4 +38,4 @@ PyJWT==2.10.1
psutil==7.0.0
portalocker==3.2.0
Jinja2==3.1.6
vosk==0.3.44
vosk==0.3.44
File diff suppressed because it is too large Load Diff
@@ -1,503 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>小智语音服务测试</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.container {
background-color: #f5f5f5;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
}
button {
padding: 8px 15px;
margin-right: 10px;
border: none;
border-radius: 5px;
background-color: #4285f4;
color: white;
cursor: pointer;
transition: background-color 0.2s;
}
button:hover {
background-color: #3367d6;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
#status {
font-weight: bold;
}
#scriptStatus {
position: fixed;
top: 10px;
left: 50%;
transform: translateX(-50%);
padding: 15px;
border-radius: 5px;
display: block;
z-index: 100;
transition: all 0.3s ease;
}
#scriptStatus.info {
background-color: #e8f0fe;
color: #4285f4;
border-left: 4px solid #4285f4;
}
#scriptStatus.success {
background-color: #e6f4ea;
color: #0f9d58;
border-left: 4px solid #0f9d58;
}
#scriptStatus.error {
background-color: #fce8e6;
color: #db4437;
border-left: 4px solid #db4437;
}
#debugInfo {
margin-top: 20px;
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
font-family: monospace;
font-size: 12px;
max-height: 200px;
overflow-y: auto;
display: none;
}
#showDebug {
margin-top: 10px;
background-color: #f5f5f5;
color: #444;
font-size: 12px;
}
#audioMeter {
margin-top: 10px;
height: 20px;
background-color: #eee;
border-radius: 4px;
overflow: hidden;
display: none;
}
#audioLevel {
height: 100%;
width: 0%;
background-color: #4285f4;
transition: width 0.1s;
}
.conversation {
max-height: 300px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 5px;
padding: 10px;
background-color: white;
margin-top: 10px;
}
.message {
margin-bottom: 10px;
padding: 8px 12px;
border-radius: 8px;
max-width: 80%;
}
.user {
background-color: #e2f2ff;
margin-left: auto;
margin-right: 10px;
text-align: right;
}
.server {
background-color: #f0f0f0;
margin-right: auto;
margin-left: 10px;
}
#serverUrl {
flex-grow: 1;
padding: 8px;
border: 1px solid #ddd;
border-radius: 5px;
width: 60%;
margin-right: 10px;
}
#messageInput {
flex-grow: 1;
padding: 8px;
border: 1px solid #ddd;
border-radius: 5px;
width: 70%;
margin-right: 10px;
}
.section {
margin-bottom: 15px;
}
</style>
</head>
<body>
<div class="container">
<h2>小智语音服务测试</h2>
<div id="scriptStatus" class="info">正在加载Opus库...</div>
<div class="section">
<h3>WebSocket连接 <span id="connectionStatus">未连接</span></h3>
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<input type="text" id="serverUrl" value="ws://127.0.0.1:8000/xiaozhi/v1/" placeholder="WebSocket服务器地址">
<button id="connectButton">连接</button>
</div>
</div>
<div class="section">
<h3>录音测试</h3>
<button id="initAudio" style="background-color: #34a853;">初始化音频</button>
<button id="testMic" style="background-color: #fbbc05;">测试麦克风</button>
<p></p>
<button id="start" disabled>开始录音</button>
<button id="stop" disabled>停止录音</button>
<button id="play" disabled>播放录音</button>
<p>录音状态: <span id="status">待机,正在初始化...</span></p>
<div id="audioMeter">
<div id="audioLevel"></div>
</div>
</div>
<div class="section">
<h3>文本消息</h3>
<div style="display: flex; align-items: center;">
<input type="text" id="messageInput" placeholder="输入消息..." disabled>
<button id="sendTextButton" disabled>发送</button>
</div>
</div>
<div class="section">
<h3>会话记录</h3>
<div id="conversation" class="conversation"></div>
</div>
<button id="showDebug">显示/隐藏调试信息</button>
<div id="debugInfo"></div>
</div>
<script>
// 定义全局变量以跟踪库加载状态
window.opusLoaded = false;
window.startButton = document.getElementById("start");
window.stopButton = document.getElementById("stop");
window.playButton = document.getElementById("play");
window.statusLabel = document.getElementById("status");
window.debugInfo = document.getElementById("debugInfo");
window.audioContextReady = false;
window.testMicActive = false;
// 显示/隐藏调试信息
document.getElementById("showDebug").addEventListener("click", function() {
if (debugInfo.style.display === "none" || !debugInfo.style.display) {
debugInfo.style.display = "block";
this.textContent = "隐藏调试信息";
} else {
debugInfo.style.display = "none";
this.textContent = "显示调试信息";
}
});
// 添加初始化音频按钮事件
document.getElementById("initAudio").addEventListener("click", function() {
initializeAudioSystem();
});
// 添加测试麦克风按钮事件
document.getElementById("testMic").addEventListener("click", function() {
if (window.testMicActive) {
stopMicTest();
} else {
startMicTest();
}
});
// 初始化音频系统
function initializeAudioSystem() {
try {
log("初始化音频系统...");
// 创建临时AudioContext来触发用户授权
const tempContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: 16000,
latencyHint: 'interactive'
});
// 创建振荡器并播放短促的声音
const oscillator = tempContext.createOscillator();
const gain = tempContext.createGain();
gain.gain.value = 0.1; // 很小的音量
oscillator.connect(gain);
gain.connect(tempContext.destination);
oscillator.frequency.value = 440; // A4
oscillator.start();
// 0.2秒后停止
setTimeout(() => {
oscillator.stop();
// 关闭上下文
tempContext.close().then(() => {
log("音频系统初始化成功", "success");
updateScriptStatus("音频系统已激活", "success");
document.getElementById("initAudio").disabled = true;
document.getElementById("initAudio").textContent = "音频已初始化";
window.audioContextReady = true;
// 如果Opus已加载,启用开始录音按钮
if (window.opusLoaded) {
startButton.disabled = false;
}
});
}, 200);
} catch (err) {
log("初始化音频系统失败: " + err.message, "error");
updateScriptStatus("初始化音频失败: " + err.message, "error");
}
}
// 测试麦克风
function startMicTest() {
const audioMeter = document.getElementById("audioMeter");
const audioLevel = document.getElementById("audioLevel");
const testMicBtn = document.getElementById("testMic");
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
log("浏览器不支持麦克风访问", "error");
return;
}
log("开始麦克风测试...");
audioMeter.style.display = "block";
testMicBtn.textContent = "停止测试";
testMicBtn.style.backgroundColor = "#ea4335";
window.testMicActive = true;
// 创建音频上下文
const testContext = new (window.AudioContext || window.webkitAudioContext)();
window.testContext = testContext;
// 获取麦克风权限
navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true
}
})
.then(stream => {
log("已获取麦克风访问权限", "success");
// 保存流以便稍后关闭
window.testStream = stream;
// 创建音频分析器
const source = testContext.createMediaStreamSource(stream);
const analyser = testContext.createAnalyser();
analyser.fftSize = 256;
source.connect(analyser);
// 创建音量显示更新函数
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
function updateMeter() {
if (!window.testMicActive) return;
analyser.getByteFrequencyData(dataArray);
// 计算音量级别 (0-100)
let sum = 0;
for (let i = 0; i < bufferLength; i++) {
sum += dataArray[i];
}
const average = sum / bufferLength;
const level = Math.min(100, Math.max(0, average * 2));
// 更新音量计
audioLevel.style.width = level + "%";
// 如果有声音,记录日志
if (level > 10) {
log(`检测到声音: ${level.toFixed(1)}%`);
}
// 循环更新
window.testMicAnimationFrame = requestAnimationFrame(updateMeter);
}
// 开始更新
updateMeter();
})
.catch(err => {
log("麦克风测试失败: " + err.message, "error");
window.testMicActive = false;
testMicBtn.textContent = "测试麦克风";
testMicBtn.style.backgroundColor = "#fbbc05";
audioMeter.style.display = "none";
});
}
// 停止麦克风测试
function stopMicTest() {
const audioMeter = document.getElementById("audioMeter");
const testMicBtn = document.getElementById("testMic");
log("停止麦克风测试");
window.testMicActive = false;
testMicBtn.textContent = "测试麦克风";
testMicBtn.style.backgroundColor = "#fbbc05";
// 停止分析器动画
if (window.testMicAnimationFrame) {
cancelAnimationFrame(window.testMicAnimationFrame);
}
// 停止麦克风流
if (window.testStream) {
window.testStream.getTracks().forEach(track => track.stop());
}
// 关闭测试上下文
if (window.testContext) {
window.testContext.close();
}
// 隐藏音量计
audioMeter.style.display = "none";
}
// 添加调试日志
function log(message, type = "info") {
console.log(message);
const time = new Date().toLocaleTimeString();
const entry = document.createElement("div");
entry.textContent = `[${time}] ${message}`;
if (type === "error") {
entry.style.color = "#db4437";
} else if (type === "success") {
entry.style.color = "#0f9d58";
}
debugInfo.appendChild(entry);
debugInfo.scrollTop = debugInfo.scrollHeight;
}
// 更新脚本状态显示
function updateScriptStatus(message, type) {
const statusElement = document.getElementById('scriptStatus');
if (statusElement) {
statusElement.textContent = message;
statusElement.className = type;
statusElement.style.display = 'block';
}
log(message, type);
}
// 检查Opus库是否已加载
function checkOpusLoaded() {
try {
// 检查Module是否存在(本地库导出的全局变量)
if (typeof Module === 'undefined') {
log("Module对象不存在", "error");
throw new Error('Opus库未加载,Module对象不存在');
}
// 记录Module对象结构以便调试
log("Module对象结构: " + Object.keys(Module).join(", "));
// 尝试使用全局Module函数
if (typeof Module._opus_decoder_get_size === 'function') {
window.ModuleInstance = Module;
log('Opus库加载成功(使用全局Module', "success");
updateScriptStatus('Opus库加载成功', 'success');
// 启用开始录音按钮
startButton.disabled = false;
statusLabel.textContent = "待机";
// 3秒后隐藏状态
setTimeout(() => {
const statusElement = document.getElementById('scriptStatus');
if (statusElement) statusElement.style.display = 'none';
}, 3000);
window.opusLoaded = true;
return true;
}
// 尝试使用Module.instance
if (typeof Module.instance !== 'undefined' && typeof Module.instance._opus_decoder_get_size === 'function') {
window.ModuleInstance = Module.instance;
log('Opus库加载成功(使用Module.instance', "success");
updateScriptStatus('Opus库加载成功', 'success');
// 启用开始录音按钮
startButton.disabled = false;
statusLabel.textContent = "待机";
// 3秒后隐藏状态
setTimeout(() => {
const statusElement = document.getElementById('scriptStatus');
if (statusElement) statusElement.style.display = 'none';
}, 3000);
window.opusLoaded = true;
return true;
}
// 检查是否有其他导出方式
log("Module上可用方法: " + Object.getOwnPropertyNames(Module).filter(prop => typeof Module[prop] === 'function').join(", "));
if (typeof Module.onRuntimeInitialized === 'function' || typeof Module.onRuntimeInitialized === 'undefined') {
log("Module.onRuntimeInitialized 尚未执行,等待模块初始化完成...");
// Module可能未完成初始化,注册回调
Module.onRuntimeInitialized = function() {
log("Opus库运行时初始化完成,重新检查");
checkOpusLoaded();
};
return false;
}
throw new Error('Opus解码函数未找到,可能Module结构不正确');
} catch (err) {
log(`Opus库加载失败: ${err.message}`, "error");
updateScriptStatus(`Opus库加载失败: ${err.message}`, 'error');
statusLabel.textContent = "错误:Opus库加载失败";
return false;
}
}
// 页面加载完成后检查浏览器能力和Opus库
window.addEventListener('load', function() {
log("页面加载完成,开始初始化...");
updateScriptStatus('正在初始化录音环境...', 'info');
// 延迟一小段时间再检查,确保库有时间加载
setTimeout(function checkAndRetry() {
if (!checkOpusLoaded()) {
// 如果加载失败,5秒后重试
log("Opus库加载失败,5秒后重试...");
updateScriptStatus('Opus库加载失败,正在重试...', 'error');
setTimeout(checkAndRetry, 5000);
}
}, 1000);
});
// 防止按钮误操作
document.getElementById("stop").disabled = true;
document.getElementById("play").disabled = true;
</script>
<script src="./../libopus.js"></script>
<script src="app.js"></script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 185 B

+998
View File
@@ -0,0 +1,998 @@
/* ==================== 全局样式 ==================== */
* {
box-sizing: border-box;
}
body {
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
margin: 0;
padding: 0px;
background-image: url('bg.png');
}
/* ==================== 容器布局 ==================== */
.container {
max-width: 1400px;
margin: 0 auto;
border-radius: 10px;
padding: 0px;
}
/* 两栏布局 */
.two-column-layout {
display: flex;
gap: 20px;
align-items: stretch;
margin-top: 10px;
margin-bottom: 10px;
}
.two-column-layout>.section {
flex: 1;
margin-top: 0;
margin-bottom: 0;
min-width: 0;
}
/* ==================== 通用区块样式 ==================== */
.section {
margin-top: 10px;
margin-bottom: 10px;
padding: 10px;
border-radius: 15px;
background-color: #fff;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.section h2 {
margin: 0;
color: #000;
font-size: 14px;
font-weight: 600;
letter-spacing: 0.02em;
display: flex;
align-items: center;
gap: 10px;
}
/* ==================== 通用按钮样式 ==================== */
button {
padding: 8px 15px;
border: none;
border-radius: 5px;
background-color: #007aff;
color: white;
cursor: pointer;
transition: background-color 0.2s;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
/* 切换按钮和连接按钮 */
.toggle-button,
.connect-button {
margin-left: auto;
padding: 4px 12px;
font-size: 14px;
border-radius: 20px;
cursor: pointer;
height: 28px;
line-height: 20px;
}
.toggle-button {
border: 1px solid #007aff;
background-color: #fff;
color: #007aff;
}
.connect-button {
box-shadow: 0px 0px 10px 2px rgba(0, 122, 255, 0.28);
}
/* ==================== 设备配置面板 ==================== */
.config-panel {
display: block;
transition: all 0.3s ease;
}
/* MCP工具面板默认隐藏 */
#mcpToolsPanel {
display: none;
}
#mcpToolsPanel.expanded {
display: block;
}
.control-panel {
display: flex;
flex-direction: column;
gap: 10px;
margin-top: 10px;
}
/* 配置行 */
.config-row {
display: flex;
gap: 10px;
width: 100%;
}
/* 配置项 */
.config-item {
flex: 1;
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
margin-bottom: 8px;
width: 100%;
}
.config-item label {
white-space: nowrap;
min-width: 70px;
text-align: left;
color: #666;
font-size: 12px;
}
.config-item input {
flex: 1;
width: 0;
flex-grow: 1;
padding: 6px;
font-size: 12px;
border: 1px solid #b1c9f8;
border-radius: 5px;
}
.config-item input:disabled {
background-color: #fff;
border-color: #fff;
cursor: default;
}
/* ==================== 连接信息面板 ==================== */
.connection-controls {
display: flex;
flex-direction: column;
gap: 10px;
width: 100%;
margin-top: 10px;
}
.connection-controls input {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 5px;
box-sizing: border-box;
}
.connection-controls button {
white-space: nowrap;
padding: 8px 15px;
}
#serverUrl,
#otaUrl {
flex-grow: 1;
padding: 8px;
border-radius: 5px;
}
#otaUrl {
border: 1px solid #b1c9f8;
}
#serverUrl {
border: 1px solid #fafafa;
background-color: #fafafa;
}
/* 连接状态 */
.connection-status {
display: flex;
align-items: center;
gap: 20px;
margin-left: 0px;
padding: 0 15px;
height: 28px;
line-height: 28px;
}
.connection-status span {
font-size: 13px;
}
.connection-status .status {
background-color: #fef2f2;
color: #b91c1c;
font-size: 12px;
padding: 0px 8px;
border-radius: 20px;
transition: all 0.3s ease;
}
/* 已连接状态 */
.connection-status .status.connected {
background-color: #ecfdf3;
color: #15803d;
}
/* 会话状态 - 离线中 */
.connection-status .status.offline {
background-color: #fef2f2;
color: #b91c1c;
}
/* 会话状态 - 聆听中 */
.connection-status .status.listening {
background-color: #ecfdf3;
color: #15803d;
}
/* 会话状态 - 说话中 */
.connection-status .status.speaking {
background-color: #fff7ed;
color: #c2410c;
animation: pulse-speaking 1.5s infinite;
}
@keyframes pulse-speaking {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.7;
}
}
/* LLM状态emoji样式 */
span.connection-status.llm-emoji {
display: block !important;
text-align: center !important;
width: 100% !important;
margin: 0 auto !important;
}
.llm-emoji .status {
font-size: 14px !important;
padding: 8px 20px !important;
}
.emoji-large {
font-size: 2em !important;
vertical-align: middle;
display: inline-block;
line-height: 1;
}
/* ==================== 标签页样式 ==================== */
.tabs {
display: flex;
margin-bottom: 20px;
border-bottom: 1px solid #e0e0e0;
align-items: center;
}
.tab {
padding: 10px 20px;
cursor: pointer;
border: none;
background: none;
font-size: 14px;
color: #666;
position: relative;
transition: all 0.3s ease;
}
.tab:hover {
color: #007aff;
}
.tab.active {
color: #007aff;
font-weight: bold;
}
.tab.active::after {
content: '';
position: absolute;
bottom: -1px;
left: 0;
width: 100%;
height: 1px;
background-color: #007aff;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
/* ==================== 文本消息输入 ==================== */
.message-input {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
#messageInput {
flex-grow: 1;
padding: 8px 20px 8px 20px;
border: 1px solid #b1c9f8;
border-radius: 10px;
}
#messageInput:disabled {
border: 1px solid #fafafa;
background-color: #fafafa;
}
#sendTextButton,
#recordButton {
border-radius: 20px;
}
/* ==================== 语音消息控制 ==================== */
.audio-controls {
display: flex;
justify-content: center;
gap: 10px;
margin-top: 20px;
}
.audio-visualizer {
height: 60px;
width: 100%;
margin-top: 10px;
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 5px;
background-color: #fafafa;
}
.record-button {
background-color: #db4437;
}
.record-button:hover {
background-color: #c53929;
}
.record-button.recording {
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0% {
background-color: #db4437;
}
50% {
background-color: #ff6659;
}
100% {
background-color: #db4437;
}
}
/* ==================== 会话记录和日志 ==================== */
.flex-container {
display: flex;
margin-top: 10px;
background-color: #f9fafb;
}
/* 会话记录容器 */
.conversation {
max-height: 300px;
overflow-y: auto;
border: 1px solid #ddd;
border-right: none;
border-radius: 5px 0px 0px 5px;
padding: 10px;
flex: 1;
}
/* 消息气泡 */
.message {
margin-bottom: 10px;
padding: 8px 12px;
border-radius: 8px;
width: fit-content;
max-width: 80%;
}
.user {
background-color: #fff;
margin-left: auto;
margin-right: 10px;
text-align: right;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.server {
background-color: #95ec69;
margin-right: auto;
margin-left: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
/* 日志容器 */
#logContainer {
margin-top: 0;
padding: 10px;
border-radius: 0px 5px 5px 0px;
font-family: monospace;
height: 300px;
overflow-y: auto;
flex: 1;
border: 1px solid #ddd;
}
.log-entry {
margin: 5px 0;
font-size: 12px;
}
.log-info {
color: #333;
}
.log-error {
color: #db4437;
}
.log-success {
color: #0f9d58;
}
/* ==================== MCP 工具管理 ==================== */
.mcp-tools-container {
display: grid;
gap: 12px;
margin-top: 10px;
}
.mcp-tool-card {
background-color: white;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 15px;
transition: all 0.2s;
}
.mcp-tool-card:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.mcp-tool-card.disabled {
opacity: 0.6;
pointer-events: none;
}
.mcp-tool-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.mcp-tool-name {
font-size: 15px;
font-weight: 600;
color: #333;
flex: 1;
}
.mcp-tool-actions {
display: flex;
gap: 6px;
}
.mcp-tool-description {
color: #666;
font-size: 13px;
line-height: 1.5;
margin-bottom: 8px;
}
.mcp-tool-info {
background-color: #f9f9f9;
border: 1px solid #e0e0e0;
border-radius: 4px;
padding: 8px;
font-size: 12px;
}
.mcp-tool-info-row {
display: flex;
gap: 15px;
margin-bottom: 4px;
}
.mcp-tool-info-label {
color: #999;
min-width: 60px;
}
.mcp-tool-info-value {
color: #333;
font-family: 'Courier New', monospace;
}
/* MCP 属性项 */
.mcp-property-item {
background-color: white;
border: 1px solid #e0e0e0;
border-radius: 5px;
padding: 12px;
margin-bottom: 10px;
}
.mcp-property-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.mcp-property-name {
font-weight: 600;
color: #333;
}
.mcp-property-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-bottom: 8px;
}
.mcp-property-row-full {
margin-bottom: 8px;
}
.mcp-small-label {
display: block;
margin-bottom: 4px;
font-size: 12px;
color: #666;
}
.mcp-small-input {
width: 100%;
padding: 6px 8px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 13px;
}
.mcp-checkbox-label {
display: flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: #666;
cursor: pointer;
}
.mcp-error {
background-color: #ffebee;
color: #c62828;
padding: 10px;
border-radius: 5px;
margin-bottom: 15px;
font-size: 14px;
}
.mcp-badge {
display: inline-block;
padding: 2px 8px;
border-radius: 12px;
font-size: 11px;
font-weight: 500;
margin-left: 8px;
}
.mcp-badge-required {
background-color: #ffebee;
color: #c62828;
}
.mcp-badge-optional {
background-color: #e3f2fd;
color: #1976d2;
}
/* ==================== 脚本加载状态 ==================== */
.script-status {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 5px;
}
.script-loaded {
background-color: #0f9d58;
}
.script-loading {
background-color: #f4b400;
}
.script-error {
background-color: #db4437;
}
.script-list {
margin: 10px 0;
padding: 10px;
background-color: #f9f9f9;
border-radius: 5px;
font-family: monospace;
font-size: 11px;
}
#scriptStatus.success {
background-color: #e6f4ea;
color: #0f9d58;
border-left: 4px solid #0f9d58;
}
#scriptStatus.error {
background-color: #fce8e6;
color: #db4437;
border-left: 4px solid #db4437;
}
#scriptStatus.warning {
background-color: #fef7e0;
color: #f4b400;
border-left: 4px solid #f4b400;
}
/* ==================== File协议警告 ==================== */
#fileProtocolWarning {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 9999;
color: white;
padding: 20px;
box-sizing: border-box;
}
#fileProtocolWarning h2 {
color: #ff4d4d;
margin-bottom: 20px;
}
#fileProtocolWarning pre {
background-color: green;
font-size: 18px;
padding: 15px;
border-radius: 5px;
font-family: monospace;
overflow-x: auto;
margin: 15px 0;
}
#fileProtocolWarning button {
background-color: #4CAF50;
color: white;
border: none;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 10px 2px;
cursor: pointer;
border-radius: 4px;
}
#fileProtocolWarning button:hover {
background-color: #45a049;
}
/* ==================== 响应式布局 ==================== */
/* 大屏幕 (宽度 > 1200px) */
@media (min-width: 1201px) {
.container {
max-width: 80%;
}
}
/* 中等屏幕 (宽度 <= 1200px) */
@media (max-width: 1200px) {
.container {
max-width: 95%;
padding: 10px;
}
}
/* 平板设备 (宽度 <= 1060px) */
@media (max-width: 1060px) {
/* 两栏布局改为单栏 */
.two-column-layout {
flex-direction: column;
gap: 0;
}
.two-column-layout>.section {
width: 100%;
margin-top: 10px;
margin-bottom: 10px;
}
/* 连接状态标签调整 */
.connection-status {
flex-wrap: wrap;
gap: 8px;
margin-left: 0px;
padding: 0 8px;
}
/* 会话记录和日志容器改为上下布局 */
.flex-container {
flex-direction: column;
}
.conversation,
#logContainer {
border-radius: 5px;
border: 1px solid #ddd;
max-height: 200px;
}
.conversation {
margin-bottom: 10px;
}
/* MCP 属性行改为单列 */
.mcp-property-row {
grid-template-columns: 1fr;
}
}
/* 移动设备 (宽度 <= 768px) */
@media (max-width: 768px) {
body {
padding: 0;
}
.container {
max-width: 100%;
padding: 5px;
}
/* 调整区块内边距 */
.section {
padding: 8px;
margin-top: 8px;
margin-bottom: 8px;
border-radius: 10px;
}
/* 调整标题字体 */
.section h2 {
font-size: 13px;
flex-wrap: wrap;
gap: 5px;
}
/* 配置行改为单列 */
.config-row {
flex-direction: column;
}
/* 按钮调整 */
.toggle-button,
.connect-button {
padding: 3px 10px;
font-size: 12px;
height: 24px;
line-height: 18px;
}
button {
padding: 6px 12px;
font-size: 13px;
}
/* 输入框 */
#serverUrl,
#otaUrl,
#messageInput {
font-size: 14px;
padding: 6px;
}
/* 配置项标签 */
.config-item label {
min-width: 60px;
font-size: 12px;
}
.config-item input {
font-size: 13px;
padding: 5px;
}
/* 标签页 */
.tab {
padding: 8px 12px;
font-size: 14px;
}
/* 消息气泡 */
.message {
max-width: 90%;
font-size: 14px;
padding: 6px 10px;
}
/* 日志容器 */
#logContainer {
font-size: 11px;
padding: 8px;
}
.log-entry {
font-size: 11px;
}
/* 连接状态 */
.connection-status {
margin-left: 0;
padding: 5px 0;
height: auto;
line-height: normal;
}
.connection-status .status {
font-size: 11px;
padding: 0px 6px;
}
/* 音频可视化 */
.audio-visualizer {
height: 50px;
}
/* MCP 工具卡片 */
.mcp-tool-card {
padding: 10px;
}
.mcp-tool-name {
font-size: 13px;
}
.mcp-tool-description {
font-size: 12px;
}
.mcp-tool-info {
font-size: 11px;
padding: 6px;
}
.mcp-tool-info-row {
flex-direction: column;
gap: 2px;
}
.mcp-tool-info-label {
min-width: auto;
}
/* 消息输入框 */
.message-input {
gap: 5px;
}
/* 会话记录高度调整 */
.conversation,
#logContainer {
max-height: 180px;
}
}
/* 小型移动设备 (宽度 <= 480px) */
@media (max-width: 480px) {
.container {
padding: 3px;
}
.section {
padding: 6px;
margin-top: 5px;
margin-bottom: 5px;
}
.section h2 {
font-size: 12px;
}
/* 更紧凑的按钮 */
.toggle-button,
.connect-button {
padding: 2px 8px;
font-size: 11px;
height: 22px;
line-height: 16px;
}
button {
padding: 5px 10px;
font-size: 12px;
}
.config-item label {
min-width: 50px;
font-size: 11px;
}
.config-item input {
font-size: 12px;
}
/* 标签页 */
.tab {
padding: 6px 10px;
font-size: 13px;
}
/* 消息气泡 */
.message {
max-width: 95%;
font-size: 13px;
}
/* 会话记录 */
.conversation,
#logContainer {
max-height: 150px;
padding: 8px;
}
/* 连接状态文字更小 */
.connection-status .status {
font-size: 10px;
}
/* MCP 工具 */
.mcp-tool-name {
font-size: 12px;
}
.mcp-tool-description {
font-size: 11px;
}
}
+50
View File
@@ -0,0 +1,50 @@
// 主应用入口
import { log } from './utils/logger.js';
import { checkOpusLoaded, initOpusEncoder } from './core/audio/opus-codec.js';
import { getUIController } from './ui/controller.js';
import { getAudioPlayer } from './core/audio/player.js';
import { initMcpTools } from './core/mcp/tools.js';
// 应用类
class App {
constructor() {
this.uiController = null;
this.audioPlayer = null;
}
// 初始化应用
async init() {
log('正在初始化应用...', 'info');
// 初始化UI控制器
this.uiController = getUIController();
this.uiController.init();
// 检查Opus库
checkOpusLoaded();
// 初始化Opus编码器
initOpusEncoder();
// 初始化音频播放器
this.audioPlayer = getAudioPlayer();
await this.audioPlayer.start();
// 初始化MCP工具
initMcpTools();
log('应用初始化完成', 'success');
}
}
// 创建并启动应用
const app = new App();
// DOM加载完成后初始化
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => app.init());
} else {
app.init();
}
export default app;
@@ -0,0 +1,85 @@
// 配置管理模块
// 生成随机MAC地址
function generateRandomMac() {
const hexDigits = '0123456789ABCDEF';
let mac = '';
for (let i = 0; i < 6; i++) {
if (i > 0) mac += ':';
for (let j = 0; j < 2; j++) {
mac += hexDigits.charAt(Math.floor(Math.random() * 16));
}
}
return mac;
}
// 加载配置
export function loadConfig() {
const deviceMacInput = document.getElementById('deviceMac');
const deviceNameInput = document.getElementById('deviceName');
const clientIdInput = document.getElementById('clientId');
const tokenInput = document.getElementById('token');
const otaUrlInput = document.getElementById('otaUrl');
// 从localStorage加载MAC地址,如果没有则生成新的
let savedMac = localStorage.getItem('xz_tester_deviceMac');
if (!savedMac) {
savedMac = generateRandomMac();
localStorage.setItem('xz_tester_deviceMac', savedMac);
}
deviceMacInput.value = savedMac;
// 从localStorage加载其他配置
const savedDeviceName = localStorage.getItem('xz_tester_deviceName');
if (savedDeviceName) {
deviceNameInput.value = savedDeviceName;
}
const savedClientId = localStorage.getItem('xz_tester_clientId');
if (savedClientId) {
clientIdInput.value = savedClientId;
}
const savedToken = localStorage.getItem('xz_tester_token');
if (savedToken) {
tokenInput.value = savedToken;
}
const savedOtaUrl = localStorage.getItem('xz_tester_otaUrl');
if (savedOtaUrl) {
otaUrlInput.value = savedOtaUrl;
}
}
// 保存配置
export function saveConfig() {
const deviceMacInput = document.getElementById('deviceMac');
const deviceNameInput = document.getElementById('deviceName');
const clientIdInput = document.getElementById('clientId');
const tokenInput = document.getElementById('token');
localStorage.setItem('xz_tester_deviceMac', deviceMacInput.value);
localStorage.setItem('xz_tester_deviceName', deviceNameInput.value);
localStorage.setItem('xz_tester_clientId', clientIdInput.value);
localStorage.setItem('xz_tester_token', tokenInput.value);
}
// 获取配置值
export function getConfig() {
const deviceMac = document.getElementById('deviceMac').value.trim();
return {
deviceId: deviceMac, // 使用MAC地址作为deviceId
deviceName: document.getElementById('deviceName').value.trim(),
deviceMac: deviceMac,
clientId: document.getElementById('clientId').value.trim(),
token: document.getElementById('token').value.trim()
};
}
// 保存连接URL
export function saveConnectionUrls() {
const otaUrl = document.getElementById('otaUrl').value.trim();
const wsUrl = document.getElementById('serverUrl').value.trim();
localStorage.setItem('xz_tester_otaUrl', otaUrl);
localStorage.setItem('xz_tester_wsUrl', wsUrl);
}
@@ -1,5 +1,5 @@
import { log } from './utils/logger.js';
import { updateScriptStatus } from './document.js'
import { log } from '../../utils/logger.js';
import { updateScriptStatus } from '../../ui/dom-helper.js'
// 检查Opus库是否已加载
@@ -0,0 +1,262 @@
// 音频播放模块
import { log } from '../../utils/logger.js';
import BlockingQueue from '../../utils/blocking-queue.js';
import { createStreamingContext } from './stream-context.js';
// 音频播放器类
export class AudioPlayer {
constructor() {
// 音频参数
this.SAMPLE_RATE = 16000;
this.CHANNELS = 1;
this.FRAME_SIZE = 960;
this.MIN_AUDIO_DURATION = 0.12;
// 状态
this.audioContext = null;
this.opusDecoder = null;
this.streamingContext = null;
this.queue = new BlockingQueue();
this.isPlaying = false;
}
// 获取或创建AudioContext
getAudioContext() {
if (!this.audioContext) {
this.audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: this.SAMPLE_RATE,
latencyHint: 'interactive'
});
log('创建音频上下文,采样率: ' + this.SAMPLE_RATE + 'Hz', 'debug');
}
return this.audioContext;
}
// 初始化Opus解码器
async initOpusDecoder() {
if (this.opusDecoder) return this.opusDecoder;
try {
if (typeof window.ModuleInstance === 'undefined') {
if (typeof Module !== 'undefined') {
window.ModuleInstance = Module;
log('使用全局Module作为ModuleInstance', 'info');
} else {
throw new Error('Opus库未加载,ModuleInstance和Module对象都不存在');
}
}
const mod = window.ModuleInstance;
this.opusDecoder = {
channels: this.CHANNELS,
rate: this.SAMPLE_RATE,
frameSize: this.FRAME_SIZE,
module: mod,
decoderPtr: null,
init: function () {
if (this.decoderPtr) return true;
const decoderSize = mod._opus_decoder_get_size(this.channels);
log(`Opus解码器大小: ${decoderSize}字节`, 'debug');
this.decoderPtr = mod._malloc(decoderSize);
if (!this.decoderPtr) {
throw new Error("无法分配解码器内存");
}
const err = mod._opus_decoder_init(
this.decoderPtr,
this.rate,
this.channels
);
if (err < 0) {
this.destroy();
throw new Error(`Opus解码器初始化失败: ${err}`);
}
log("Opus解码器初始化成功", 'success');
return true;
},
decode: function (opusData) {
if (!this.decoderPtr) {
if (!this.init()) {
throw new Error("解码器未初始化且无法初始化");
}
}
try {
const mod = this.module;
const opusPtr = mod._malloc(opusData.length);
mod.HEAPU8.set(opusData, opusPtr);
const pcmPtr = mod._malloc(this.frameSize * 2);
const decodedSamples = mod._opus_decode(
this.decoderPtr,
opusPtr,
opusData.length,
pcmPtr,
this.frameSize,
0
);
if (decodedSamples < 0) {
mod._free(opusPtr);
mod._free(pcmPtr);
throw new Error(`Opus解码失败: ${decodedSamples}`);
}
const decodedData = new Int16Array(decodedSamples);
for (let i = 0; i < decodedSamples; i++) {
decodedData[i] = mod.HEAP16[(pcmPtr >> 1) + i];
}
mod._free(opusPtr);
mod._free(pcmPtr);
return decodedData;
} catch (error) {
log(`Opus解码错误: ${error.message}`, 'error');
return new Int16Array(0);
}
},
destroy: function () {
if (this.decoderPtr) {
this.module._free(this.decoderPtr);
this.decoderPtr = null;
}
}
};
if (!this.opusDecoder.init()) {
throw new Error("Opus解码器初始化失败");
}
return this.opusDecoder;
} catch (error) {
log(`Opus解码器初始化失败: ${error.message}`, 'error');
this.opusDecoder = null;
throw error;
}
}
// 启动音频缓冲
async startAudioBuffering() {
log("开始音频缓冲...", 'info');
this.initOpusDecoder().catch(error => {
log(`预初始化Opus解码器失败: ${error.message}`, 'warning');
});
const timeout = 400;
while (true) {
const packets = await this.queue.dequeue(
6,
timeout,
(count) => {
log(`缓冲超时,当前缓冲包数: ${count},开始播放`, 'info');
}
);
if (packets.length) {
log(`已缓冲 ${packets.length} 个音频包,开始播放`, 'info');
this.streamingContext.pushAudioBuffer(packets);
}
while (true) {
const data = await this.queue.dequeue(99, 30);
if (data.length) {
this.streamingContext.pushAudioBuffer(data);
} else {
break;
}
}
}
}
// 播放已缓冲的音频
async playBufferedAudio() {
try {
this.audioContext = this.getAudioContext();
if (!this.opusDecoder) {
log('初始化Opus解码器...', 'info');
try {
this.opusDecoder = await this.initOpusDecoder();
if (!this.opusDecoder) {
throw new Error('解码器初始化失败');
}
log('Opus解码器初始化成功', 'success');
} catch (error) {
log('Opus解码器初始化失败: ' + error.message, 'error');
this.isPlaying = false;
return;
}
}
if (!this.streamingContext) {
this.streamingContext = createStreamingContext(
this.opusDecoder,
this.audioContext,
this.SAMPLE_RATE,
this.CHANNELS,
this.MIN_AUDIO_DURATION
);
}
this.streamingContext.decodeOpusFrames();
this.streamingContext.startPlaying();
} catch (error) {
log(`播放已缓冲的音频出错: ${error.message}`, 'error');
this.isPlaying = false;
this.streamingContext = null;
}
}
// 添加音频数据到队列
enqueueAudioData(opusData) {
if (opusData.length > 0) {
this.queue.enqueue(opusData);
} else {
log('收到空音频数据帧,可能是结束标志', 'warning');
if (this.isPlaying && this.streamingContext) {
this.streamingContext.endOfStream = true;
}
}
}
// 预加载解码器
async preload() {
log('预加载Opus解码器...', 'info');
try {
await this.initOpusDecoder();
log('Opus解码器预加载成功', 'success');
} catch (error) {
log(`Opus解码器预加载失败: ${error.message},将在需要时重试`, 'warning');
}
}
// 启动播放系统
async start() {
await this.preload();
this.playBufferedAudio();
this.startAudioBuffering();
}
}
// 创建单例
let audioPlayerInstance = null;
export function getAudioPlayer() {
if (!audioPlayerInstance) {
audioPlayerInstance = new AudioPlayer();
}
return audioPlayerInstance;
}
@@ -0,0 +1,420 @@
// 音频录制模块
import { log } from '../../utils/logger.js';
import { initOpusEncoder } from './opus-codec.js';
import { getAudioPlayer } from './player.js';
// 音频录制器类
export class AudioRecorder {
constructor() {
this.isRecording = false;
this.audioContext = null;
this.analyser = null;
this.audioProcessor = null;
this.audioProcessorType = null;
this.audioSource = null;
this.opusEncoder = null;
this.pcmDataBuffer = new Int16Array();
this.audioBuffers = [];
this.totalAudioSize = 0;
this.visualizationRequest = null;
this.recordingTimer = null;
this.websocket = null;
// 回调函数
this.onRecordingStart = null;
this.onRecordingStop = null;
this.onVisualizerUpdate = null;
}
// 设置WebSocket实例
setWebSocket(ws) {
this.websocket = ws;
}
// 获取AudioContext实例
getAudioContext() {
const audioPlayer = getAudioPlayer();
return audioPlayer.getAudioContext();
}
// 初始化编码器
initEncoder() {
if (!this.opusEncoder) {
this.opusEncoder = initOpusEncoder();
}
return this.opusEncoder;
}
// PCM处理器代码
getAudioProcessorCode() {
return `
class AudioRecorderProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.buffers = [];
this.frameSize = 960;
this.buffer = new Int16Array(this.frameSize);
this.bufferIndex = 0;
this.isRecording = false;
this.port.onmessage = (event) => {
if (event.data.command === 'start') {
this.isRecording = true;
this.port.postMessage({ type: 'status', status: 'started' });
} else if (event.data.command === 'stop') {
this.isRecording = false;
if (this.bufferIndex > 0) {
const finalBuffer = this.buffer.slice(0, this.bufferIndex);
this.port.postMessage({
type: 'buffer',
buffer: finalBuffer
});
this.bufferIndex = 0;
}
this.port.postMessage({ type: 'status', status: 'stopped' });
}
};
}
process(inputs, outputs, parameters) {
if (!this.isRecording) return true;
const input = inputs[0][0];
if (!input) return true;
for (let i = 0; i < input.length; i++) {
if (this.bufferIndex >= this.frameSize) {
this.port.postMessage({
type: 'buffer',
buffer: this.buffer.slice(0)
});
this.bufferIndex = 0;
}
this.buffer[this.bufferIndex++] = Math.max(-32768, Math.min(32767, Math.floor(input[i] * 32767)));
}
return true;
}
}
registerProcessor('audio-recorder-processor', AudioRecorderProcessor);
`;
}
// 创建音频处理器
async createAudioProcessor() {
this.audioContext = this.getAudioContext();
try {
if (this.audioContext.audioWorklet) {
const blob = new Blob([this.getAudioProcessorCode()], { type: 'application/javascript' });
const url = URL.createObjectURL(blob);
await this.audioContext.audioWorklet.addModule(url);
URL.revokeObjectURL(url);
const audioProcessor = new AudioWorkletNode(this.audioContext, 'audio-recorder-processor');
audioProcessor.port.onmessage = (event) => {
if (event.data.type === 'buffer') {
this.processPCMBuffer(event.data.buffer);
}
};
log('使用AudioWorklet处理音频', 'success');
const silent = this.audioContext.createGain();
silent.gain.value = 0;
audioProcessor.connect(silent);
silent.connect(this.audioContext.destination);
return { node: audioProcessor, type: 'worklet' };
} else {
log('AudioWorklet不可用,使用ScriptProcessorNode作为回退方案', 'warning');
return this.createScriptProcessor();
}
} catch (error) {
log(`创建音频处理器失败: ${error.message},尝试回退方案`, 'error');
return this.createScriptProcessor();
}
}
// 创建ScriptProcessor作为回退
createScriptProcessor() {
try {
const frameSize = 4096;
const scriptProcessor = this.audioContext.createScriptProcessor(frameSize, 1, 1);
scriptProcessor.onaudioprocess = (event) => {
if (!this.isRecording) return;
const input = event.inputBuffer.getChannelData(0);
const buffer = new Int16Array(input.length);
for (let i = 0; i < input.length; i++) {
buffer[i] = Math.max(-32768, Math.min(32767, Math.floor(input[i] * 32767)));
}
this.processPCMBuffer(buffer);
};
const silent = this.audioContext.createGain();
silent.gain.value = 0;
scriptProcessor.connect(silent);
silent.connect(this.audioContext.destination);
log('使用ScriptProcessorNode作为回退方案成功', 'warning');
return { node: scriptProcessor, type: 'processor' };
} catch (fallbackError) {
log(`回退方案也失败: ${fallbackError.message}`, 'error');
return null;
}
}
// 处理PCM缓冲数据
processPCMBuffer(buffer) {
if (!this.isRecording) return;
const newBuffer = new Int16Array(this.pcmDataBuffer.length + buffer.length);
newBuffer.set(this.pcmDataBuffer);
newBuffer.set(buffer, this.pcmDataBuffer.length);
this.pcmDataBuffer = newBuffer;
const samplesPerFrame = 960;
while (this.pcmDataBuffer.length >= samplesPerFrame) {
const frameData = this.pcmDataBuffer.slice(0, samplesPerFrame);
this.pcmDataBuffer = this.pcmDataBuffer.slice(samplesPerFrame);
this.encodeAndSendOpus(frameData);
}
}
// 编码并发送Opus数据
encodeAndSendOpus(pcmData = null) {
if (!this.opusEncoder) {
log('Opus编码器未初始化', 'error');
return;
}
try {
if (pcmData) {
const opusData = this.opusEncoder.encode(pcmData);
if (opusData && opusData.length > 0) {
this.audioBuffers.push(opusData.buffer);
this.totalAudioSize += opusData.length;
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
try {
this.websocket.send(opusData.buffer);
log(`发送Opus帧,大小:${opusData.length}字节`, 'debug');
} catch (error) {
log(`WebSocket发送错误: ${error.message}`, 'error');
}
}
} else {
log('Opus编码失败,无有效数据返回', 'error');
}
} else {
if (this.pcmDataBuffer.length > 0) {
const samplesPerFrame = 960;
if (this.pcmDataBuffer.length < samplesPerFrame) {
const paddedBuffer = new Int16Array(samplesPerFrame);
paddedBuffer.set(this.pcmDataBuffer);
this.encodeAndSendOpus(paddedBuffer);
} else {
this.encodeAndSendOpus(this.pcmDataBuffer.slice(0, samplesPerFrame));
}
this.pcmDataBuffer = new Int16Array(0);
}
}
} catch (error) {
log(`Opus编码错误: ${error.message}`, 'error');
}
}
// 开始录音
async start() {
if (this.isRecording) return false;
try {
if (!this.initEncoder()) {
log('无法启动录音: Opus编码器初始化失败', 'error');
return false;
}
log('请至少录制1-2秒钟的音频,确保采集到足够数据', 'info');
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
sampleRate: 16000,
channelCount: 1
}
});
this.audioContext = this.getAudioContext();
if (this.audioContext.state === 'suspended') {
await this.audioContext.resume();
}
const processorResult = await this.createAudioProcessor();
if (!processorResult) {
log('无法创建音频处理器', 'error');
return false;
}
this.audioProcessor = processorResult.node;
this.audioProcessorType = processorResult.type;
this.audioSource = this.audioContext.createMediaStreamSource(stream);
this.analyser = this.audioContext.createAnalyser();
this.analyser.fftSize = 2048;
this.audioSource.connect(this.analyser);
this.audioSource.connect(this.audioProcessor);
this.pcmDataBuffer = new Int16Array();
this.audioBuffers = [];
this.totalAudioSize = 0;
this.isRecording = true;
if (this.audioProcessorType === 'worklet' && this.audioProcessor.port) {
this.audioProcessor.port.postMessage({ command: 'start' });
}
// 发送监听开始消息
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
const listenMessage = {
type: 'listen',
mode: 'manual',
state: 'start'
};
log(`发送录音开始消息: ${JSON.stringify(listenMessage)}`, 'info');
this.websocket.send(JSON.stringify(listenMessage));
} else {
log('WebSocket未连接,无法发送开始消息', 'error');
return false;
}
// 开始可视化
if (this.onVisualizerUpdate) {
const dataArray = new Uint8Array(this.analyser.frequencyBinCount);
this.startVisualization(dataArray);
}
// 启动录音计时器
let recordingSeconds = 0;
this.recordingTimer = setInterval(() => {
recordingSeconds += 0.1;
if (this.onRecordingStart) {
this.onRecordingStart(recordingSeconds);
}
}, 100);
log('开始PCM直接录音', 'success');
return true;
} catch (error) {
log(`直接录音启动错误: ${error.message}`, 'error');
this.isRecording = false;
return false;
}
}
// 开始可视化
startVisualization(dataArray) {
const draw = () => {
this.visualizationRequest = requestAnimationFrame(() => draw());
if (!this.isRecording) return;
this.analyser.getByteFrequencyData(dataArray);
if (this.onVisualizerUpdate) {
this.onVisualizerUpdate(dataArray);
}
};
draw();
}
// 停止录音
stop() {
if (!this.isRecording) return false;
try {
this.isRecording = false;
if (this.audioProcessor) {
if (this.audioProcessorType === 'worklet' && this.audioProcessor.port) {
this.audioProcessor.port.postMessage({ command: 'stop' });
}
this.audioProcessor.disconnect();
this.audioProcessor = null;
}
if (this.audioSource) {
this.audioSource.disconnect();
this.audioSource = null;
}
if (this.visualizationRequest) {
cancelAnimationFrame(this.visualizationRequest);
this.visualizationRequest = null;
}
if (this.recordingTimer) {
clearInterval(this.recordingTimer);
this.recordingTimer = null;
}
// 编码并发送剩余的数据
this.encodeAndSendOpus();
// 发送结束信号
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
const emptyOpusFrame = new Uint8Array(0);
this.websocket.send(emptyOpusFrame);
const stopMessage = {
type: 'listen',
mode: 'manual',
state: 'stop'
};
this.websocket.send(JSON.stringify(stopMessage));
log('已发送录音停止信号', 'info');
}
if (this.onRecordingStop) {
this.onRecordingStop();
}
log('停止PCM直接录音', 'success');
return true;
} catch (error) {
log(`直接录音停止错误: ${error.message}`, 'error');
return false;
}
}
// 获取分析器
getAnalyser() {
return this.analyser;
}
}
// 创建单例
let audioRecorderInstance = null;
export function getAudioRecorder() {
if (!audioRecorderInstance) {
audioRecorderInstance = new AudioRecorder();
}
return audioRecorderInstance;
}
@@ -1,5 +1,5 @@
import BlockingQueue from './utils/BlockingQueue.js';
import { log } from './utils/logger.js';
import BlockingQueue from '../../utils/blocking-queue.js';
import { log } from '../../utils/logger.js';
// 音频流播放上下文类
export class StreamingContext {
@@ -48,8 +48,8 @@ export class StreamingContext {
convertInt16ToFloat32(int16Data) {
const float32Data = new Float32Array(int16Data.length);
for (let i = 0; i < int16Data.length; i++) {
// 将[-32768,32767]范围转换为[-1,1]
float32Data[i] = int16Data[i] / (int16Data[i] < 0 ? 0x8000 : 0x7FFF);
// 将[-32768,32767]范围转换为[-1,1],统一使用32768.0避免不对称失真
float32Data[i] = int16Data[i] / 32768.0;
}
return float32Data;
}
@@ -97,18 +97,26 @@ export class StreamingContext {
// 开始播放音频
async startPlaying() {
let scheduledEndTime = this.audioContext.currentTime; // 跟踪已调度音频的结束时间
while (true) {
// 如果累积了至少0.3秒的音频,开始播放
const minSamples = this.sampleRate * this.minAudioDuration * 3;
// 初始缓冲:等待足够的样本再开始播放
const minSamples = this.sampleRate * this.minAudioDuration * 2;
if (!this.playing && this.queue.length < minSamples) {
await this.getQueue(minSamples);
}
this.playing = true;
while (this.playing && this.queue.length) {
// 创建新的音频缓冲区
const minPlaySamples = Math.min(this.queue.length, this.sampleRate);
const currentSamples = this.queue.splice(0, minPlaySamples);
// 持续播放队列中的音频,每次播放一个小块
while (this.playing && this.queue.length > 0) {
// 每次播放120ms的音频(2个Opus包)
const playDuration = 0.12;
const targetSamples = Math.floor(this.sampleRate * playDuration);
const actualSamples = Math.min(this.queue.length, targetSamples);
if (actualSamples === 0) break;
const currentSamples = this.queue.splice(0, actualSamples);
const audioBuffer = this.audioContext.createBuffer(this.channels, currentSamples.length, this.sampleRate);
audioBuffer.copyToChannel(new Float32Array(currentSamples), 0);
@@ -116,28 +124,28 @@ export class StreamingContext {
this.source = this.audioContext.createBufferSource();
this.source.buffer = audioBuffer;
// 创建增益节点用于平滑过渡
const gainNode = this.audioContext.createGain();
// 精确调度播放时间
const currentTime = this.audioContext.currentTime;
const startTime = Math.max(scheduledEndTime, currentTime);
// 应用淡入淡出效果避免爆音
const fadeDuration = 0.02; // 20毫秒
gainNode.gain.setValueAtTime(0, this.audioContext.currentTime);
gainNode.gain.linearRampToValueAtTime(1, this.audioContext.currentTime + fadeDuration);
// 直接连接到输出
this.source.connect(this.audioContext.destination);
log(`调度播放 ${currentSamples.length} 个样本,约 ${(currentSamples.length / this.sampleRate).toFixed(2)}`, 'debug');
this.source.start(startTime);
// 更新下一个音频块的调度时间
const duration = audioBuffer.duration;
if (duration > fadeDuration * 2) {
gainNode.gain.setValueAtTime(1, this.audioContext.currentTime + duration - fadeDuration);
gainNode.gain.linearRampToValueAtTime(0, this.audioContext.currentTime + duration);
scheduledEndTime = startTime + duration;
this.lastPlayTime = startTime;
// 如果队列中数据不足,等待新数据
if (this.queue.length < targetSamples) {
break;
}
// 连接节点并开始播放
this.source.connect(gainNode);
gainNode.connect(this.audioContext.destination);
this.lastPlayTime = this.audioContext.currentTime;
log(`开始播放 ${currentSamples.length} 个样本,约 ${(currentSamples.length / this.sampleRate).toFixed(2)}`, 'info');
this.source.start();
}
// 等待新数据
await this.getQueue(minSamples);
}
}
@@ -0,0 +1,477 @@
import { log } from '../../utils/logger.js';
// ==========================================
// MCP 工具管理逻辑
// ==========================================
// 全局变量
let mcpTools = [];
let mcpEditingIndex = null;
let mcpProperties = [];
let websocket = null; // 将从外部设置
/**
* 设置 WebSocket 实例
* @param {WebSocket} ws - WebSocket 连接实例
*/
export function setWebSocket(ws) {
websocket = ws;
}
/**
* 初始化 MCP 工具
*/
export async function initMcpTools() {
// 加载默认工具数据
const defaultMcpTools = await fetch("js/config/default-mcp-tools.json").then(res => res.json());
const savedTools = localStorage.getItem('mcpTools');
if (savedTools) {
try {
mcpTools = JSON.parse(savedTools);
} catch (e) {
log('加载MCP工具失败,使用默认工具', 'warning');
mcpTools = [...defaultMcpTools];
}
} else {
mcpTools = [...defaultMcpTools];
}
renderMcpTools();
setupMcpEventListeners();
}
/**
* 渲染工具列表
*/
function renderMcpTools() {
const container = document.getElementById('mcpToolsContainer');
const countSpan = document.getElementById('mcpToolsCount');
countSpan.textContent = `${mcpTools.length} 个工具`;
if (mcpTools.length === 0) {
container.innerHTML = '<div style="text-align: center; padding: 30px; color: #999;">暂无工具,点击下方按钮添加新工具</div>';
return;
}
container.innerHTML = mcpTools.map((tool, index) => {
const paramCount = tool.inputSchema.properties ? Object.keys(tool.inputSchema.properties).length : 0;
const requiredCount = tool.inputSchema.required ? tool.inputSchema.required.length : 0;
const hasMockResponse = tool.mockResponse && Object.keys(tool.mockResponse).length > 0;
return `
<div class="mcp-tool-card">
<div class="mcp-tool-header">
<div class="mcp-tool-name">${tool.name}</div>
<div class="mcp-tool-actions">
<button onclick="window.mcpModule.editMcpTool(${index})"
style="padding: 4px 10px; border: none; border-radius: 4px; background-color: #2196f3; color: white; cursor: pointer; font-size: 12px;">
编辑
</button>
<button onclick="window.mcpModule.deleteMcpTool(${index})"
style="padding: 4px 10px; border: none; border-radius: 4px; background-color: #f44336; color: white; cursor: pointer; font-size: 12px;">
🗑 删除
</button>
</div>
</div>
<div class="mcp-tool-description">${tool.description}</div>
<div class="mcp-tool-info">
<div class="mcp-tool-info-row">
<span class="mcp-tool-info-label">参数数量:</span>
<span class="mcp-tool-info-value">${paramCount} ${requiredCount > 0 ? `(${requiredCount} 个必填)` : ''}</span>
</div>
<div class="mcp-tool-info-row">
<span class="mcp-tool-info-label">模拟返回:</span>
<span class="mcp-tool-info-value">${hasMockResponse ? '✅ 已配置: ' + JSON.stringify(tool.mockResponse) : '⚪ 使用默认'}</span>
</div>
</div>
</div>
`;
}).join('');
}
/**
* 渲染参数列表
*/
function renderMcpProperties() {
const container = document.getElementById('mcpPropertiesContainer');
if (mcpProperties.length === 0) {
container.innerHTML = '<div style="text-align: center; padding: 20px; color: #999; font-size: 14px;">暂无参数,点击下方按钮添加参数</div>';
return;
}
container.innerHTML = mcpProperties.map((prop, index) => `
<div class="mcp-property-item">
<div class="mcp-property-header">
<span class="mcp-property-name">${prop.name}</span>
<button type="button" onclick="window.mcpModule.deleteMcpProperty(${index})"
style="padding: 3px 8px; border: none; border-radius: 3px; background-color: #f44336; color: white; cursor: pointer; font-size: 11px;">
删除
</button>
</div>
<div class="mcp-property-row">
<div>
<label class="mcp-small-label">参数名称 *</label>
<input type="text" class="mcp-small-input" value="${prop.name}"
onchange="window.mcpModule.updateMcpProperty(${index}, 'name', this.value)" required>
</div>
<div>
<label class="mcp-small-label">数据类型 *</label>
<select class="mcp-small-input" onchange="window.mcpModule.updateMcpProperty(${index}, 'type', this.value)">
<option value="string" ${prop.type === 'string' ? 'selected' : ''}>字符串</option>
<option value="integer" ${prop.type === 'integer' ? 'selected' : ''}>整数</option>
<option value="number" ${prop.type === 'number' ? 'selected' : ''}>数字</option>
<option value="boolean" ${prop.type === 'boolean' ? 'selected' : ''}>布尔值</option>
<option value="array" ${prop.type === 'array' ? 'selected' : ''}>数组</option>
<option value="object" ${prop.type === 'object' ? 'selected' : ''}>对象</option>
</select>
</div>
</div>
${(prop.type === 'integer' || prop.type === 'number') ? `
<div class="mcp-property-row">
<div>
<label class="mcp-small-label">最小值</label>
<input type="number" class="mcp-small-input" value="${prop.minimum !== undefined ? prop.minimum : ''}"
placeholder="可选" onchange="window.mcpModule.updateMcpProperty(${index}, 'minimum', this.value ? parseFloat(this.value) : undefined)">
</div>
<div>
<label class="mcp-small-label">最大值</label>
<input type="number" class="mcp-small-input" value="${prop.maximum !== undefined ? prop.maximum : ''}"
placeholder="可选" onchange="window.mcpModule.updateMcpProperty(${index}, 'maximum', this.value ? parseFloat(this.value) : undefined)">
</div>
</div>
` : ''}
<div class="mcp-property-row-full">
<label class="mcp-small-label">参数描述</label>
<input type="text" class="mcp-small-input" value="${prop.description || ''}"
placeholder="可选" onchange="window.mcpModule.updateMcpProperty(${index}, 'description', this.value)">
</div>
<label class="mcp-checkbox-label">
<input type="checkbox" ${prop.required ? 'checked' : ''}
onchange="window.mcpModule.updateMcpProperty(${index}, 'required', this.checked)">
必填参数
</label>
</div>
`).join('');
}
/**
* 添加参数
*/
function addMcpProperty() {
mcpProperties.push({
name: `param_${mcpProperties.length + 1}`,
type: 'string',
required: false,
description: ''
});
renderMcpProperties();
}
/**
* 更新参数
*/
function updateMcpProperty(index, field, value) {
if (field === 'name') {
const isDuplicate = mcpProperties.some((p, i) => i !== index && p.name === value);
if (isDuplicate) {
alert('参数名称已存在,请使用不同的名称');
renderMcpProperties();
return;
}
}
mcpProperties[index][field] = value;
if (field === 'type' && value !== 'integer' && value !== 'number') {
delete mcpProperties[index].minimum;
delete mcpProperties[index].maximum;
renderMcpProperties();
}
}
/**
* 删除参数
*/
function deleteMcpProperty(index) {
mcpProperties.splice(index, 1);
renderMcpProperties();
}
/**
* 设置事件监听
*/
function setupMcpEventListeners() {
const toggleBtn = document.getElementById('toggleMcpTools');
const panel = document.getElementById('mcpToolsPanel');
const addBtn = document.getElementById('addMcpToolBtn');
const modal = document.getElementById('mcpToolModal');
const closeBtn = document.getElementById('closeMcpModalBtn');
const cancelBtn = document.getElementById('cancelMcpBtn');
const form = document.getElementById('mcpToolForm');
const addPropertyBtn = document.getElementById('addMcpPropertyBtn');
toggleBtn.addEventListener('click', () => {
const isExpanded = panel.classList.contains('expanded');
panel.classList.toggle('expanded');
toggleBtn.textContent = isExpanded ? '展开' : '收起';
});
addBtn.addEventListener('click', () => openMcpModal());
closeBtn.addEventListener('click', closeMcpModal);
cancelBtn.addEventListener('click', closeMcpModal);
addPropertyBtn.addEventListener('click', addMcpProperty);
modal.addEventListener('click', (e) => {
if (e.target === modal) closeMcpModal();
});
form.addEventListener('submit', handleMcpSubmit);
}
/**
* 打开模态框
*/
function openMcpModal(index = null) {
const isConnected = websocket && websocket.readyState === WebSocket.OPEN;
if (isConnected) {
alert('WebSocket 已连接,无法编辑工具');
return;
}
mcpEditingIndex = index;
const errorContainer = document.getElementById('mcpErrorContainer');
errorContainer.innerHTML = '';
if (index !== null) {
document.getElementById('mcpModalTitle').textContent = '编辑工具';
const tool = mcpTools[index];
document.getElementById('mcpToolName').value = tool.name;
document.getElementById('mcpToolDescription').value = tool.description;
document.getElementById('mcpMockResponse').value = tool.mockResponse ? JSON.stringify(tool.mockResponse, null, 2) : '';
mcpProperties = [];
const schema = tool.inputSchema;
if (schema.properties) {
Object.keys(schema.properties).forEach(key => {
const prop = schema.properties[key];
mcpProperties.push({
name: key,
type: prop.type || 'string',
minimum: prop.minimum,
maximum: prop.maximum,
description: prop.description || '',
required: schema.required && schema.required.includes(key)
});
});
}
} else {
document.getElementById('mcpModalTitle').textContent = '添加工具';
document.getElementById('mcpToolForm').reset();
mcpProperties = [];
}
renderMcpProperties();
document.getElementById('mcpToolModal').style.display = 'block';
}
/**
* 关闭模态框
*/
function closeMcpModal() {
document.getElementById('mcpToolModal').style.display = 'none';
mcpEditingIndex = null;
document.getElementById('mcpToolForm').reset();
mcpProperties = [];
document.getElementById('mcpErrorContainer').innerHTML = '';
}
/**
* 处理表单提交
*/
function handleMcpSubmit(e) {
e.preventDefault();
const errorContainer = document.getElementById('mcpErrorContainer');
errorContainer.innerHTML = '';
const name = document.getElementById('mcpToolName').value.trim();
const description = document.getElementById('mcpToolDescription').value.trim();
const mockResponseText = document.getElementById('mcpMockResponse').value.trim();
// 检查名称重复
const isDuplicate = mcpTools.some((tool, index) =>
tool.name === name && index !== mcpEditingIndex
);
if (isDuplicate) {
showMcpError('工具名称已存在,请使用不同的名称');
return;
}
// 解析模拟返回结果
let mockResponse = null;
if (mockResponseText) {
try {
mockResponse = JSON.parse(mockResponseText);
} catch (e) {
showMcpError('模拟返回结果不是有效的 JSON 格式: ' + e.message);
return;
}
}
// 构建 inputSchema
const inputSchema = {
type: "object",
properties: {},
required: []
};
mcpProperties.forEach(prop => {
const propSchema = { type: prop.type };
if (prop.description) {
propSchema.description = prop.description;
}
if ((prop.type === 'integer' || prop.type === 'number')) {
if (prop.minimum !== undefined && prop.minimum !== '') {
propSchema.minimum = prop.minimum;
}
if (prop.maximum !== undefined && prop.maximum !== '') {
propSchema.maximum = prop.maximum;
}
}
inputSchema.properties[prop.name] = propSchema;
if (prop.required) {
inputSchema.required.push(prop.name);
}
});
if (inputSchema.required.length === 0) {
delete inputSchema.required;
}
const tool = { name, description, inputSchema, mockResponse };
if (mcpEditingIndex !== null) {
mcpTools[mcpEditingIndex] = tool;
log(`已更新工具: ${name}`, 'success');
} else {
mcpTools.push(tool);
log(`已添加工具: ${name}`, 'success');
}
saveMcpTools();
renderMcpTools();
closeMcpModal();
}
/**
* 显示错误
*/
function showMcpError(message) {
const errorContainer = document.getElementById('mcpErrorContainer');
errorContainer.innerHTML = `<div class="mcp-error">${message}</div>`;
}
/**
* 编辑工具
*/
function editMcpTool(index) {
openMcpModal(index);
}
/**
* 删除工具
*/
function deleteMcpTool(index) {
const isConnected = websocket && websocket.readyState === WebSocket.OPEN;
if (isConnected) {
alert('WebSocket 已连接,无法编辑工具');
return;
}
if (confirm(`确定要删除工具 "${mcpTools[index].name}" 吗?`)) {
const toolName = mcpTools[index].name;
mcpTools.splice(index, 1);
saveMcpTools();
renderMcpTools();
log(`已删除工具: ${toolName}`, 'info');
}
}
/**
* 保存工具
*/
function saveMcpTools() {
localStorage.setItem('mcpTools', JSON.stringify(mcpTools));
}
/**
* 获取工具列表
*/
export function getMcpTools() {
return mcpTools.map(tool => ({
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema
}));
}
/**
* 执行工具调用
*/
export function executeMcpTool(toolName, toolArgs) {
const tool = mcpTools.find(t => t.name === toolName);
if (!tool) {
log(`未找到工具: ${toolName}`, 'error');
return {
success: false,
error: `未知工具: ${toolName}`
};
}
// 如果有模拟返回结果,使用它
if (tool.mockResponse) {
// 替换模板变量
let responseStr = JSON.stringify(tool.mockResponse);
// 替换 ${paramName} 格式的变量
if (toolArgs) {
Object.keys(toolArgs).forEach(key => {
const regex = new RegExp(`\\$\\{${key}\\}`, 'g');
responseStr = responseStr.replace(regex, toolArgs[key]);
});
}
try {
const response = JSON.parse(responseStr);
log(`工具 ${toolName} 执行成功,返回模拟结果: ${responseStr}`, 'success');
return response;
} catch (e) {
log(`解析模拟返回结果失败: ${e.message}`, 'error');
return tool.mockResponse;
}
}
// 没有模拟返回结果,返回默认成功消息
log(`工具 ${toolName} 执行成功,返回默认结果`, 'success');
return {
success: true,
message: `工具 ${toolName} 执行成功`,
tool: toolName,
arguments: toolArgs
};
}
// 暴露全局方法供 HTML 内联事件调用
window.mcpModule = {
updateMcpProperty,
deleteMcpProperty,
editMcpTool,
deleteMcpTool
};
@@ -1,5 +1,5 @@
import { otaStatusStyle } from './document.js';
import { log } from './utils/logger.js';
import { otaStatusStyle } from '../../ui/dom-helper.js';
import { log } from '../../utils/logger.js';
// WebSocket 连接
export async function webSocketConnect(otaUrl, config) {
@@ -0,0 +1,372 @@
// WebSocket消息处理模块
import { log } from '../../utils/logger.js';
import { addMessage } from '../../ui/dom-helper.js';
import { webSocketConnect } from './ota-connector.js';
import { getConfig, saveConnectionUrls } from '../../config/manager.js';
import { getAudioPlayer } from '../audio/player.js';
import { getAudioRecorder } from '../audio/recorder.js';
import { getMcpTools, executeMcpTool, setWebSocket as setMcpWebSocket } from '../mcp/tools.js';
// WebSocket处理器类
export class WebSocketHandler {
constructor() {
this.websocket = null;
this.onConnectionStateChange = null;
this.onRecordButtonStateChange = null;
this.onSessionStateChange = null;
this.onSessionEmotionChange = null;
this.currentSessionId = null;
this.isRemoteSpeaking = false;
}
// 发送hello握手消息
async sendHelloMessage() {
if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) return false;
try {
const config = getConfig();
const helloMessage = {
type: 'hello',
device_id: config.deviceId,
device_name: config.deviceName,
device_mac: config.deviceMac,
token: config.token,
features: {
mcp: true
}
};
log('发送hello握手消息', 'info');
this.websocket.send(JSON.stringify(helloMessage));
return new Promise(resolve => {
const timeout = setTimeout(() => {
log('等待hello响应超时', 'error');
log('提示: 请尝试点击"测试认证"按钮进行连接排查', 'info');
resolve(false);
}, 5000);
const onMessageHandler = (event) => {
try {
const response = JSON.parse(event.data);
if (response.type === 'hello' && response.session_id) {
log(`服务器握手成功,会话ID: ${response.session_id}`, 'success');
clearTimeout(timeout);
this.websocket.removeEventListener('message', onMessageHandler);
resolve(true);
}
} catch (e) {
// 忽略非JSON消息
}
};
this.websocket.addEventListener('message', onMessageHandler);
});
} catch (error) {
log(`发送hello消息错误: ${error.message}`, 'error');
return false;
}
}
// 处理文本消息
handleTextMessage(message) {
if (message.type === 'hello') {
log(`服务器回应:${JSON.stringify(message, null, 2)}`, 'success');
} else if (message.type === 'tts') {
this.handleTTSMessage(message);
} else if (message.type === 'audio') {
log(`收到音频控制消息: ${JSON.stringify(message)}`, 'info');
} else if (message.type === 'stt') {
log(`识别结果: ${message.text}`, 'info');
addMessage(`${message.text}`, true);
} else if (message.type === 'llm') {
log(`大模型回复: ${message.text}`, 'info');
// 如果包含表情,更新sessionStatus表情
if (message.text && /[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/u.test(message.text)) {
// 提取表情符号
const emojiMatch = message.text.match(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/u);
if (emojiMatch && this.onSessionEmotionChange) {
this.onSessionEmotionChange(emojiMatch[0]);
}
}
// 只有当文本不仅仅是表情时,才添加到对话中
// 移除文本中的表情后检查是否还有内容
const textWithoutEmoji = message.text ? message.text.replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu, '').trim() : '';
if (textWithoutEmoji) {
addMessage(message.text);
}
} else if (message.type === 'mcp') {
this.handleMCPMessage(message);
} else {
log(`未知消息类型: ${message.type}`, 'info');
addMessage(JSON.stringify(message, null, 2));
}
}
// 处理TTS消息
handleTTSMessage(message) {
if (message.state === 'start') {
log('服务器开始发送语音', 'info');
this.currentSessionId = message.session_id;
this.isRemoteSpeaking = true;
if (this.onSessionStateChange) {
this.onSessionStateChange(true);
}
} else if (message.state === 'sentence_start') {
log(`服务器发送语音段: ${message.text}`, 'info');
if (message.text) {
addMessage(message.text);
}
} else if (message.state === 'sentence_end') {
log(`语音段结束: ${message.text}`, 'info');
} else if (message.state === 'stop') {
log('服务器语音传输结束', 'info');
this.isRemoteSpeaking = false;
if (this.onRecordButtonStateChange) {
this.onRecordButtonStateChange(false);
}
if (this.onSessionStateChange) {
this.onSessionStateChange(false);
}
}
}
// 处理MCP消息
handleMCPMessage(message) {
const payload = message.payload || {};
log(`服务器下发: ${JSON.stringify(message)}`, 'info');
if (payload.method === 'tools/list') {
const tools = getMcpTools();
const replyMessage = JSON.stringify({
"session_id": message.session_id || "",
"type": "mcp",
"payload": {
"jsonrpc": "2.0",
"id": payload.id,
"result": {
"tools": tools
}
}
});
log(`客户端上报: ${replyMessage}`, 'info');
this.websocket.send(replyMessage);
log(`回复MCP工具列表: ${tools.length} 个工具`, 'info');
} else if (payload.method === 'tools/call') {
const toolName = payload.params?.name;
const toolArgs = payload.params?.arguments;
log(`调用工具: ${toolName} 参数: ${JSON.stringify(toolArgs)}`, 'info');
const result = executeMcpTool(toolName, toolArgs);
const replyMessage = JSON.stringify({
"session_id": message.session_id || "",
"type": "mcp",
"payload": {
"jsonrpc": "2.0",
"id": payload.id,
"result": {
"content": [
{
"type": "text",
"text": JSON.stringify(result)
}
],
"isError": false
}
}
});
log(`客户端上报: ${replyMessage}`, 'info');
this.websocket.send(replyMessage);
} else if (payload.method === 'initialize') {
log(`收到工具初始化请求: ${JSON.stringify(payload.params)}`, 'info');
} else {
log(`未知的MCP方法: ${payload.method}`, 'warning');
}
}
// 处理二进制消息
async handleBinaryMessage(data) {
try {
let arrayBuffer;
if (data instanceof ArrayBuffer) {
arrayBuffer = data;
log(`收到ArrayBuffer音频数据,大小: ${data.byteLength}字节`, 'debug');
} else if (data instanceof Blob) {
arrayBuffer = await data.arrayBuffer();
log(`收到Blob音频数据,大小: ${arrayBuffer.byteLength}字节`, 'debug');
} else {
log(`收到未知类型的二进制数据: ${typeof data}`, 'warning');
return;
}
const opusData = new Uint8Array(arrayBuffer);
const audioPlayer = getAudioPlayer();
audioPlayer.enqueueAudioData(opusData);
} catch (error) {
log(`处理二进制消息出错: ${error.message}`, 'error');
}
}
// 连接WebSocket服务器
async connect() {
const config = getConfig();
log('正在检查OTA状态...', 'info');
saveConnectionUrls();
try {
const otaUrl = document.getElementById('otaUrl').value.trim();
const ws = await webSocketConnect(otaUrl, config);
if (ws === undefined) {
return false;
}
this.websocket = ws;
// 设置接收二进制数据的类型为ArrayBuffer
this.websocket.binaryType = 'arraybuffer';
// 设置 MCP 模块的 WebSocket 实例
setMcpWebSocket(this.websocket);
// 设置录音器的WebSocket
const audioRecorder = getAudioRecorder();
audioRecorder.setWebSocket(this.websocket);
this.setupEventHandlers();
return true;
} catch (error) {
log(`连接错误: ${error.message}`, 'error');
if (this.onConnectionStateChange) {
this.onConnectionStateChange(false);
}
return false;
}
}
// 设置事件处理器
setupEventHandlers() {
this.websocket.onopen = async () => {
const url = document.getElementById('serverUrl').value;
log(`已连接到服务器: ${url}`, 'success');
if (this.onConnectionStateChange) {
this.onConnectionStateChange(true);
}
// 连接成功后,默认状态为聆听中
this.isRemoteSpeaking = false;
if (this.onSessionStateChange) {
this.onSessionStateChange(false);
}
await this.sendHelloMessage();
};
this.websocket.onclose = () => {
log('已断开连接', 'info');
if (this.onConnectionStateChange) {
this.onConnectionStateChange(false);
}
const audioRecorder = getAudioRecorder();
audioRecorder.stop();
};
this.websocket.onerror = (error) => {
log(`WebSocket错误: ${error.message || '未知错误'}`, 'error');
if (this.onConnectionStateChange) {
this.onConnectionStateChange(false);
}
};
this.websocket.onmessage = (event) => {
try {
if (typeof event.data === 'string') {
const message = JSON.parse(event.data);
this.handleTextMessage(message);
} else {
this.handleBinaryMessage(event.data);
}
} catch (error) {
log(`WebSocket消息处理错误: ${error.message}`, 'error');
if (typeof event.data === 'string') {
addMessage(event.data);
}
}
};
}
// 断开连接
disconnect() {
if (!this.websocket) return;
this.websocket.close();
const audioRecorder = getAudioRecorder();
audioRecorder.stop();
}
// 发送文本消息
sendTextMessage(text) {
if (text === '' || !this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
return false;
}
try {
// 如果对方正在说话,先发送打断消息
if (this.isRemoteSpeaking && this.currentSessionId) {
const abortMessage = {
session_id: this.currentSessionId,
type: 'abort',
reason: 'wake_word_detected'
};
this.websocket.send(JSON.stringify(abortMessage));
log('发送打断消息', 'info');
}
const listenMessage = {
type: 'listen',
mode: 'manual',
state: 'detect',
text: text
};
this.websocket.send(JSON.stringify(listenMessage));
log(`发送文本消息: ${text}`, 'info');
return true;
} catch (error) {
log(`发送消息错误: ${error.message}`, 'error');
return false;
}
}
// 获取WebSocket实例
getWebSocket() {
return this.websocket;
}
// 检查是否已连接
isConnected() {
return this.websocket && this.websocket.readyState === WebSocket.OPEN;
}
}
// 创建单例
let wsHandlerInstance = null;
export function getWebSocketHandler() {
if (!wsHandlerInstance) {
wsHandlerInstance = new WebSocketHandler();
}
return wsHandlerInstance;
}
@@ -0,0 +1,274 @@
// UI控制模块
import { loadConfig, saveConfig } from '../config/manager.js';
import { getAudioRecorder } from '../core/audio/recorder.js';
import { getWebSocketHandler } from '../core/network/websocket.js';
// UI控制器类
export class UIController {
constructor() {
this.isEditing = false;
this.visualizerCanvas = null;
this.visualizerContext = null;
}
// 初始化
init() {
this.visualizerCanvas = document.getElementById('audioVisualizer');
this.visualizerContext = this.visualizerCanvas.getContext('2d');
this.initVisualizer();
this.initEventListeners();
loadConfig();
}
// 初始化可视化器
initVisualizer() {
this.visualizerCanvas.width = this.visualizerCanvas.clientWidth;
this.visualizerCanvas.height = this.visualizerCanvas.clientHeight;
this.visualizerContext.fillStyle = '#fafafa';
this.visualizerContext.fillRect(0, 0, this.visualizerCanvas.width, this.visualizerCanvas.height);
}
// 更新状态显示
updateStatusDisplay(element, text) {
element.textContent = text;
element.removeAttribute('style');
element.classList.remove('connected');
if (text.includes('已连接')) {
element.classList.add('connected');
}
console.log('更新状态:', text, '类列表:', element.className, '样式属性:', element.getAttribute('style'));
}
// 更新连接状态UI
updateConnectionUI(isConnected) {
const connectionStatus = document.getElementById('connectionStatus');
const otaStatus = document.getElementById('otaStatus');
const connectButton = document.getElementById('connectButton');
const messageInput = document.getElementById('messageInput');
const sendTextButton = document.getElementById('sendTextButton');
const recordButton = document.getElementById('recordButton');
if (isConnected) {
this.updateStatusDisplay(connectionStatus, '● WS已连接');
this.updateStatusDisplay(otaStatus, '● OTA已连接');
connectButton.textContent = '断开';
messageInput.disabled = false;
sendTextButton.disabled = false;
recordButton.disabled = false;
} else {
this.updateStatusDisplay(connectionStatus, '● WS未连接');
this.updateStatusDisplay(otaStatus, '● OTA未连接');
connectButton.textContent = '连接';
messageInput.disabled = true;
sendTextButton.disabled = true;
recordButton.disabled = true;
// 断开连接时,会话状态变为离线
this.updateSessionStatus(null);
}
}
// 更新录音按钮状态
updateRecordButtonState(isRecording, seconds = 0) {
const recordButton = document.getElementById('recordButton');
if (isRecording) {
recordButton.textContent = `停止录音 ${seconds.toFixed(1)}`;
recordButton.classList.add('recording');
} else {
recordButton.textContent = '开始录音';
recordButton.classList.remove('recording');
}
recordButton.disabled = false;
}
// 更新会话状态UI
updateSessionStatus(isSpeaking) {
const sessionStatus = document.getElementById('sessionStatus');
if (!sessionStatus) return;
if (isSpeaking === null) {
// 离线状态
sessionStatus.innerHTML = '<span class="emoji-large">😶</span> 小智离线中';
sessionStatus.className = 'status offline';
} else if (isSpeaking) {
// 说话中
sessionStatus.innerHTML = '<span class="emoji-large">😶</span> 小智说话中';
sessionStatus.className = 'status speaking';
} else {
// 聆听中
sessionStatus.innerHTML = '<span class="emoji-large">😶</span> 小智聆听中';
sessionStatus.className = 'status listening';
}
}
// 更新会话表情
updateSessionEmotion(emoji) {
const sessionStatus = document.getElementById('sessionStatus');
if (!sessionStatus) return;
// 获取当前文本内容,提取非表情部分
let currentText = sessionStatus.textContent;
// 移除现有的表情符号
currentText = currentText.replace(/[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu, '').trim();
// 使用 innerHTML 添加带样式的表情
sessionStatus.innerHTML = `<span class="emoji-large">${emoji}</span> ${currentText}`;
}
// 绘制音频可视化效果
drawVisualizer(dataArray) {
this.visualizerContext.fillStyle = '#fafafa';
this.visualizerContext.fillRect(0, 0, this.visualizerCanvas.width, this.visualizerCanvas.height);
const barWidth = (this.visualizerCanvas.width / dataArray.length) * 2.5;
let barHeight;
let x = 0;
for (let i = 0; i < dataArray.length; i++) {
barHeight = dataArray[i] / 2;
// 创建渐变色:从紫色到蓝色到青色
const hue = 200 + (barHeight / this.visualizerCanvas.height) * 60; // 200-260度,从青色到紫色
const saturation = 80 + (barHeight / this.visualizerCanvas.height) * 20; // 饱和度 80-100%
const lightness = 45 + (barHeight / this.visualizerCanvas.height) * 15; // 亮度 45-60%
this.visualizerContext.fillStyle = `hsl(${hue}, ${saturation}%, ${lightness}%)`;
this.visualizerContext.fillRect(x, this.visualizerCanvas.height - barHeight, barWidth, barHeight);
x += barWidth + 1;
}
}
// 初始化事件监听器
initEventListeners() {
const wsHandler = getWebSocketHandler();
const audioRecorder = getAudioRecorder();
// 设置WebSocket回调
wsHandler.onConnectionStateChange = (isConnected) => {
this.updateConnectionUI(isConnected);
};
wsHandler.onRecordButtonStateChange = (isRecording) => {
this.updateRecordButtonState(isRecording);
};
wsHandler.onSessionStateChange = (isSpeaking) => {
this.updateSessionStatus(isSpeaking);
};
wsHandler.onSessionEmotionChange = (emoji) => {
this.updateSessionEmotion(emoji);
};
// 设置录音器回调
audioRecorder.onRecordingStart = (seconds) => {
this.updateRecordButtonState(true, seconds);
};
audioRecorder.onRecordingStop = () => {
this.updateRecordButtonState(false);
};
audioRecorder.onVisualizerUpdate = (dataArray) => {
this.drawVisualizer(dataArray);
};
// 连接按钮
const connectButton = document.getElementById('connectButton');
let isConnecting = false;
const handleConnect = async () => {
if (isConnecting) return;
if (wsHandler.isConnected()) {
wsHandler.disconnect();
} else {
isConnecting = true;
await wsHandler.connect();
isConnecting = false;
}
};
connectButton.addEventListener('click', handleConnect);
// 设备配置面板编辑/确定切换
const toggleButton = document.getElementById('toggleConfig');
const deviceMacInput = document.getElementById('deviceMac');
const deviceNameInput = document.getElementById('deviceName');
const clientIdInput = document.getElementById('clientId');
const tokenInput = document.getElementById('token');
toggleButton.addEventListener('click', () => {
this.isEditing = !this.isEditing;
deviceMacInput.disabled = !this.isEditing;
deviceNameInput.disabled = !this.isEditing;
clientIdInput.disabled = !this.isEditing;
tokenInput.disabled = !this.isEditing;
toggleButton.textContent = this.isEditing ? '确定' : '编辑';
if (!this.isEditing) {
saveConfig();
}
});
// 标签页切换
const tabs = document.querySelectorAll('.tab');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
tabs.forEach(t => t.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
tab.classList.add('active');
const tabContent = document.getElementById(`${tab.dataset.tab}Tab`);
tabContent.classList.add('active');
if (tab.dataset.tab === 'voice') {
setTimeout(() => {
this.initVisualizer();
}, 50);
}
});
});
// 发送文本消息
const messageInput = document.getElementById('messageInput');
const sendTextButton = document.getElementById('sendTextButton');
const sendMessage = () => {
const message = messageInput.value.trim();
if (message && wsHandler.sendTextMessage(message)) {
messageInput.value = '';
}
};
sendTextButton.addEventListener('click', sendMessage);
messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') sendMessage();
});
// 录音按钮
const recordButton = document.getElementById('recordButton');
recordButton.addEventListener('click', () => {
if (audioRecorder.isRecording) {
audioRecorder.stop();
} else {
audioRecorder.start();
}
});
// 窗口大小变化
window.addEventListener('resize', () => this.initVisualizer());
}
}
// 创建单例
let uiControllerInstance = null;
export function getUIController() {
if (!uiControllerInstance) {
uiControllerInstance = new UIController();
}
return uiControllerInstance;
}
@@ -12,19 +12,19 @@ const logContainer = document.getElementById('logContainer');
let visualizerCanvas = document.getElementById('audioVisualizer');
// ota 是否连接成功,修改成对应的样式
export function otaStatusStyle (flan) {
if(flan){
document.getElementById('otaStatus').textContent = 'ota已连接';
export function otaStatusStyle(flan) {
if (flan) {
document.getElementById('otaStatus').textContent = 'OTA已连接';
document.getElementById('otaStatus').style.color = 'green';
}else{
document.getElementById('otaStatus').textContent = 'ota未连接';
} else {
document.getElementById('otaStatus').textContent = 'OTA未连接';
document.getElementById('otaStatus').style.color = 'red';
}
}
// ota 是否连接成功,修改成对应的样式
export function getLogContainer (flan) {
return logContainer;
export function getLogContainer(flan) {
return logContainer;
}
// 更新Opus库状态显示
+1 -1
View File
@@ -1,4 +1,4 @@
import { getLogContainer } from '../document.js'
import { getLogContainer } from '../ui/dom-helper.js'
const logContainer = getLogContainer();
// 日志记录函数
-670
View File
@@ -1,670 +0,0 @@
const SAMPLE_RATE = 16000;
const CHANNELS = 1;
const FRAME_SIZE = 960; // 对应于60ms帧大小 (16000Hz * 0.06s = 960 samples)
const OPUS_APPLICATION = 2049; // OPUS_APPLICATION_AUDIO
const BUFFER_SIZE = 4096;
let audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: SAMPLE_RATE });
let mediaStream, mediaSource, audioProcessor;
let recordedPcmData = []; // 存储原始PCM数据
let recordedOpusData = []; // 存储Opus编码后的数据
let opusEncoder, opusDecoder;
let isRecording = false;
const startButton = document.getElementById("start");
const stopButton = document.getElementById("stop");
const playButton = document.getElementById("play");
const statusLabel = document.getElementById("status");
startButton.addEventListener("click", startRecording);
stopButton.addEventListener("click", stopRecording);
playButton.addEventListener("click", playRecording);
// 初始化Opus编码器与解码器
async function initOpus() {
if (typeof window.ModuleInstance === 'undefined') {
if (typeof Module !== 'undefined') {
// 尝试使用全局Module
window.ModuleInstance = Module;
console.log('使用全局Module作为ModuleInstance');
} else {
console.error("Opus库未加载,ModuleInstance和Module对象都不存在");
return false;
}
}
try {
const mod = window.ModuleInstance;
// 创建编码器
opusEncoder = {
channels: CHANNELS,
sampleRate: SAMPLE_RATE,
frameSize: FRAME_SIZE,
maxPacketSize: 4000,
module: mod,
// 初始化编码器
init: function() {
// 获取编码器大小
const encoderSize = mod._opus_encoder_get_size(this.channels);
console.log(`Opus编码器大小: ${encoderSize}字节`);
// 分配内存
this.encoderPtr = mod._malloc(encoderSize);
if (!this.encoderPtr) {
throw new Error("无法分配编码器内存");
}
// 初始化编码器
const err = mod._opus_encoder_init(
this.encoderPtr,
this.sampleRate,
this.channels,
OPUS_APPLICATION
);
if (err < 0) {
throw new Error(`Opus编码器初始化失败: ${err}`);
}
return true;
},
// 编码方法
encode: function(pcmData) {
const mod = this.module;
// 为PCM数据分配内存
const pcmPtr = mod._malloc(pcmData.length * 2); // Int16 = 2字节
// 将数据复制到WASM内存
for (let i = 0; i < pcmData.length; i++) {
mod.HEAP16[(pcmPtr >> 1) + i] = pcmData[i];
}
// 为Opus编码数据分配内存
const maxEncodedSize = this.maxPacketSize;
const encodedPtr = mod._malloc(maxEncodedSize);
// 编码
const encodedBytes = mod._opus_encode(
this.encoderPtr,
pcmPtr,
this.frameSize,
encodedPtr,
maxEncodedSize
);
if (encodedBytes < 0) {
mod._free(pcmPtr);
mod._free(encodedPtr);
throw new Error(`Opus编码失败: ${encodedBytes}`);
}
// 复制编码后的数据
const encodedData = new Uint8Array(encodedBytes);
for (let i = 0; i < encodedBytes; i++) {
encodedData[i] = mod.HEAPU8[encodedPtr + i];
}
// 释放内存
mod._free(pcmPtr);
mod._free(encodedPtr);
return encodedData;
},
// 销毁方法
destroy: function() {
if (this.encoderPtr) {
this.module._free(this.encoderPtr);
this.encoderPtr = null;
}
}
};
// 创建解码器
opusDecoder = {
channels: CHANNELS,
rate: SAMPLE_RATE,
frameSize: FRAME_SIZE,
module: mod,
// 初始化解码器
init: function() {
// 获取解码器大小
const decoderSize = mod._opus_decoder_get_size(this.channels);
console.log(`Opus解码器大小: ${decoderSize}字节`);
// 分配内存
this.decoderPtr = mod._malloc(decoderSize);
if (!this.decoderPtr) {
throw new Error("无法分配解码器内存");
}
// 初始化解码器
const err = mod._opus_decoder_init(
this.decoderPtr,
this.rate,
this.channels
);
if (err < 0) {
throw new Error(`Opus解码器初始化失败: ${err}`);
}
return true;
},
// 解码方法
decode: function(opusData) {
const mod = this.module;
// 为Opus数据分配内存
const opusPtr = mod._malloc(opusData.length);
mod.HEAPU8.set(opusData, opusPtr);
// 为PCM输出分配内存
const pcmPtr = mod._malloc(this.frameSize * 2); // Int16 = 2字节
// 解码
const decodedSamples = mod._opus_decode(
this.decoderPtr,
opusPtr,
opusData.length,
pcmPtr,
this.frameSize,
0 // 不使用FEC
);
if (decodedSamples < 0) {
mod._free(opusPtr);
mod._free(pcmPtr);
throw new Error(`Opus解码失败: ${decodedSamples}`);
}
// 复制解码后的数据
const decodedData = new Int16Array(decodedSamples);
for (let i = 0; i < decodedSamples; i++) {
decodedData[i] = mod.HEAP16[(pcmPtr >> 1) + i];
}
// 释放内存
mod._free(opusPtr);
mod._free(pcmPtr);
return decodedData;
},
// 销毁方法
destroy: function() {
if (this.decoderPtr) {
this.module._free(this.decoderPtr);
this.decoderPtr = null;
}
}
};
// 初始化编码器和解码器
if (opusEncoder.init() && opusDecoder.init()) {
console.log("Opus 编码器和解码器初始化成功。");
return true;
} else {
console.error("Opus 初始化失败");
return false;
}
} catch (error) {
console.error("Opus 初始化失败:", error);
return false;
}
}
// 将Float32音频数据转换为Int16音频数据
function convertFloat32ToInt16(float32Data) {
const int16Data = new Int16Array(float32Data.length);
for (let i = 0; i < float32Data.length; i++) {
// 将[-1,1]范围转换为[-32768,32767]
const s = Math.max(-1, Math.min(1, float32Data[i]));
int16Data[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
}
return int16Data;
}
// 将Int16音频数据转换为Float32音频数据
function convertInt16ToFloat32(int16Data) {
const float32Data = new Float32Array(int16Data.length);
for (let i = 0; i < int16Data.length; i++) {
// 将[-32768,32767]范围转换为[-1,1]
float32Data[i] = int16Data[i] / (int16Data[i] < 0 ? 0x8000 : 0x7FFF);
}
return float32Data;
}
function startRecording() {
if (isRecording) return;
// 确保有权限并且AudioContext是活跃的
if (audioContext.state === 'suspended') {
audioContext.resume().then(() => {
console.log("AudioContext已恢复");
continueStartRecording();
}).catch(err => {
console.error("恢复AudioContext失败:", err);
statusLabel.textContent = "无法激活音频上下文,请再次点击";
});
} else {
continueStartRecording();
}
}
// 实际开始录音的逻辑
function continueStartRecording() {
// 重置录音数据
recordedPcmData = [];
recordedOpusData = [];
window.audioDataBuffer = new Int16Array(0); // 重置缓冲区
// 初始化Opus
initOpus().then(success => {
if (!success) {
statusLabel.textContent = "Opus初始化失败";
return;
}
console.log("开始录音,参数:", {
sampleRate: SAMPLE_RATE,
channels: CHANNELS,
frameSize: FRAME_SIZE,
bufferSize: BUFFER_SIZE
});
// 请求麦克风权限
navigator.mediaDevices.getUserMedia({
audio: {
sampleRate: SAMPLE_RATE,
channelCount: CHANNELS,
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true
}
})
.then(stream => {
console.log("获取到麦克风流,实际参数:", stream.getAudioTracks()[0].getSettings());
// 检查流是否有效
if (!stream || !stream.getAudioTracks().length || !stream.getAudioTracks()[0].enabled) {
throw new Error("获取到的音频流无效");
}
mediaStream = stream;
mediaSource = audioContext.createMediaStreamSource(stream);
// 创建ScriptProcessor(虽然已弃用,但兼容性好)
// 在降级到ScriptProcessor之前尝试使用AudioWorklet
createAudioProcessor().then(processor => {
if (processor) {
console.log("使用AudioWorklet处理音频");
audioProcessor = processor;
// 连接音频处理链
mediaSource.connect(audioProcessor);
audioProcessor.connect(audioContext.destination);
} else {
console.log("回退到ScriptProcessor");
// 创建ScriptProcessor节点
audioProcessor = audioContext.createScriptProcessor(BUFFER_SIZE, CHANNELS, CHANNELS);
// 处理音频数据
audioProcessor.onaudioprocess = processAudioData;
// 连接音频处理链
mediaSource.connect(audioProcessor);
audioProcessor.connect(audioContext.destination);
}
// 更新UI
isRecording = true;
statusLabel.textContent = "录音中...";
startButton.disabled = true;
stopButton.disabled = false;
playButton.disabled = true;
}).catch(error => {
console.error("创建音频处理器失败:", error);
statusLabel.textContent = "创建音频处理器失败";
});
})
.catch(error => {
console.error("获取麦克风失败:", error);
statusLabel.textContent = "获取麦克风失败: " + error.message;
});
});
}
// 创建AudioWorklet处理器
async function createAudioProcessor() {
try {
// 尝试使用更现代的AudioWorklet API
if ('AudioWorklet' in window && 'AudioWorkletNode' in window) {
// 定义AudioWorklet处理器代码
const workletCode = `
class OpusRecorderProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.buffers = [];
this.frameSize = ${FRAME_SIZE};
this.buffer = new Float32Array(this.frameSize);
this.bufferIndex = 0;
this.isRecording = false;
this.port.onmessage = (event) => {
if (event.data.command === 'start') {
this.isRecording = true;
} else if (event.data.command === 'stop') {
this.isRecording = false;
// 发送最后的缓冲区
if (this.bufferIndex > 0) {
const finalBuffer = this.buffer.slice(0, this.bufferIndex);
this.port.postMessage({ buffer: finalBuffer });
}
}
};
}
process(inputs, outputs) {
if (!this.isRecording) return true;
// 获取输入数据
const input = inputs[0][0]; // mono channel
if (!input || input.length === 0) return true;
// 将输入数据添加到缓冲区
for (let i = 0; i < input.length; i++) {
this.buffer[this.bufferIndex++] = input[i];
// 当缓冲区填满时,发送给主线程
if (this.bufferIndex >= this.frameSize) {
this.port.postMessage({ buffer: this.buffer.slice() });
this.bufferIndex = 0;
}
}
return true;
}
}
registerProcessor('opus-recorder-processor', OpusRecorderProcessor);
`;
// 创建Blob URL
const blob = new Blob([workletCode], { type: 'application/javascript' });
const url = URL.createObjectURL(blob);
// 加载AudioWorklet模块
await audioContext.audioWorklet.addModule(url);
// 创建AudioWorkletNode
const workletNode = new AudioWorkletNode(audioContext, 'opus-recorder-processor');
// 处理从AudioWorklet接收的消息
workletNode.port.onmessage = (event) => {
if (event.data.buffer) {
// 使用与ScriptProcessor相同的处理逻辑
processAudioData({
inputBuffer: {
getChannelData: () => event.data.buffer
}
});
}
};
// 启动录音
workletNode.port.postMessage({ command: 'start' });
// 保存停止函数
workletNode.stopRecording = () => {
workletNode.port.postMessage({ command: 'stop' });
};
console.log("AudioWorklet 音频处理器创建成功");
return workletNode;
}
} catch (error) {
console.error("创建AudioWorklet失败,将使用ScriptProcessor:", error);
}
// 如果AudioWorklet不可用或失败,返回null以便回退到ScriptProcessor
return null;
}
// 处理音频数据
function processAudioData(e) {
// 获取输入缓冲区
const inputBuffer = e.inputBuffer;
// 获取第一个通道的Float32数据
const inputData = inputBuffer.getChannelData(0);
// 添加调试信息
const nonZeroCount = Array.from(inputData).filter(x => Math.abs(x) > 0.001).length;
console.log(`接收到音频数据: ${inputData.length} 个样本, 非零样本数: ${nonZeroCount}`);
// 如果全是0,可能是麦克风没有正确获取声音
if (nonZeroCount < 5) {
console.warn("警告: 检测到大量静音样本,请检查麦克风是否正常工作");
// 继续处理,以防有些样本确实是静音
}
// 存储PCM数据用于调试
recordedPcmData.push(new Float32Array(inputData));
// 转换为Int16数据供Opus编码
const int16Data = convertFloat32ToInt16(inputData);
// 如果收集到的数据不是FRAME_SIZE的整数倍,需要进行处理
// 创建静态缓冲区来存储不足一帧的数据
if (!window.audioDataBuffer) {
window.audioDataBuffer = new Int16Array(0);
}
// 合并之前缓存的数据和新数据
const combinedData = new Int16Array(window.audioDataBuffer.length + int16Data.length);
combinedData.set(window.audioDataBuffer);
combinedData.set(int16Data, window.audioDataBuffer.length);
// 处理完整帧
const frameCount = Math.floor(combinedData.length / FRAME_SIZE);
console.log(`可编码的完整帧数: ${frameCount}, 缓冲区总大小: ${combinedData.length}`);
for (let i = 0; i < frameCount; i++) {
const frameData = combinedData.subarray(i * FRAME_SIZE, (i + 1) * FRAME_SIZE);
try {
console.log(`编码第 ${i+1}/${frameCount} 帧, 帧大小: ${frameData.length}`);
const encodedData = opusEncoder.encode(frameData);
if (encodedData) {
console.log(`编码成功: ${encodedData.length} 字节`);
recordedOpusData.push(encodedData);
}
} catch (error) {
console.error(`Opus编码帧 ${i+1} 失败:`, error);
}
}
// 保存剩余不足一帧的数据
const remainingSamples = combinedData.length % FRAME_SIZE;
if (remainingSamples > 0) {
window.audioDataBuffer = combinedData.subarray(frameCount * FRAME_SIZE);
console.log(`保留 ${remainingSamples} 个样本到下一次处理`);
} else {
window.audioDataBuffer = new Int16Array(0);
}
}
function stopRecording() {
if (!isRecording) return;
// 处理剩余的缓冲数据
if (window.audioDataBuffer && window.audioDataBuffer.length > 0) {
console.log(`停止录音,处理剩余的 ${window.audioDataBuffer.length} 个样本`);
// 如果剩余数据不足一帧,可以通过补零的方式凑成一帧
if (window.audioDataBuffer.length < FRAME_SIZE) {
const paddedFrame = new Int16Array(FRAME_SIZE);
paddedFrame.set(window.audioDataBuffer);
// 剩余部分填充为0
for (let i = window.audioDataBuffer.length; i < FRAME_SIZE; i++) {
paddedFrame[i] = 0;
}
try {
console.log(`编码最后一帧(补零): ${paddedFrame.length} 样本`);
const encodedData = opusEncoder.encode(paddedFrame);
if (encodedData) {
recordedOpusData.push(encodedData);
}
} catch (error) {
console.error("最后一帧Opus编码失败:", error);
}
} else {
// 如果数据超过一帧,按正常流程处理
processAudioData({
inputBuffer: {
getChannelData: () => convertInt16ToFloat32(window.audioDataBuffer)
}
});
}
window.audioDataBuffer = null;
}
// 如果使用的是AudioWorklet,调用其特定的停止方法
if (audioProcessor && typeof audioProcessor.stopRecording === 'function') {
audioProcessor.stopRecording();
}
// 停止麦克风
if (mediaStream) {
mediaStream.getTracks().forEach(track => track.stop());
}
// 断开音频处理链
if (audioProcessor) {
try {
audioProcessor.disconnect();
if (mediaSource) mediaSource.disconnect();
} catch (error) {
console.warn("断开音频处理链时出错:", error);
}
}
// 更新UI
isRecording = false;
statusLabel.textContent = "已停止录音,收集了 " + recordedOpusData.length + " 帧Opus数据";
startButton.disabled = false;
stopButton.disabled = true;
playButton.disabled = recordedOpusData.length === 0;
console.log("录制完成:",
"PCM帧数:", recordedPcmData.length,
"Opus帧数:", recordedOpusData.length);
}
function playRecording() {
if (!recordedOpusData.length) {
statusLabel.textContent = "没有可播放的录音";
return;
}
// 将所有Opus数据解码为PCM
let allDecodedData = [];
for (const opusData of recordedOpusData) {
try {
// 解码为Int16数据
const decodedData = opusDecoder.decode(opusData);
if (decodedData && decodedData.length > 0) {
// 将Int16数据转换为Float32
const float32Data = convertInt16ToFloat32(decodedData);
// 添加到总解码数据中
allDecodedData.push(...float32Data);
}
} catch (error) {
console.error("Opus解码失败:", error);
}
}
// 如果没有解码出数据,返回
if (allDecodedData.length === 0) {
statusLabel.textContent = "解码失败,无法播放";
return;
}
// 创建音频缓冲区
const audioBuffer = audioContext.createBuffer(CHANNELS, allDecodedData.length, SAMPLE_RATE);
audioBuffer.copyToChannel(new Float32Array(allDecodedData), 0);
// 创建音频源并播放
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
source.start();
// 更新UI
statusLabel.textContent = "正在播放...";
playButton.disabled = true;
// 播放结束后恢复UI
source.onended = () => {
statusLabel.textContent = "播放完毕";
playButton.disabled = false;
};
}
// 模拟服务端返回的Opus数据进行解码播放
function playOpusFromServer(opusData) {
// 这个函数展示如何处理服务端返回的opus数据
// opusData应该是一个包含opus帧的数组
if (!opusDecoder) {
initOpus().then(success => {
if (success) {
decodeAndPlayOpusData(opusData);
} else {
statusLabel.textContent = "Opus解码器初始化失败";
}
});
} else {
decodeAndPlayOpusData(opusData);
}
}
function decodeAndPlayOpusData(opusData) {
let allDecodedData = [];
for (const frame of opusData) {
try {
const decodedData = opusDecoder.decode(frame);
if (decodedData && decodedData.length > 0) {
const float32Data = convertInt16ToFloat32(decodedData);
allDecodedData.push(...float32Data);
}
} catch (error) {
console.error("服务端Opus数据解码失败:", error);
}
}
if (allDecodedData.length === 0) {
statusLabel.textContent = "服务端数据解码失败";
return;
}
const audioBuffer = audioContext.createBuffer(CHANNELS, allDecodedData.length, SAMPLE_RATE);
audioBuffer.copyToChannel(new Float32Array(allDecodedData), 0);
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
source.start();
statusLabel.textContent = "正在播放服务端数据...";
source.onended = () => statusLabel.textContent = "服务端数据播放完毕";
}
@@ -1,464 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Opus 编解码测试</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.container {
background-color: #f5f5f5;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
button {
padding: 8px 15px;
margin-right: 10px;
border: none;
border-radius: 5px;
background-color: #4285f4;
color: white;
cursor: pointer;
transition: background-color 0.2s;
}
button:hover {
background-color: #3367d6;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
#status {
font-weight: bold;
}
#scriptStatus {
position: fixed;
top: 10px;
left: 50%;
transform: translateX(-50%);
padding: 15px;
border-radius: 5px;
display: block;
z-index: 100;
transition: all 0.3s ease;
}
#scriptStatus.info {
background-color: #e8f0fe;
color: #4285f4;
border-left: 4px solid #4285f4;
}
#scriptStatus.success {
background-color: #e6f4ea;
color: #0f9d58;
border-left: 4px solid #0f9d58;
}
#scriptStatus.error {
background-color: #fce8e6;
color: #db4437;
border-left: 4px solid #db4437;
}
#debugInfo {
margin-top: 20px;
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
font-family: monospace;
font-size: 12px;
max-height: 200px;
overflow-y: auto;
display: none;
}
#showDebug {
margin-top: 10px;
background-color: #f5f5f5;
color: #444;
font-size: 12px;
}
</style>
</head>
<body>
<div class="container">
<h2>Opus 编解码录音播放测试</h2>
<div id="scriptStatus" class="info">正在加载Opus库...</div>
<div>
<button id="initAudio" style="background-color: #34a853;">初始化音频</button>
<button id="testMic" style="background-color: #fbbc05;">测试麦克风</button>
<p></p>
<button id="start" disabled>开始录音</button>
<button id="stop" disabled>停止录音</button>
<button id="play" disabled>播放录音</button>
<p>录音状态: <span id="status">待机,正在初始化...</span></p>
<button id="showDebug">显示/隐藏调试信息</button>
<div id="debugInfo"></div>
<div id="audioMeter" style="margin-top: 10px; height: 20px; background-color: #eee; border-radius: 4px; overflow: hidden; display: none;">
<div id="audioLevel" style="height: 100%; width: 0%; background-color: #4285f4; transition: width 0.1s;"></div>
</div>
</div>
</div>
<!-- Opus解码库 - 这个库会设置一个全局Module变量 -->
<script>
// 定义全局变量以跟踪库加载状态
window.opusLoaded = false;
window.startButton = document.getElementById("start");
window.stopButton = document.getElementById("stop");
window.playButton = document.getElementById("play");
window.statusLabel = document.getElementById("status");
window.debugInfo = document.getElementById("debugInfo");
window.audioContextReady = false;
window.testMicActive = false;
// 显示/隐藏调试信息
document.getElementById("showDebug").addEventListener("click", function() {
if (debugInfo.style.display === "none" || !debugInfo.style.display) {
debugInfo.style.display = "block";
this.textContent = "隐藏调试信息";
} else {
debugInfo.style.display = "none";
this.textContent = "显示调试信息";
}
});
// 添加初始化音频按钮事件
document.getElementById("initAudio").addEventListener("click", function() {
initializeAudioSystem();
});
// 添加测试麦克风按钮事件
document.getElementById("testMic").addEventListener("click", function() {
if (window.testMicActive) {
stopMicTest();
} else {
startMicTest();
}
});
// 初始化音频系统
function initializeAudioSystem() {
try {
log("初始化音频系统...");
// 创建临时AudioContext来触发用户授权
const tempContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: 16000,
latencyHint: 'interactive'
});
// 创建振荡器并播放短促的声音
const oscillator = tempContext.createOscillator();
const gain = tempContext.createGain();
gain.gain.value = 0.1; // 很小的音量
oscillator.connect(gain);
gain.connect(tempContext.destination);
oscillator.frequency.value = 440; // A4
oscillator.start();
// 0.2秒后停止
setTimeout(() => {
oscillator.stop();
// 关闭上下文
tempContext.close().then(() => {
log("音频系统初始化成功", "success");
updateScriptStatus("音频系统已激活", "success");
document.getElementById("initAudio").disabled = true;
document.getElementById("initAudio").textContent = "音频已初始化";
window.audioContextReady = true;
// 如果Opus已加载,启用开始录音按钮
if (window.opusLoaded) {
startButton.disabled = false;
}
});
}, 200);
} catch (err) {
log("初始化音频系统失败: " + err.message, "error");
updateScriptStatus("初始化音频失败: " + err.message, "error");
}
}
// 测试麦克风
function startMicTest() {
const audioMeter = document.getElementById("audioMeter");
const audioLevel = document.getElementById("audioLevel");
const testMicBtn = document.getElementById("testMic");
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
log("浏览器不支持麦克风访问", "error");
return;
}
log("开始麦克风测试...");
audioMeter.style.display = "block";
testMicBtn.textContent = "停止测试";
testMicBtn.style.backgroundColor = "#ea4335";
window.testMicActive = true;
// 创建音频上下文
const testContext = new (window.AudioContext || window.webkitAudioContext)();
window.testContext = testContext;
// 获取麦克风权限
navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true
}
})
.then(stream => {
log("已获取麦克风访问权限", "success");
// 保存流以便稍后关闭
window.testStream = stream;
// 创建音频分析器
const source = testContext.createMediaStreamSource(stream);
const analyser = testContext.createAnalyser();
analyser.fftSize = 256;
source.connect(analyser);
// 创建音量显示更新函数
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
function updateMeter() {
if (!window.testMicActive) return;
analyser.getByteFrequencyData(dataArray);
// 计算音量级别 (0-100)
let sum = 0;
for (let i = 0; i < bufferLength; i++) {
sum += dataArray[i];
}
const average = sum / bufferLength;
const level = Math.min(100, Math.max(0, average * 2));
// 更新音量计
audioLevel.style.width = level + "%";
// 如果有声音,记录日志
if (level > 10) {
log(`检测到声音: ${level.toFixed(1)}%`);
}
// 循环更新
window.testMicAnimationFrame = requestAnimationFrame(updateMeter);
}
// 开始更新
updateMeter();
})
.catch(err => {
log("麦克风测试失败: " + err.message, "error");
window.testMicActive = false;
testMicBtn.textContent = "测试麦克风";
testMicBtn.style.backgroundColor = "#fbbc05";
audioMeter.style.display = "none";
});
}
// 停止麦克风测试
function stopMicTest() {
const audioMeter = document.getElementById("audioMeter");
const testMicBtn = document.getElementById("testMic");
log("停止麦克风测试");
window.testMicActive = false;
testMicBtn.textContent = "测试麦克风";
testMicBtn.style.backgroundColor = "#fbbc05";
// 停止分析器动画
if (window.testMicAnimationFrame) {
cancelAnimationFrame(window.testMicAnimationFrame);
}
// 停止麦克风流
if (window.testStream) {
window.testStream.getTracks().forEach(track => track.stop());
}
// 关闭测试上下文
if (window.testContext) {
window.testContext.close();
}
// 隐藏音量计
audioMeter.style.display = "none";
}
// 初始化AudioContext
function initAudioContext() {
try {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
if (!window.AudioContext) {
throw new Error("浏览器不支持AudioContext");
}
// 我们在app.js中会创建AudioContext,这里只检查兼容性
log("AudioContext API 可用");
return true;
} catch (err) {
log("AudioContext初始化失败: " + err.message, "error");
updateScriptStatus("AudioContext初始化失败,录音功能不可用", "error");
return false;
}
}
// 检查麦克风权限
function checkMicrophonePermission() {
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
log("浏览器不支持getUserMedia API", "error");
updateScriptStatus("浏览器不支持录音功能", "error");
return false;
}
log("getUserMedia API 可用");
return true;
}
// 添加调试日志
function log(message, type = "info") {
console.log(message);
const time = new Date().toLocaleTimeString();
const entry = document.createElement("div");
entry.textContent = `[${time}] ${message}`;
if (type === "error") {
entry.style.color = "#db4437";
} else if (type === "success") {
entry.style.color = "#0f9d58";
}
debugInfo.appendChild(entry);
debugInfo.scrollTop = debugInfo.scrollHeight;
}
// 更新脚本状态显示
function updateScriptStatus(message, type) {
const statusElement = document.getElementById('scriptStatus');
if (statusElement) {
statusElement.textContent = message;
statusElement.className = type;
statusElement.style.display = 'block';
}
log(message, type);
}
// 检查Opus库是否已加载
function checkOpusLoaded() {
try {
// 检查Module是否存在(本地库导出的全局变量)
if (typeof Module === 'undefined') {
log("Module对象不存在", "error");
throw new Error('Opus库未加载,Module对象不存在');
}
// 记录Module对象结构以便调试
log("Module对象结构: " + Object.keys(Module).join(", "));
// 尝试使用全局Module函数
if (typeof Module._opus_decoder_get_size === 'function') {
window.ModuleInstance = Module;
log('Opus库加载成功(使用全局Module', "success");
updateScriptStatus('Opus库加载成功', 'success');
// 启用开始录音按钮
startButton.disabled = false;
statusLabel.textContent = "待机";
// 3秒后隐藏状态
setTimeout(() => {
const statusElement = document.getElementById('scriptStatus');
if (statusElement) statusElement.style.display = 'none';
}, 3000);
window.opusLoaded = true;
return true;
}
// 尝试使用Module.instance
if (typeof Module.instance !== 'undefined' && typeof Module.instance._opus_decoder_get_size === 'function') {
window.ModuleInstance = Module.instance;
log('Opus库加载成功(使用Module.instance', "success");
updateScriptStatus('Opus库加载成功', 'success');
// 启用开始录音按钮
startButton.disabled = false;
statusLabel.textContent = "待机";
// 3秒后隐藏状态
setTimeout(() => {
const statusElement = document.getElementById('scriptStatus');
if (statusElement) statusElement.style.display = 'none';
}, 3000);
window.opusLoaded = true;
return true;
}
// 检查是否有其他导出方式
log("Module上可用方法: " + Object.getOwnPropertyNames(Module).filter(prop => typeof Module[prop] === 'function').join(", "));
if (typeof Module.onRuntimeInitialized === 'function' || typeof Module.onRuntimeInitialized === 'undefined') {
log("Module.onRuntimeInitialized 尚未执行,等待模块初始化完成...");
// Module可能未完成初始化,注册回调
Module.onRuntimeInitialized = function() {
log("Opus库运行时初始化完成,重新检查");
checkOpusLoaded();
};
return false;
}
throw new Error('Opus解码函数未找到,可能Module结构不正确');
} catch (err) {
log(`Opus库加载失败: ${err.message}`, "error");
updateScriptStatus(`Opus库加载失败: ${err.message}`, 'error');
statusLabel.textContent = "错误:Opus库加载失败";
return false;
}
}
// 页面加载完成后检查浏览器能力和Opus库
window.addEventListener('load', function() {
log("页面加载完成,开始初始化...");
updateScriptStatus('正在初始化录音环境...', 'info');
// 检查浏览器能力
const audioContextSupported = initAudioContext();
const microphoneSupported = checkMicrophonePermission();
if (!audioContextSupported || !microphoneSupported) {
log("浏览器不支持必要API,无法进行录音", "error");
updateScriptStatus('浏览器不支持录音功能', 'error');
return;
}
log("检查环境完成,开始加载Opus库");
updateScriptStatus('正在加载Opus库...', 'info');
// 延迟一小段时间再检查,确保库有时间加载
setTimeout(function checkAndRetry() {
if (!checkOpusLoaded()) {
// 如果加载失败,5秒后重试
log("Opus库加载失败,5秒后重试...");
updateScriptStatus('Opus库加载失败,正在重试...', 'error');
setTimeout(checkAndRetry, 5000);
}
}, 1000);
});
// 防止按钮误操作
document.getElementById("stop").disabled = true;
document.getElementById("play").disabled = true;
</script>
<script src="./../libopus.js"></script>
<script src="app.js"></script>
</body>
</html>
-425
View File
@@ -1,425 +0,0 @@
body {
font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
}
.container {
max-width: 1000px;
margin: 0 auto;
background-color: white;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
padding: 10px 20px 10px 20px;
}
h1 {
color: #333;
text-align: center;
margin-bottom: 30px;
}
.section {
margin-bottom: 5px;
padding: 10px;
border-radius: 10px;
background-color: #f9f9f9;
}
.section h2 {
margin-top: 0;
color: #444;
font-size: 18px;
display: flex;
align-items: center;
gap: 10px;
padding: 10px 0;
}
.section h2 .toggle-button {
margin-left: auto;
padding: 4px 12px;
font-size: 12px;
border-radius: 4px;
cursor: pointer;
height: 28px;
line-height: 20px;
}
.device-info {
display: flex;
align-items: center;
gap: 20px;
margin-left: 20px;
padding: 0 15px;
background-color: #f9f9f9;
border-radius: 4px;
height: 28px;
line-height: 28px;
}
.device-info span {
color: #666;
font-size: 13px;
}
.device-info strong {
color: #333;
font-weight: 500;
}
.config-panel {
display: none;
transition: all 0.3s ease;
margin-top: 5px;
padding: 5px 0;
}
.config-panel.expanded {
display: block;
}
.control-panel {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 10px;
}
button {
padding: 8px 15px;
border: none;
border-radius: 5px;
background-color: #4285f4;
color: white;
cursor: pointer;
transition: background-color 0.2s;
}
button:hover {
background-color: #3367d6;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
#serverUrl,
#otaUrl {
flex-grow: 1;
padding: 8px;
border: 1px solid #ddd;
border-radius: 5px;
}
.message-input {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
#messageInput {
flex-grow: 1;
padding: 8px;
border: 1px solid #ddd;
border-radius: 5px;
}
#nfcCardId {
flex-grow: 1;
padding: 8px;
border: 1px solid #ddd;
border-radius: 5px;
}
.conversation {
max-height: 300px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 5px;
padding: 10px;
background-color: white;
flex: 1;
margin-right: 10px;
}
.message {
margin-bottom: 10px;
padding: 8px 12px;
border-radius: 8px;
max-width: 80%;
}
.user {
background-color: #e2f2ff;
margin-left: auto;
margin-right: 10px;
text-align: right;
}
.server {
background-color: #f0f0f0;
margin-right: auto;
margin-left: 10px;
}
.status {
color: #666;
font-style: italic;
font-size: 14px;
margin: 0;
padding: 0;
}
.audio-controls {
display: flex;
justify-content: center;
gap: 10px;
margin-top: 20px;
}
.audio-visualizer {
height: 60px;
width: 100%;
margin-top: 10px;
border: 1px solid #ddd;
border-radius: 5px;
background-color: #fafafa;
}
.record-button {
background-color: #db4437;
}
.record-button:hover {
background-color: #c53929;
}
.record-button.recording {
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0% {
background-color: #db4437;
}
50% {
background-color: #ff6659;
}
100% {
background-color: #db4437;
}
}
#logContainer {
margin-top: 0;
padding: 10px;
background-color: #f0f0f0;
border-radius: 5px;
font-family: monospace;
height: 300px;
overflow-y: auto;
flex: 1;
margin-left: 10px;
}
.log-entry {
margin: 5px 0;
font-size: 12px;
}
.log-info {
color: #333;
}
.log-error {
color: #db4437;
}
.log-success {
color: #0f9d58;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translate(-50%, -60%);
}
to {
opacity: 1;
transform: translate(-50%, -50%);
}
}
.script-status {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 5px;
}
.script-loaded {
background-color: #0f9d58;
}
.script-loading {
background-color: #f4b400;
}
.script-error {
background-color: #db4437;
}
.script-list {
margin: 10px 0;
padding: 10px;
background-color: #f9f9f9;
border-radius: 5px;
font-family: monospace;
font-size: 11px;
}
#scriptStatus.success {
background-color: #e6f4ea;
color: #0f9d58;
border-left: 4px solid #0f9d58;
}
#scriptStatus.error {
background-color: #fce8e6;
color: #db4437;
border-left: 4px solid #db4437;
}
#scriptStatus.warning {
background-color: #fef7e0;
color: #f4b400;
border-left: 4px solid #f4b400;
}
/* 标签页样式 */
.tabs {
display: flex;
margin-bottom: 20px;
border-bottom: 2px solid #e0e0e0;
}
.tab {
padding: 10px 20px;
cursor: pointer;
border: none;
background: none;
font-size: 16px;
color: #666;
position: relative;
transition: all 0.3s ease;
}
.tab:hover {
color: #4285f4;
}
.tab.active {
color: #4285f4;
font-weight: bold;
}
.tab.active::after {
content: '';
position: absolute;
bottom: -2px;
left: 0;
width: 100%;
height: 2px;
background-color: #4285f4;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.flex-container {
display: flex;
gap: 20px;
margin-top: 10px;
}
.config-item {
display: flex;
align-items: center;
margin-bottom: 8px;
width: 100%;
}
.config-item label {
width: 100px;
text-align: right;
margin-right: 10px;
color: #666;
}
.config-item input {
flex-grow: 1;
padding: 6px;
border: 1px solid #ddd;
border-radius: 5px;
}
.control-panel {
display: flex;
flex-direction: column;
gap: 10px;
margin-top: 10px;
}
.connection-controls {
display: flex;
gap: 10px;
align-items: center;
width: 100%;
}
.connection-controls input {
flex: 1;
padding: 8px;
border: 1px solid #ddd;
border-radius: 5px;
min-width: 200px;
}
.connection-controls button {
white-space: nowrap;
padding: 8px 15px;
}
.connection-status {
display: flex;
align-items: center;
gap: 20px;
margin-left: 20px;
padding: 0 15px;
background-color: #f9f9f9;
border-radius: 4px;
height: 28px;
line-height: 28px;
}
.connection-status span {
color: #666;
font-size: 13px;
}
.connection-status .status {
color: #333;
font-weight: 500;
}
File diff suppressed because it is too large Load Diff