diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..af9906389 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: pip + directory: /main/xiaozhi-server + schedule: + interval: weekly \ No newline at end of file diff --git a/.github/workflows/build-base-image.yml b/.github/workflows/build-base-image.yml new file mode 100644 index 000000000..7b6fec6b6 --- /dev/null +++ b/.github/workflows/build-base-image.yml @@ -0,0 +1,49 @@ +name: Build Base Image + +on: + push: + branches: + - main + paths: + - 'main/xiaozhi-server/requirements.txt' + - 'Dockerfile-server-base' + - '.github/workflows/build-base-image.yml' + +jobs: + build-base: + name: Build and push server base image + runs-on: ubuntu-latest + permissions: + packages: write + contents: read + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.TOKEN }} + + - name: Build and push server-base + uses: docker/build-push-action@v6 + with: + context: . + file: Dockerfile-server-base + push: true + tags: ghcr.io/${{ github.repository }}:server-base + platforms: linux/amd64 + cache-from: type=gha,scope=server-base + cache-to: type=gha,mode=max,scope=server-base + build-args: | + BUILDKIT_PROGRESS=plain + + - name: Output image info + run: | + echo "✅ Base image built and pushed successfully!" + echo "📦 Tag: ghcr.io/${{ github.repository }}:server-base" diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 22562abef..f795fd5a5 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -5,6 +5,10 @@ on: tags: - 'v*.*.*' # 只在以 v 开头的标签推送时触发,例如 v1.0.0 workflow_dispatch: + workflow_run: + workflows: ["Build Base Image"] + types: + - completed jobs: release: diff --git a/Dockerfile-server b/Dockerfile-server index a12fbb11d..9df93c9e3 100644 --- a/Dockerfile-server +++ b/Dockerfile-server @@ -1,36 +1,6 @@ -# 第一阶段:构建Python依赖 -FROM python:3.10-slim AS builder +# 生产镜像,仅包含应用代码 +FROM ghcr.io/xinnan-tech/xiaozhi-esp32-server:server-base -WORKDIR /app - -# 配置pip使用国内镜像源(阿里云)并设置超时和重试 -RUN pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ && \ - pip config set global.trusted-host mirrors.aliyun.com && \ - pip config set global.timeout 120 && \ - pip config set install.retries 5 - -COPY main/xiaozhi-server/requirements.txt . - -# 安装Python依赖,使用并行下载 -RUN pip install --no-cache-dir --upgrade pip setuptools wheel && \ - pip install --no-cache-dir -r requirements.txt --default-timeout=120 --retries 5 - -# 第二阶段:生产镜像 -FROM python:3.10-slim - -WORKDIR /opt/xiaozhi-esp32-server - -# 安装系统依赖 -RUN apt-get update && \ - apt-get install -y --no-install-recommends libopus0 ffmpeg && \ - apt-get clean && \ - rm -rf /var/lib/apt/lists/* - -# 从构建阶段复制Python包和前端构建产物 -COPY --from=builder /usr/local/lib/python3.10/site-packages /usr/local/lib/python3.10/site-packages -COPY --from=builder /usr/local/bin/mcp-proxy /usr/local/bin/mcp-proxy - -# 复制应用代码 COPY main/xiaozhi-server . # 启动应用 diff --git a/Dockerfile-server-base b/Dockerfile-server-base new file mode 100644 index 000000000..70429ab16 --- /dev/null +++ b/Dockerfile-server-base @@ -0,0 +1,32 @@ +# Dockerfile-server-base +# 基础镜像,包含系统依赖和Python包 +FROM python:3.10-slim + +# 安装系统依赖 +RUN apt-get update && \ + apt-get install -y --no-install-recommends libopus0 ffmpeg locales && \ + sed -i '/zh_CN.UTF-8/s/^# //g' /etc/locale.gen && \ + locale-gen && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/* + +# 配置pip使用国内镜像源(阿里云)并设置超时和重试 +RUN pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ && \ + pip config set global.trusted-host mirrors.aliyun.com && \ + pip config set global.timeout 120 && \ + pip config set install.retries 5 + +# 设置环境变量以确保正确的字符编码 +ENV LANG=zh_CN.UTF-8 \ + LC_ALL=zh_CN.UTF-8 \ + LANGUAGE=zh_CN:zh \ + PYTHONIOENCODING=utf-8 + +WORKDIR /opt/xiaozhi-esp32-server + +# 复制requirements.txt +COPY main/xiaozhi-server/requirements.txt . + +# 安装Python依赖 +RUN pip install --no-cache-dir --upgrade pip setuptools wheel && \ + pip install --no-cache-dir -r requirements.txt --default-timeout=120 --retries 5 \ No newline at end of file diff --git a/README.md b/README.md index c0d474dfd..943501a71 100644 --- a/README.md +++ b/README.md @@ -6,29 +6,24 @@ 本项目基于人机共生智能理论和技术研发智能终端软硬件体系
为开源智能硬件项目 xiaozhi-esp32提供后端服务
根据小智通信协议使用Python、Java、Vue实现
-支持MQTT+UDP协议、Websocket协议、MCP接入点、声纹识别 +支持MQTT+UDP协议、Websocket协议、MCP接入点、声纹识别、知识库

-English -· 常见问题 +常见问题 · 反馈问题 · 部署文档 · 更新日志

+

+ 简体中文版自述文件 + README in English + Tiếng Việt + Deutsch GitHub Contributors - - GitHub Contributors - - - Issues - - - GitHub pull requests - GitHub pull requests @@ -56,10 +51,24 @@ Spearheaded by Professor Siyuan Liu's Team (South China University of Technology + + @@ -71,19 +80,14 @@ Spearheaded by Professor Siyuan Liu's Team (South China University of Technology - + + - - + @@ -114,20 +123,6 @@ Spearheaded by Professor Siyuan Liu's Team (South China University of Technology - - @@ -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 | 项目/公司 | 说明 | diff --git a/README_de.md b/README_de.md new file mode 100644 index 000000000..c3578fec7 --- /dev/null +++ b/README_de.md @@ -0,0 +1,374 @@ +[![Banners](docs/images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server) + +

Xiaozhi Backend-Service xiaozhi-esp32-server

+ +

+Dieses Projekt basiert auf der Theorie und Technologie der Mensch-Maschine-symbiotischen Intelligenz zur Entwicklung intelligenter Terminal-Hardware- und Software-Systeme
und bietet Backend-Dienste für das Open-Source-Hardware-Projekt +xiaozhi-esp32
+Implementiert mit Python, Java und Vue gemäß dem Xiaozhi-Kommunikationsprotokoll
+Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Endpunkte und Stimmabdruckerkennung +

+ +

+Häufige Fragen +· Probleme melden +· Deployment-Dokumentation +· Release-Hinweise +

+ +

+ 简体中文版自述文件 + README in English + Tiếng Việt + Deutsch + + GitHub Contributors + + + GitHub pull requests + + + stars + +

+ +

+Geleitet vom Team von Professor Siyuan Liu (South China University of Technology) +
+刘思源教授团队主导研发(华南理工大学) +
+South China University of Technology +

+ +--- + +## 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 🎥 + +
+ + + 响应速度感受 + + + + + + 速度优化秘诀 + + + - 小智医疗救护车场景 + 复杂医疗场景 - + - 自定义音色 - - - - - - 使用粤语交流 + 声纹识别
@@ -91,12 +95,17 @@ Spearheaded by Professor Siyuan Liu's Team (South China University of Technology
- + - 自定义音色 + MCP接入点 + + + + + + 多指令任务 - - - IOT指令控制设备 - - - - - - 播报新闻 - - -
@@ -145,23 +140,23 @@ Spearheaded by Professor Siyuan Liu's Team (South China University of Technology - + - 多指令任务 + 自定义音色 - + - MCP接入点 + 使用粤语交流 - + - 声纹识别 + 播报新闻
+ + + + + + + + + + + + + + + + + + + + + +
+ + + 响应速度感受 + + + + + + 速度优化秘诀 + + + + + + 复杂医疗场景 + + + + + + MQTT指令下发 + + + + + + 声纹识别 + + +
+ + + 控制家电开关 + + + + + + MCP接入点 + + + + + + 多指令任务 + + + + + + 播放音乐 + + + + + + 天气插件 + + +
+ + + 实时打断 + + + + + + 拍照识物品 + + + + + + 自定义音色 + + + + + + 使用粤语交流 + + + + + + 播报新闻 + + +
+ +--- + +## 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 | +|:---:|:---:|:---| +| | [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 | +| | [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 | +| | [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 | +| | [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 | +| | [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 | +| | [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 | +| | [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. | + + + + + + + + Star History Chart + + diff --git a/README_en.md b/README_en.md index a50006f8b..e84378327 100644 --- a/README_en.md +++ b/README_en.md @@ -6,29 +6,24 @@ This project is based on human-machine symbiotic intelligence theory and technology to develop intelligent terminal hardware and software systems
providing backend services for the open-source intelligent hardware project xiaozhi-esp32
Implemented using Python, Java, and Vue according to the Xiaozhi Communication Protocol
-Supports MCP endpoints and voiceprint recognition +Support for MQTT+UDP protocol, Websocket protocol, MCP access point, voiceprint recognition, and knowledge base

-中文 -· FAQ +FAQ · Report Issues · Deployment Docs · Release Notes

+

+ 简体中文版自述文件 + README in English + Tiếng Việt + Deutsch GitHub Contributors - - GitHub Contributors - - - Issues - - - GitHub pull requests - GitHub pull requests @@ -58,72 +53,72 @@ Want to see the usage effects? Click the videos below 🎥 - Xiaozhi ESP32 connecting to own backend model + 响应速度感受 + + + + + + + 速度优化秘诀 + + + + + + + 复杂医疗场景 - MQTT command issuance + MQTT指令下发 - + - Custom voice timbre - - - - - - - Using Cantonese for communication - - - - - - - Controlling home appliances + 声纹识别 - + - Custom voice timbre + 控制家电开关 + + + + + + + MCP接入点 + + + + + + + 多指令任务 - Playing music + 播放音乐 - Weather plugin - - - - - - - IOT command control devices - - - - - - - News broadcasting + 天气插件 @@ -132,35 +127,35 @@ Want to see the usage effects? Click the videos below 🎥 - Real-time interruption + 实时打断 - Photo recognition of objects + 拍照识物品 - + - Multi-command tasks + 自定义音色 - + - MCP endpoint + 使用粤语交流 - + - Voiceprint recognition + 播报新闻 @@ -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 | diff --git a/README_vi.md b/README_vi.md new file mode 100644 index 000000000..926975518 --- /dev/null +++ b/README_vi.md @@ -0,0 +1,375 @@ +[![Banners](docs/images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server) + +

Dịch vụ Backend Xiaozhi xiaozhi-esp32-server

+ +

+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
Cung cấp dịch vụ backend cho dự án phần cứng thông minh mã nguồn mở +xiaozhi-esp32
+Được triển khai bằng Python, Java, Vue theo giao thức truyền thông Xiaozhi
+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 +

+ +

+Câu hỏi thường gặp +· Báo cáo vấn đề +· Tài liệu triển khai +· Nhật ký cập nhật +

+ +

+ 简体中文版自述文件 + README in English + Tiếng Việt + Deutsch + + GitHub Contributors + + + GitHub pull requests + + + stars + +

+ +

+Spearheaded by Professor Siyuan Liu's Team (South China University of Technology) +
+Đượ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) +
+华南理工大学 +

+ +--- + +## 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 🎥 + + + + + + + + + + + + + + + + + + + + + + + +
+ + + 响应速度感受 + + + + + + 速度优化秘诀 + + + + + + 复杂医疗场景 + + + + + + MQTT指令下发 + + + + + + 声纹识别 + + +
+ + + 控制家电开关 + + + + + + MCP接入点 + + + + + + 多指令任务 + + + + + + 播放音乐 + + + + + + 天气插件 + + +
+ + + 实时打断 + + + + + + 拍照识物品 + + + + + + 自定义音色 + + + + + + 使用粤语交流 + + + + + + 播报新闻 + + +
+ +--- + +## 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ả | +|:---:|:---:|:---| +| | [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ở đó | +| | [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 | +| | [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) | +| | [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 | +| | [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 | +| | [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 | +| | [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. | + + + + + + + + Star History Chart + + diff --git a/docs/Deployment.md b/docs/Deployment.md index 7d9bcd042..25518a0fb 100644 --- a/docs/Deployment.md +++ b/docs/Deployment.md @@ -80,7 +80,7 @@ After configuring the project files, return to this tutorial to continue. Open the command line tool, use the `terminal` or `command line` tool to enter your `xiaozhi-server`, and execute the following command ``` -docker-compose up -d +docker compose up -d ``` After the execution is complete, execute the following command to view the log information. @@ -139,6 +139,9 @@ conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/ conda install libopus -y conda install ffmpeg -y + +# 在 Linux 环境下进行部署时,如出现类似缺失 libiconv.so.2 动态库的报错 请通过以下命令进行安装 +conda install libiconv -y ``` Please note that the above commands are not executed successfully all at once. You need to execute them step by step. After each step, check the output log to see if it is successful. @@ -242,44 +245,47 @@ If you can see logs similar to the following, it means that the project service 250427 13:04:20[0.3.11_SiFuChTTnofu][__main__]-INFO-========================================================== ``` -Normally, if you run this project through source code, the log will have your interface address information. -However, if you deploy with Docker, the interface address information given in your log is not the real interface address. +正常来说,如果您是通过源码运行本项目,日志会有你的接口地址信息。 +但是如果你用docker部署,那么你的日志里给出的接口地址信息就不是真实的接口地址。 -The most correct way is to determine your interface address based on the computer's LAN IP. -If your computer's LAN IP is, for example, `192.168.1.25`, then your interface address is: `ws://192.168.1.25:8000/xiaozhi/v1/`, and the corresponding OTA address is: `http://192.168.1.25:8003/xiaozhi/ota/`. +最正确的方法,是根据电脑的局域网IP来确定你的接口地址。 +如果你的电脑的局域网IP比如是`192.168.1.25`,那么你的接口地址就是:`ws://192.168.1.25:8000/xiaozhi/v1/`,对应的OTA地址就是:`http://192.168.1.25:8003/xiaozhi/ota/`。 -This information is very useful and will be needed later when `compiling the ESP32 firmware`. +这个信息很有用的,后面`编译esp32固件`需要用到。 -Next, you can start operating your ESP32 device. You can either compile the ESP32 firmware yourself or use the firmware compiled by Xiage (version 1.6.1 or above). +接下来,你就可以开始操作你的esp32设备了,你可以`自行编译esp32固件`也可以配置使用`虾哥编译好的1.6.1以上版本的固件`。两个任选一个 -1. [Compile your own ESP32 firmware](firmware-build.md). +1、 [编译自己的esp32固件](firmware-build.md)了。 -2. [Configure a custom server based on the firmware compiled by Xia Ge](firmware-setting.md). +2、 [基于虾哥编译好的固件配置自定义服务器](firmware-setting.md)了。 -# FAQ -Here are some frequently asked questions for your reference: +# 常见问题 +以下是一些常见问题,供参考: -1. [Why does Xiaozhi recognize a lot of Korean, Japanese, and English when I say something?](./FAQ.md) -2. [Why does the error "TTS task error file does not exist" appear?](./FAQ.md)
-3. [TTS often fails and times out](./FAQ.md)
-4. [I can connect to my own server using Wi-Fi, but not using 4G](./FAQ.md)
-5. [How to improve Xiaozhi's dialogue response speed? ](./FAQ.md)
-6. [I speak very slowly, and Xiaozhi always interrupts me when I pause](./FAQ.md) -## Deployment related tutorials -1. [How to automatically pull the latest code of this project, compile and start it](./dev-ops-integration.md)
-2. [How to integrate with Nginx](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791) -## Expand related tutorials -1. [How to enable mobile phone number registration smart console](./ali-sms-integration.md)
-2. [How to integrate HomeAssistant to achieve smart home control](./homeassistant-integration.md) -3. [How to enable the vision model to realize photo recognition](./mcp-vision-integration.md) -4. [How to deploy MCP access points](./mcp-endpoint-enable.md) -5. [How to access the MCP access point](./mcp-endpoint-integration.md) -6. [How to enable voiceprint recognition](./voiceprint-integration.md) -10. [News plugin source configuration guide](./newsnow_plugin_config.md)
-## Tutorials on voice cloning and local voice deployment -1. [How to deploy and integrate index-tts local voice](./index-stream-integration.md)
-2. [How to deploy integrated fish-speech local voice](./fish-speech-integration.md)
-3. [How to deploy and integrate PaddleSpeech local voice](./paddlespeech-deploy.md)
-## Performance Testing Tutorial -1. [Component Speed ​​Test Guide](./performance_tester.md)
-2. [Publish test results regularly](https://github.com/xinnan-tech/xiaozhi-performance-research) +1、[为什么我说的话,小智识别出来很多韩文、日文、英文](./FAQ.md)
+2、[为什么会出现“TTS 任务出错 文件不存在”?](./FAQ.md)
+3、[TTS 经常失败,经常超时](./FAQ.md)
+4、[使用Wifi能连接自建服务器,但是4G模式却接不上](./FAQ.md)
+5、[如何提高小智对话响应速度?](./FAQ.md)
+6、[我说话很慢,停顿时小智老是抢话](./FAQ.md)
+## 部署相关教程 +1、[如何自动拉取本项目最新代码自动编译和启动](./dev-ops-integration.md)
+2、[如何部署MQTT网关开启MQTT+UDP协议](./mqtt-gateway-integration.md)
+3、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)
+## 拓展相关教程 +1、[如何开启手机号码注册智控台](./ali-sms-integration.md)
+2、[如何集成HomeAssistant实现智能家居控制](./homeassistant-integration.md)
+3、[如何开启视觉模型实现拍照识物](./mcp-vision-integration.md)
+4、[如何部署MCP接入点](./mcp-endpoint-enable.md)
+5、[如何接入MCP接入点](./mcp-endpoint-integration.md)
+6、[如何开启声纹识别](./voiceprint-integration.md)
+7、[新闻插件源配置指南](./newsnow_plugin_config.md)
+8、[天气插件使用指南](./weather-integration.md)
+## 语音克隆、本地语音部署相关教程 +1、[如何在智控台克隆音色](./huoshan-streamTTS-voice-cloning.md)
+2、[如何部署集成index-tts本地语音](./index-stream-integration.md)
+3、[如何部署集成fish-speech本地语音](./fish-speech-integration.md)
+4、[如何部署集成PaddleSpeech本地语音](./paddlespeech-deploy.md)
+## 性能测试教程 +1、[各组件速度测试指南](./performance_tester.md)
+2、[定期公开测试结果](https://github.com/xinnan-tech/xiaozhi-performance-research)
diff --git a/docs/Deployment_all.md b/docs/Deployment_all.md index bc627fac5..fa67d8482 100644 --- a/docs/Deployment_all.md +++ b/docs/Deployment_all.md @@ -355,6 +355,9 @@ conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/ conda install libopus -y conda install ffmpeg -y + +# 在 Linux 环境下进行部署时,如出现类似缺失 libiconv.so.2 动态库的报错 请通过以下命令进行安装 +conda install libiconv -y ``` Please note that the above commands are not executed successfully all at once. You need to execute them step by step. After each step, check the output log to see if it is successful. @@ -460,28 +463,30 @@ Next, you can start operating your ESP32 device. You can either compile the ESP3 # FAQ Here are some frequently asked questions for your reference: -1. [Why does Xiaozhi recognize a lot of Korean, Japanese, and English when I say something?](./FAQ.md) -2. [Why does the error "TTS task error file does not exist" appear?](./FAQ.md)
-3. [TTS often fails and times out](./FAQ.md)
-4. [I can connect to my own server using Wi-Fi, but not using 4G](./FAQ.md)
-5. [How to improve Xiaozhi's dialogue response speed? ](./FAQ.md)
-6. [I speak very slowly, and Xiaozhi always interrupts me when I pause](./FAQ.md) -## Deployment related tutorials -1. [How to automatically pull the latest code of this project, compile and start it](./dev-ops-integration.md)
-2. [How to integrate with Nginx](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791) -## Expand related tutorials -1. [How to enable mobile phone number registration smart console](./ali-sms-integration.md)
-2. [How to integrate HomeAssistant to achieve smart home control](./homeassistant-integration.md) -3. [How to enable the vision model to realize photo recognition](./mcp-vision-integration.md) -4. [How to deploy MCP access points](./mcp-endpoint-enable.md) -5. [How to access the MCP access point](./mcp-endpoint-integration.md) -6. [How to enable voiceprint recognition](./voiceprint-integration.md) -7. [News plugin source configuration guide](./newsnow_plugin_config.md)
-8. [Weather Plugin Usage Guide](./weather-integration.md) -## Tutorials on voice cloning and local voice deployment -1. [How to deploy and integrate index-tts local voice](./index-stream-integration.md)
-2. [How to deploy integrated fish-speech local voice](./fish-speech-integration.md)
-3. [How to deploy and integrate PaddleSpeech local voice](./paddlespeech-deploy.md)
-## Performance Testing Tutorial -1. [Component Speed ​​Test Guide](./performance_tester.md)
-2. [Publish test results regularly](https://github.com/xinnan-tech/xiaozhi-performance-research) +1、[为什么我说的话,小智识别出来很多韩文、日文、英文](./FAQ.md)
+2、[为什么会出现“TTS 任务出错 文件不存在”?](./FAQ.md)
+3、[TTS 经常失败,经常超时](./FAQ.md)
+4、[使用Wifi能连接自建服务器,但是4G模式却接不上](./FAQ.md)
+5、[如何提高小智对话响应速度?](./FAQ.md)
+6、[我说话很慢,停顿时小智老是抢话](./FAQ.md)
+## 部署相关教程 +1、[如何自动拉取本项目最新代码自动编译和启动](./dev-ops-integration.md)
+2、[如何部署MQTT网关开启MQTT+UDP协议](./mqtt-gateway-integration.md)
+3、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)
+## 拓展相关教程 +1、[如何开启手机号码注册智控台](./ali-sms-integration.md)
+2、[如何集成HomeAssistant实现智能家居控制](./homeassistant-integration.md)
+3、[如何开启视觉模型实现拍照识物](./mcp-vision-integration.md)
+4、[如何部署MCP接入点](./mcp-endpoint-enable.md)
+5、[如何接入MCP接入点](./mcp-endpoint-integration.md)
+6、[如何开启声纹识别](./voiceprint-integration.md)
+7、[新闻插件源配置指南](./newsnow_plugin_config.md)
+8、[天气插件使用指南](./weather-integration.md)
+## 语音克隆、本地语音部署相关教程 +1、[如何在智控台克隆音色](./huoshan-streamTTS-voice-cloning.md)
+2、[如何部署集成index-tts本地语音](./index-stream-integration.md)
+3、[如何部署集成fish-speech本地语音](./fish-speech-integration.md)
+4、[如何部署集成PaddleSpeech本地语音](./paddlespeech-deploy.md)
+## 性能测试教程 +1、[各组件速度测试指南](./performance_tester.md)
+2、[定期公开测试结果](https://github.com/xinnan-tech/xiaozhi-performance-research)
diff --git a/docs/FAQ.md b/docs/FAQ.md index 4a8d481d1..5baa09436 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -59,35 +59,38 @@ VAD: min_silence_duration_ms: 700 # If the pauses in speaking are long, you can increase this value ``` -### 7. Deployment related tutorials -1. [How to perform the simplest deployment](./Deployment.md) -2. [How to deploy all modules](./Deployment_all.md)
-2. [How to deploy an MQTT gateway and enable the MQTT+UDP protocol](./mqtt-gateway-integration.md) -3. [How to automatically pull the latest code of this project, compile and start it](./dev-ops-integration.md)
-4. [How to integrate with Nginx](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791) +### 7、部署相关教程 +1、[如何进行最简化部署](./Deployment.md)
+2、[如何进行全模块部署](./Deployment_all.md)
+3、[如何部署MQTT网关开启MQTT+UDP协议](./mqtt-gateway-integration.md)
+4、[如何自动拉取本项目最新代码自动编译和启动](./dev-ops-integration.md)
+5、[如何与Nginx集成](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues/791)
-### 8. Compile firmware related tutorials -1. [How to compile Xiaozhi firmware yourself](./firmware-build.md)
-2. [How to modify the OTA address based on the firmware compiled by Xia Ge](./firmware-setting.md)
+### 9、编译固件相关教程 +1、[如何自己编译小智固件](./firmware-build.md)
+2、[如何基于虾哥编译好的固件修改OTA地址](./firmware-setting.md)
-### 8. Expand related tutorials -1. [How to enable mobile phone number registration smart console](./ali-sms-integration.md)
-2. [How to integrate HomeAssistant to achieve smart home control](./homeassistant-integration.md) -3. [How to enable the vision model to realize photo recognition](./mcp-vision-integration.md) -4. [How to deploy MCP access points](./mcp-endpoint-enable.md) -5. [How to access the MCP access point](./mcp-endpoint-integration.md) -6. [How to enable voiceprint recognition](./voiceprint-integration.md) -10. [News plugin source configuration guide](./newsnow_plugin_config.md)
+### 10、拓展相关教程 +1、[如何开启手机号码注册智控台](./ali-sms-integration.md)
+2、[如何集成HomeAssistant实现智能家居控制](./homeassistant-integration.md)
+3、[如何开启视觉模型实现拍照识物](./mcp-vision-integration.md)
+4、[如何部署MCP接入点](./mcp-endpoint-enable.md)
+5、[如何接入MCP接入点](./mcp-endpoint-integration.md)
+6、[MCP方法如何获取设备信息](./mcp-get-device-info.md)
+7、[如何开启声纹识别](./voiceprint-integration.md)
+8、[新闻插件源配置指南](./newsnow_plugin_config.md)
+9、[知识库ragflow集成指南](./ragflow-integration.md)
-### 9. Tutorials on voice cloning and local voice deployment -1. [How to deploy and integrate index-tts local voice](./index-stream-integration.md)
-2. [How to deploy integrated fish-speech local voice](./fish-speech-integration.md)
-3. [How to deploy and integrate PaddleSpeech local voice](./paddlespeech-deploy.md)
+### 11、语音克隆、本地语音部署相关教程 +1、[如何在智控台克隆音色](./huoshan-streamTTS-voice-cloning.md)
+2、[如何部署集成index-tts本地语音](./index-stream-integration.md)
+3、[如何部署集成fish-speech本地语音](./fish-speech-integration.md)
+4、[如何部署集成PaddleSpeech本地语音](./paddlespeech-deploy.md)
-### 10. Performance Testing Tutorial -1. [Component Speed ​​Test Guide](./performance_tester.md)
-2. [Publish test results regularly](https://github.com/xinnan-tech/xiaozhi-performance-research) +### 12、性能测试教程 +1、[各组件速度测试指南](./performance_tester.md)
+2、[定期公开测试结果](https://github.com/xinnan-tech/xiaozhi-performance-research)
-### 13. For more questions, please contact us for feedback💬 +### 13、更多问题,可联系我们反馈 💬 -Please submit your issues at [issues](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues). +可以在[issues](https://github.com/xinnan-tech/xiaozhi-esp32-server/issues)提交您的问题。 diff --git a/docs/docker-build.md b/docs/docker-build.md index 043746cee..a98ca0a73 100644 --- a/docs/docker-build.md +++ b/docs/docker-build.md @@ -17,5 +17,5 @@ docker build -t xiaozhi-esp32-server:web_latest -f ./Dockerfile-web . # After compilation is complete, you can use docker-compose to start the project # You need to modify docker-compose.yml to the image version you compiled yourself cd main/xiaozhi-server -docker-compose up -d +docker compose up -d ``` diff --git a/docs/homeassistant-integration.md b/docs/homeassistant-integration.md index fe0e5baca..7874e3eeb 100644 --- a/docs/homeassistant-integration.md +++ b/docs/homeassistant-integration.md @@ -97,7 +97,7 @@ This string, which we call "device list string", needs to be saved as it will be Log in to the Smart Console using an administrator account. In Agent Management, find your agent and click Configure Role. -Set intent recognition to `Function Call` or `LLM Intent Recognition`. You will see an `Edit Function` button on the right. Click the `Edit Function` button and the `Function Management` dialog box will pop up. +将意图识别设置成`外挂的大模型意图识别`或`大模型自主函数调用`。这时你会看到右侧有一个`编辑功能`。点击`编辑功能`按钮,会弹出`功能管理`的框。 In the `Feature Management` box, you need to check `HomeAssistant device status query` and `HomeAssistant device status modification`. diff --git a/docs/huoshan-streamTTS-voice-cloning.md b/docs/huoshan-streamTTS-voice-cloning.md index beb4d1f19..c2d261d96 100644 --- a/docs/huoshan-streamTTS-voice-cloning.md +++ b/docs/huoshan-streamTTS-voice-cloning.md @@ -1,29 +1,56 @@ -# Volcano Bidirectional Streaming TTS + Voice Cloning Configuration Tutorial -In a single-module deployment, voice cloning is performed while using the Volcano Engine bidirectional streaming speech synthesis service, supporting WebSocket protocol streaming calls. -### 1. Open the Volcano Engine service -Visit https://console.volcengine.com/speech/app and create an app in the App Manager. Select the speech synthesis model and the sound replication model. Click the sound replication model in the list on the left and scroll down to obtain the App ID, Access Token, Cluster ID, and Sound ID (S_xxxxx). -### 2. Clone the sound -To clone the voice, please refer to the tutorial https://github.com/104gogo/huoshan-voice-copy +# 智控台 火山双流式语音合成+音色克隆配置教程 -Prepare a 10-30 second audio file (.wav format) and add it to the cloned project. Fill the key obtained from the platform into ```uploadAndStatus.py``` and ```tts_http_demo.py``` +本教程分为4个阶段:准备阶段、配置阶段、克隆阶段、使用阶段。主要是介绍通过智控台配置火山双流式语音合成+音色克隆的过程。 -In uploadAndStatus.py, change audio_path= to your own .wav file name -```Python -train(appid=appid, token=token, audio_path=r".\audios\xiaohe.wav", spk_id=spk_id) -``` +## 第一阶段:准备阶段 +超级管理员先预先把火山引擎服务开通好,获取到App Id,Access Token。默认火上引擎会赠送一个音色资源。这个音色资源需要把它复制到本项目里。 -Run the following command to generate test_submit.mp3 and click Play to listen to the cloned effect. +如果你想克隆多个音色,需要购买开通多个音色资源。只要把每个音色资源的声音ID(S_xxxxx)复制到本项目。然后分配给系统的账号使用即可。以下是详细步骤: -```Python -python uploadAndStatus.py -python tts_http_demo.py -``` -Go back to the Volcano Engine console page and refresh it to see that the status of the sound replication details is successful. -### 3. Fill in the configuration file -Fill in the key applied for by the Volcano Engine service into the HuoshanDoubleStreamTTS configuration file in .config.yaml +### 1.开通火山引擎服务 +访问 https://console.volcengine.com/speech/app 在应用管理创建应用,勾选语音合成大模型和声音复刻大模型。 -Modify the resource_id parameter to ``` volc.megatts.default``` -(See the official documentation at https://www.volcengine.com/docs/6561/1329505) -Fill in the sound ID (S_xxxxx) of the speaker parameter +### 2.获取音色资源ID +访问 https://console.volcengine.com/speech/service/9999 复制三项内容,分别是App Id,Access Token以及声音ID(S_xxxxx)。如图 -Start the service. If the sound produced by Xiaozhi when waking him up is the cloned one, it means success. +![获取音色资源](images/image-clone-integration-01.png) + +## 第二阶段:配置火山引擎服务 + +### 1.填写火山引擎配置 + +使用超级管理员账号登录智控台,点击顶部【模型配置】,再点击模型配置页面左侧的【语音合成】,搜索找到“火山双流式语音合成”,点击修改,将你火山引擎的`App Id`填入到【应用ID】字段里,将`Access Token`填入到【访问令牌】字段里。然后保存。 + +### 2.将音色资源ID分配给系统账号 + +使用超级管理员账号登录智控台,点击顶部【音色克隆】、【音色资源】。 + +点击新增按钮,在【平台名称】选择“火山双流式语音合成”; + +在【音色资源ID】填入你火山引擎的声音资源ID(S_xxxxx),填入后按回车; + +在【归属账号】选择你要分配给的系统账号,你可以分配给你自己。然后点击保存 + +## 第三阶段:克隆阶段 + +如果登录后,点击顶部【音色克隆】》【音色克隆】,显示【您的账号暂无音色资源请联系管理员分配音色资源】,说明你在第二阶段还没有把音色资源ID分配给这个账号。那就是回到第二阶段,分配音色资源给对应的账号。 + +如果登录后,点击顶部【音色克隆】》【音色克隆】,能看到对应的音色列表。请继续。 + +在列表里会看到对应的音色列表。选择其中一个音色资源,点击【上传音频】按钮。上传后,可以试听一下声音或者截取某段声音。确认后点击【上传音频】按钮。 +![上传音频](images/image-clone-integration-02.png) + +上传音频后,在列表里会看到对应的音色会变成“待复刻”状态。点击【立即复刻】按钮。等1~2秒会返回结果。 + +如果复刻失败,请将鼠标放到“错误信息”图标上,会显示失败的原因。 + +如果复刻成功,在列表里会看到对应的音色会变成“训练成功”状态。此时你可以点击【声音名称】栏的修改按钮,修改音色资源的名称,方便后期选择使用。 + +## 第四阶段:使用阶段 + +点击顶部【智能体管理】,选择任意一个智能体,点击【配置角色】按钮。 + +语音合成(TTS)选择“火山双流式语音合成”。在列表里,找到名字带有“克隆音色”的音色资源(如图),选择它,点击保存。 +![选择音色](images/image-clone-integration-03.png) + +接下来,可以唤醒小智和它对话。 diff --git a/docs/images/demo1.png b/docs/images/demo1.png index 6459a06fd..1ab7c2247 100644 Binary files a/docs/images/demo1.png and b/docs/images/demo1.png differ diff --git a/docs/images/demo6.png b/docs/images/demo6.png index dc4edbebe..51f1f5e65 100644 Binary files a/docs/images/demo6.png and b/docs/images/demo6.png differ diff --git a/docs/images/demo9.png b/docs/images/demo9.png index ce74a02df..ff422fe9c 100644 Binary files a/docs/images/demo9.png and b/docs/images/demo9.png differ diff --git a/docs/images/image-clone-integration-01.png b/docs/images/image-clone-integration-01.png new file mode 100644 index 000000000..7132ee7a5 Binary files /dev/null and b/docs/images/image-clone-integration-01.png differ diff --git a/docs/images/image-clone-integration-02.png b/docs/images/image-clone-integration-02.png new file mode 100644 index 000000000..80972df9b Binary files /dev/null and b/docs/images/image-clone-integration-02.png differ diff --git a/docs/images/image-clone-integration-03.png b/docs/images/image-clone-integration-03.png new file mode 100644 index 000000000..7f35e3933 Binary files /dev/null and b/docs/images/image-clone-integration-03.png differ diff --git a/docs/index-stream-integration.md b/docs/index-stream-integration.md index 08f5afd67..446685218 100644 --- a/docs/index-stream-integration.md +++ b/docs/index-stream-integration.md @@ -1,14 +1,18 @@ # IndexStreamTTS Usage Guide -## Environment Preparation -### 1. Clone the project (note that the release version of VLLM1.0 is used here) +## 环境准备 +### 1. 克隆项目 ```bash -https://github.com/Ksuriuri/index-tts-vllm/releases/tag/IndexTTS-vLLM-1.0 +git clone https://github.com/Ksuriuri/index-tts-vllm.git ``` Enter the unzipped directory ```bash cd index-tts-vllm ``` +切换到指定版本 (使用VLLM-0.10.2的历史版本) +```bash +git checkout 224e8d5e5c8f66801845c66b30fa765328fd0be3 +``` ### 2. Create and activate a conda environment ```bash @@ -34,22 +38,23 @@ Cuda compilation tools, release 12.8, V12.8.89 ```bash pip install torch torchvision ``` -You need PyTorch version 2.8.0 (corresponding to VLLM 0.10.2). For specific installation instructions, please refer to the [PyTorch official website](https://pytorch.org/get-started/locally/) +需要 pytorch 版本 2.8.0(对应 vllm 0.10.2),具体安装指令请参考:[pytorch 官网](https://pytorch.org/get-started/locally/) ### 4. Install dependencies ```bash pip install -r requirements.txt ``` -### 5. Download model weights -This is the official weight file, which can be downloaded to any local path. It supports the weight of IndexTTS-1.5. +### 5. 下载模型权重 +### 方案一:下载官方权重文件后转换 +此为官方权重文件,下载到本地任意路径即可,支持 IndexTTS-1.5 的权重 | HuggingFace | ModelScope | |---------------------------------------------------------------|---------------------------------------------------------------------| | [IndexTTS](https://huggingface.co/IndexTeam/Index-TTS) | [IndexTTS](https://modelscope.cn/models/IndexTeam/Index-TTS) | | [IndexTTS-1.5](https://huggingface.co/IndexTeam/IndexTTS-1.5) | [IndexTTS-1.5](https://modelscope.cn/models/IndexTeam/IndexTTS-1.5) | -The following is an example of how to install ModelScope -### Please note: Git needs to be installed and initialized to enable LFS (if already installed, you can skip this step) +下面以ModelScope的安装方法为例 +#### 请注意:git需要安装并初始化启用lfs(如已安装可以跳过) ```bash sudo apt-get install git-lfs git lfs install @@ -61,8 +66,8 @@ cd model_dir git clone https://www.modelscope.cn/IndexTeam/IndexTTS-1.5.git ``` -### 5. Model weight conversion -```bash +#### 模型权重转换 +```bash bash convert_hf_format.sh /path/to/your/model_dir ``` For example, if the IndexTTS-1.5 model you downloaded is stored in the model_dir directory, execute the following command: @@ -169,10 +174,12 @@ The log will be output in tmp/server.log. You can view the log status by the fol ```bash tail -f tmp/server.log ``` -## Tone Configuration -index-tts-vllm supports registering custom timbres through configuration files, and supports single-timbre and mixed-timbre configurations. -Configure custom timbre in the assets/speaker.json file in the project root directory -### Configuration format description +如果显卡内存足够,可在脚本中添加启动参数 ----gpu_memory_utilization 来调整显存占用比例,默认值为 0.25 + +## 音色配置 +index-tts-vllm支持通过配置文件注册自定义音色,支持单音色和混合音色配置。 +在项目根目录下的assets/speaker.json文件中配置自定义音色 +### 配置格式说明 ```bash { "Speaker Name 1": [ @@ -184,5 +191,5 @@ Configure custom timbre in the assets/speaker.json file in the project root dire ] } ``` -### Note (need to restart the service to register) -After adding, you need to add the corresponding speaker in the smart console (for single module, change the corresponding voice) +### 注意 (配置角色后需重启服务进行音色注册) +添加后需在智控台中添加相应的说话人(单模块则更换相应的voice) diff --git a/docs/mcp-get-device-info.md b/docs/mcp-get-device-info.md new file mode 100644 index 000000000..bf4799587 --- /dev/null +++ b/docs/mcp-get-device-info.md @@ -0,0 +1,40 @@ +# MCP 方法如何获取设备信息 + +本教程将指导你如何使用MCP方法获取设备信息。 + +第一步:自定义你的`agent-base-prompt.txt`文件 + +把xiaozhi-server目录的`agent-base-prompt.txt`文件内容复制到你的`data`目录下,并重命名为`.agent-base-prompt.txt`。 + +第二步:修改`data/.agent-base-prompt.txt`文件,找到``标签,在标签内容中添加以下代码内容: +``` +- **设备ID:** {{device_id}} +``` + +添加完成后,你的`data/.agent-base-prompt.txt`文件的``标签内容大致如下: +``` + +【重要!以下信息已实时提供,无需调用工具查询,请直接使用:】 +- **设备ID:** {{device_id}} +- **当前时间:** {{current_time}} +- **今天日期:** {{today_date}} ({{today_weekday}}) +- **今天农历:** {{lunar_date}} +- **用户所在城市:** {{local_address}} +- **当地未来7天天气:** {{weather_info}} + +``` + +第三步:修改`data/.config.yaml`文件,找到`agent-base-prompt`配置,修改前内容如下: +``` +prompt_template: agent-base-prompt.txt +``` +修改成 +``` +prompt_template: data/.agent-base-prompt.txt +``` + +第四步:重启你的xiaozhi-server服务。 + +第五步:在你的mcp方法增加名称为`device_id`,类型为`string`,描述为`设备ID`的参数。 + +第六步:重新唤醒小智,让他调用mcp方法,查看你的mcp方法是否可以获取`设备ID`。 diff --git a/docs/mqtt-gateway-integration.md b/docs/mqtt-gateway-integration.md index 8d8bd34d8..1d386c8b0 100644 --- a/docs/mqtt-gateway-integration.md +++ b/docs/mqtt-gateway-integration.md @@ -11,12 +11,12 @@ Prepare the `mqtt-websocket` connection address of your `xiaozhi-server`. Based 1. If you are deploying from source code, your `mqtt-websocket` address is: ``` -ws://127.0.0.1:8000/xiaozhi/v1?from=mqtt_gateway +ws://127.0.0.1:8000/xiaozhi/v1/?from=mqtt_gateway ``` 2. If you are deploying with docker, your `mqtt-websocket` address is ``` -ws://your host LAN IP:8000/xiaozhi/v1?from=mqtt_gateway +ws://你宿主机局域网IP:8000/xiaozhi/v1/?from=mqtt_gateway ``` ## Important Note @@ -53,7 +53,7 @@ cp config/mqtt.json.example config/mqtt.json { "production": { "chat_servers": [ - "ws://127.0.0.1:8000/xiaozhi/v1?from=mqtt_gateway" + "ws://127.0.0.1:8000/xiaozhi/v1/?from=mqtt_gateway" ] }, "debug": false, diff --git a/docs/ragflow-integration.md b/docs/ragflow-integration.md new file mode 100644 index 000000000..c2cd20f5f --- /dev/null +++ b/docs/ragflow-integration.md @@ -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知识库 +登录到智控台。在顶部导航栏中,点击`智能体`,找到你要配置的智能体,点击`配置角色`按钮。 + +在意图识别左侧,点击`编辑功能`按钮,弹出一个弹框。在弹框中选择你要添加的知识库。保存即可。 diff --git a/docs/voiceprint-integration.md b/docs/voiceprint-integration.md index 19bcb0b10..e559d51b4 100644 --- a/docs/voiceprint-integration.md +++ b/docs/voiceprint-integration.md @@ -28,7 +28,7 @@ If you can access port 3306, please ignore the following content and go directly If you can't access it, you need to recall how you installed `mysql`. -If you installed MySQL using a package yourself, it means your MySQL server is isolated from the network. You may need to first resolve the issue of accessing port 3306 of MySQL server. +如果你的mysql是通过自己使用安装包安装的,说明你的`mysql`做了网络隔离。你可能先解决访问`mysql`的`3306`端口这个问题。 If you installed `mysql` through `docker-compose_all.yml` of this project, you need to find the `docker-compose_all.yml` file where you created the database and modify the following content diff --git a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java index febe12ffe..a7deaba19 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java +++ b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java @@ -146,6 +146,16 @@ public interface Constant { */ String MEMORY_NO_MEM = "Memory_nomem"; + /** + * 火山引擎双声道语音克隆 + */ + String VOICE_CLONE_HUOSHAN_DOUBLE_STREAM = "huoshan_double_stream"; + + /** + * RAG配置类型 + */ + String RAG_CONFIG_TYPE = "RAG"; + enum SysBaseParam { /** * ICP备案号 @@ -171,6 +181,38 @@ public interface Constant { } } + /** + * 训练状态 + */ + enum TrainStatus { + /** + * 未训练 + */ + NOT_TRAINED(0), + /** + * 训练中 + */ + TRAINING(1), + /** + * 已训练 + */ + TRAINED(2), + /** + * 训练失败 + */ + TRAIN_FAILED(3); + + private final int code; + + TrainStatus(int code) { + this.code = code; + } + + public int getCode() { + return code; + } + } + /** * 系统短信 */ @@ -257,7 +299,7 @@ public interface Constant { /** * 版本号 */ - public static final String VERSION = "0.8.4"; + public static final String VERSION = "0.8.8"; /** * 无效固件URL diff --git a/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java b/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java index 573269b87..659e135ac 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java +++ b/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java @@ -55,7 +55,7 @@ public interface ErrorCode { int OTA_DEVICE_NOT_FOUND = 10041; int OTA_DEVICE_NEED_BIND = 10042; - + // 新增错误编码 int DELETE_DATA_FAILED = 10043; int USER_NOT_LOGIN = 10044; @@ -66,7 +66,7 @@ public interface ErrorCode { int INVALID_LLM_TYPE = 10049; int TOKEN_GENERATE_ERROR = 10050; int RESOURCE_NOT_FOUND = 10051; - + // 新增错误编码 int DEFAULT_AGENT_NOT_FOUND = 10052; int AGENT_NOT_FOUND = 10053; @@ -82,14 +82,6 @@ public interface ErrorCode { int DEVICE_ALREADY_ACTIVATED = 10063; // 默认模型删除错误 int DEFAULT_MODEL_DELETE_ERROR = 10064; - // 设备相关错误码 - int MAC_ADDRESS_ALREADY_EXISTS = 10090; // Mac地址已存在 - // 模型相关错误码 - int MODEL_PROVIDER_NOT_EXIST = 10091; // 供应器不存在 - int LLM_NOT_EXIST = 10092; // 设置的LLM不存在 - int MODEL_REFERENCED_BY_AGENT = 10093; // 该模型配置已被智能体引用,无法删除 - int LLM_REFERENCED_BY_INTENT = 10094; // 该LLM模型已被意图识别配置引用,无法删除 - // 登录相关错误码 int ADD_DATA_FAILED = 10065; // 新增数据失败 int UPDATE_DATA_FAILED = 10066; // 修改数据失败 @@ -102,17 +94,17 @@ public interface ErrorCode { int RETRIEVE_PASSWORD_DISABLED = 10073; // 未开启找回密码功能 int PHONE_FORMAT_ERROR = 10074; // 手机号码格式不正确 int SMS_CODE_ERROR = 10075; // 手机验证码错误 - + // 字典类型相关错误码 int DICT_TYPE_NOT_EXIST = 10076; // 字典类型不存在 int DICT_TYPE_DUPLICATE = 10077; // 字典类型编码重复 - + // 资源处理相关错误码 int RESOURCE_READ_ERROR = 10078; // 读取资源失败 - + // 智能体相关错误码 int LLM_INTENT_PARAMS_MISMATCH = 10079; // LLM大模型和Intent意图识别,选择参数不匹配 - + // 声纹相关错误码 int VOICEPRINT_ALREADY_REGISTERED = 10080; // 此声音声纹已经注册 int VOICEPRINT_DELETE_ERROR = 10081; // 删除声纹出现错误 @@ -126,12 +118,16 @@ public interface ErrorCode { int VOICEPRINT_UNREGISTER_REQUEST_ERROR = 10089; // 声纹注销请求失败 int VOICEPRINT_UNREGISTER_PROCESS_ERROR = 10090; // 声纹注销处理失败 int VOICEPRINT_IDENTIFY_REQUEST_ERROR = 10091; // 声纹识别请求失败 - + + int LLM_NOT_EXIST = 10092; // 设置的LLM不存在 + int MODEL_REFERENCED_BY_AGENT = 10093; // 该模型配置已被智能体引用,无法删除 + int LLM_REFERENCED_BY_INTENT = 10094; // 该LLM模型已被意图识别配置引用,无法删除 + // 服务端管理相关错误码 int INVALID_SERVER_ACTION = 10095; // 无效服务端操作 int SERVER_WEBSOCKET_NOT_CONFIGURED = 10096; // 未配置服务端WebSocket地址 int TARGET_WEBSOCKET_NOT_EXIST = 10097; // 目标WebSocket地址不存在 - + // 参数验证相关错误码 int WEBSOCKET_URLS_EMPTY = 10098; // WebSocket地址列表不能为空 int WEBSOCKET_URL_LOCALHOST = 10099; // WebSocket地址不能使用localhost或127.0.0.1 @@ -175,7 +171,7 @@ public interface ErrorCode { int DOWNLOAD_LINK_INVALID = 10137; // 下载链接无效 int CHAT_ROLE_USER = 10138; // 用户角色 int CHAT_ROLE_AGENT = 10139; // 智能体角色 - + // 声音克隆相关错误码 int VOICE_CLONE_AUDIO_EMPTY = 10140; // 音频文件不能为空 int VOICE_CLONE_NOT_AUDIO_FILE = 10141; // 只支持音频文件 @@ -188,4 +184,33 @@ public interface ErrorCode { int VOICE_RESOURCE_ACCOUNT_EMPTY = 10148; // 归属账号不能为空 int VOICE_RESOURCE_DELETE_ID_EMPTY = 10149; // 删除的音色资源ID不能为空 int VOICE_RESOURCE_NO_PERMISSION = 10150; // 您没有权限操作该记录 + int VOICE_CLONE_AUDIO_NOT_UPLOADED = 10151; // 请先上传音频文件 + int VOICE_CLONE_MODEL_CONFIG_NOT_FOUND = 10152; // 模型配置未找到 + int VOICE_CLONE_MODEL_TYPE_NOT_FOUND = 10153; // 模型类型未找到 + int VOICE_CLONE_TRAINING_FAILED = 10154; // 训练失败 + int VOICE_CLONE_HUOSHAN_CONFIG_MISSING = 10155; // 火山引擎缺少配置 + int VOICE_CLONE_RESPONSE_FORMAT_ERROR = 10156; // 响应格式错误 + int VOICE_CLONE_REQUEST_FAILED = 10157; // 请求失败 + int VOICE_CLONE_PREFIX = 10158; // 复刻音色前缀 + int VOICE_ID_ALREADY_EXISTS = 10159; // 音色ID已存在 + int VOICE_CLONE_HUOSHAN_VOICE_ID_ERROR = 10160; // 火山引擎音色ID格式错误 + + // 设备相关错误码 + int MAC_ADDRESS_ALREADY_EXISTS = 10161; // Mac地址已存在 + // 模型相关错误码 + int MODEL_PROVIDER_NOT_EXIST = 10162; // 供应器不存在 + + // 知识库相关错误码 + int Knowledge_Base_RECORD_NOT_EXISTS = 10163; // 知识库记录不存在 + int RAG_CONFIG_NOT_FOUND = 10164; // RAG配置未找到 + int RAG_CONFIG_TYPE_ERROR = 10165; // RAG配置类型错误 + int RAG_DEFAULT_CONFIG_NOT_FOUND = 10166; // 默认RAG配置未找到 + int RAG_API_ERROR = 10167; // RAG调用失败 + int UPLOAD_FILE_ERROR = 10168; // 上传文件失败 + int NO_PERMISSION = 10169; // 没有权限 + int KNOWLEDGE_BASE_NAME_EXISTS = 10170; // 同名知识库已存在 + int RAG_API_ERROR_URL_NULL = 10171; // RAG配置中base_url为空,请完善配置 + int RAG_API_ERROR_API_KEY_NULL = 10172; // RAG配置中api_key为空,请完善配置 + int RAG_API_ERROR_API_KEY_INVALID = 10173; // RAG配置中api_key包含占位符,请替换为实际的API密钥 + int RAG_API_ERROR_URL_INVALID = 10174; // RAG配置中base_url格式不正确,请检查协议是否正确 } diff --git a/main/manager-api/src/main/java/xiaozhi/common/handler/FieldMetaObjectHandler.java b/main/manager-api/src/main/java/xiaozhi/common/handler/FieldMetaObjectHandler.java index a6b33b620..95add2f06 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/handler/FieldMetaObjectHandler.java +++ b/main/manager-api/src/main/java/xiaozhi/common/handler/FieldMetaObjectHandler.java @@ -32,13 +32,23 @@ public class FieldMetaObjectHandler implements MetaObjectHandler { // 创建者 strictInsertFill(metaObject, CREATOR, Long.class, user.getId()); - // 创建时间 - strictInsertFill(metaObject, CREATE_DATE, Date.class, date); + // 创建时间 - 支持createDate和createdAt两种字段名 + if (metaObject.hasSetter(CREATE_DATE)) { + strictInsertFill(metaObject, CREATE_DATE, Date.class, date); + } + if (metaObject.hasSetter("createdAt")) { + strictInsertFill(metaObject, "createdAt", Date.class, date); + } // 更新者 strictInsertFill(metaObject, UPDATER, Long.class, user.getId()); - // 更新时间 - strictInsertFill(metaObject, UPDATE_DATE, Date.class, date); + // 更新时间 - 支持updateDate和updatedAt两种字段名 + if (metaObject.hasSetter(UPDATE_DATE)) { + strictInsertFill(metaObject, UPDATE_DATE, Date.class, date); + } + if (metaObject.hasSetter("updatedAt")) { + strictInsertFill(metaObject, "updatedAt", Date.class, date); + } // 数据标识 strictInsertFill(metaObject, DATA_OPERATION, String.class, Constant.DataOperation.INSERT.getValue()); @@ -46,10 +56,17 @@ public class FieldMetaObjectHandler implements MetaObjectHandler { @Override public void updateFill(MetaObject metaObject) { + Date date = new Date(); + // 更新者 strictUpdateFill(metaObject, UPDATER, Long.class, SecurityUser.getUserId()); - // 更新时间 - strictUpdateFill(metaObject, UPDATE_DATE, Date.class, new Date()); + // 更新时间 - 支持updateDate和updatedAt两种字段名 + if (metaObject.hasSetter(UPDATE_DATE)) { + strictUpdateFill(metaObject, UPDATE_DATE, Date.class, date); + } + if (metaObject.hasSetter("updatedAt")) { + strictUpdateFill(metaObject, "updatedAt", Date.class, date); + } // 数据标识 strictInsertFill(metaObject, DATA_OPERATION, String.class, Constant.DataOperation.UPDATE.getValue()); diff --git a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java index d25c72b6f..3a9697131 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java +++ b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java @@ -152,4 +152,11 @@ public class RedisKeys { public static String getVoiceCloneAudioIdKey(String uuid) { return "voiceClone:audio:id:" + uuid; } + + /** + * 获取知识库缓存key + */ + public static String getKnowledgeBaseCacheKey(String datasetId) { + return "knowledge:base:" + datasetId; + } } diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java index c346bf3da..abcc2cb3d 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java @@ -11,15 +11,15 @@ import org.springframework.context.i18n.LocaleContextHolder; public class MessageUtils { private static MessageSource messageSource; - static { - messageSource = (MessageSource) SpringContextUtils.getBean("messageSource"); - } - public static String getMessage(int code) { return getMessage(code, new String[0]); } public static String getMessage(int code, String... params) { + if (messageSource == null) { + // 延迟初始化,确保Spring上下文已完全初始化 + messageSource = (MessageSource) SpringContextUtils.getBean("messageSource"); + } return messageSource.getMessage(code + "", params, LocaleContextHolder.getLocale()); } } diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/SensitiveDataUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/SensitiveDataUtils.java index 05f4853a0..4d5715cc1 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/utils/SensitiveDataUtils.java +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/SensitiveDataUtils.java @@ -1,14 +1,15 @@ package xiaozhi.common.utils; -import cn.hutool.json.JSONObject; -import org.apache.commons.lang3.StringUtils; - import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; import java.util.Map; -import java.util.HashMap; import java.util.Set; +import org.apache.commons.lang3.StringUtils; + +import cn.hutool.json.JSONObject; + /** * 敏感数据处理工具类 */ @@ -30,7 +31,7 @@ public class SensitiveDataUtils { * 隐藏字符串中间部分 */ public static String maskMiddle(String value) { - if (StringUtils.isBlank(value)) { + if (StringUtils.isBlank(value) || value.length() == 1) { return value; } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java index 2a53d4748..6d839d9c5 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentPluginMappingServiceImpl.java @@ -1,16 +1,26 @@ package xiaozhi.modules.agent.service.impl; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; 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; import xiaozhi.modules.agent.service.AgentPluginMappingService; +import xiaozhi.modules.knowledge.entity.KnowledgeBaseEntity; +import xiaozhi.modules.knowledge.service.KnowledgeBaseService; +import xiaozhi.modules.model.entity.ModelConfigEntity; +import xiaozhi.modules.model.service.ModelConfigService; /** * @description 针对表【ai_agent_plugin_mapping(Agent与插件的唯一映射表)】的数据库操作Service实现 @@ -18,13 +28,73 @@ import xiaozhi.modules.agent.service.AgentPluginMappingService; */ @Service @RequiredArgsConstructor +@Slf4j public class AgentPluginMappingServiceImpl extends ServiceImpl implements AgentPluginMappingService { private final AgentPluginMappingMapper agentPluginMappingMapper; + private final KnowledgeBaseService knowledgeBaseService; + private final ModelConfigService modelConfigService; @Override public List agentPluginParamsByAgentId(String agentId) { - return agentPluginMappingMapper.selectPluginsByAgentId(agentId); + List list = agentPluginMappingMapper.selectPluginsByAgentId(agentId); + Map> knowledgeBaseMap = new HashMap<>(); + Map modelConfigMap = new HashMap<>(); + for (int i = list.size() - 1; i >= 0; i--) { + AgentPluginMapping mapping = list.get(i); + if (StringUtils.isBlank(mapping.getProviderCode())) { + // 查询知识库插件参数 + KnowledgeBaseEntity knowledgeBaseEntity = knowledgeBaseService.selectById(mapping.getPluginId()); + if (knowledgeBaseEntity == null) { + list.remove(i); + continue; + } + ModelConfigEntity modelConfigEntity = modelConfigService + .getModelByIdFromCache(knowledgeBaseEntity.getRagModelId()); + if (modelConfigEntity == null) { + list.remove(i); + continue; + } + List knowledgeBaseList = knowledgeBaseMap.get(modelConfigEntity.getModelCode()); + if (knowledgeBaseList == null) { + knowledgeBaseList = new ArrayList<>(); + } + modelConfigMap.put(modelConfigEntity.getModelCode(), modelConfigEntity); + knowledgeBaseList.add(knowledgeBaseEntity); + knowledgeBaseMap.put(modelConfigEntity.getModelCode(), knowledgeBaseList); + list.remove(i); + } + } + if (knowledgeBaseMap.size() > 0) { + for (String pluginCode : knowledgeBaseMap.keySet()) { + List knowledgeBaseList = knowledgeBaseMap.get(pluginCode); + if (knowledgeBaseList == null || knowledgeBaseList.isEmpty()) { + continue; + } + + AgentPluginMapping agentPluginMapping = new AgentPluginMapping(); + agentPluginMapping.setAgentId(agentId); + agentPluginMapping.setPluginId(pluginCode); + agentPluginMapping.setProviderCode("search_from_" + pluginCode); + agentPluginMapping.setId(Long.valueOf(list.size() + 1)); + + Map paramInfo = new HashMap<>(4); + ModelConfigEntity modelConfigEntity = modelConfigMap.get(pluginCode); + paramInfo.put("base_url", modelConfigEntity.getConfigJson().getStr("base_url")); + paramInfo.put("api_key", modelConfigEntity.getConfigJson().getStr("api_key")); + paramInfo.put("dataset_ids", + knowledgeBaseList.stream().map(KnowledgeBaseEntity::getDatasetId).toList()); + + String description = "如果用户询问与【" + + String.join(",", knowledgeBaseList.stream().map(KnowledgeBaseEntity::getName).toList()) + + "】涵盖的主体范围相关内容时应调用本方法,用于查询:" + String.join(",", + knowledgeBaseList.stream().map(KnowledgeBaseEntity::getDescription).toList()); + paramInfo.put("description", description); + agentPluginMapping.setParamInfo(JsonUtils.toJsonString(paramInfo)); + list.add(agentPluginMapping); + } + } + return list; } @Override diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java index 72b8ea4d6..3556877d1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java @@ -42,6 +42,7 @@ import xiaozhi.modules.agent.service.AgentTemplateService; import xiaozhi.modules.agent.vo.AgentInfoVO; import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.model.dto.ModelProviderDTO; +import xiaozhi.modules.model.dto.VoiceDTO; import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; import xiaozhi.modules.model.service.ModelProviderService; @@ -373,6 +374,22 @@ public class AgentServiceImpl extends BaseServiceImpl imp entity.setLlmModelId(template.getLlmModelId()); entity.setVllmModelId(template.getVllmModelId()); entity.setTtsModelId(template.getTtsModelId()); + + if (template.getTtsVoiceId() == null && template.getTtsModelId() != null) { + ModelConfigEntity ttsModel = modelConfigService.selectById(template.getTtsModelId()); + if (ttsModel != null && ttsModel.getConfigJson() != null) { + Map config = ttsModel.getConfigJson(); + String voice = (String) config.get("voice"); + if (StringUtils.isBlank(voice)) { + voice = (String) config.get("speaker"); + } + VoiceDTO timbre = timbreModelService.getByVoiceCode(template.getTtsModelId(), voice); + if (timbre != null) { + template.setTtsVoiceId(timbre.getId()); + } + } + } + entity.setTtsVoiceId(template.getTtsVoiceId()); entity.setMemModelId(template.getMemModelId()); entity.setIntentModelId(template.getIntentModelId()); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java index 8c562edb9..321b5cb27 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentTemplateServiceImpl.java @@ -45,6 +45,10 @@ public class AgentTemplateServiceImpl extends ServiceImpl wrapper = new UpdateWrapper<>(); switch (modelType) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java index 1b0181bc0..7883b8c1e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java @@ -38,6 +38,8 @@ import xiaozhi.modules.sys.dto.SysParamsDTO; import xiaozhi.modules.sys.service.SysParamsService; import xiaozhi.modules.timbre.service.TimbreService; import xiaozhi.modules.timbre.vo.TimbreDetailsVO; +import xiaozhi.modules.voiceclone.entity.VoiceCloneEntity; +import xiaozhi.modules.voiceclone.service.VoiceCloneService; @Service @AllArgsConstructor @@ -51,6 +53,7 @@ public class ConfigServiceImpl implements ConfigService { private final TimbreService timbreService; private final AgentPluginMappingService agentPluginMappingService; private final AgentMcpAccessPointService agentMcpAccessPointService; + private final VoiceCloneService cloneVoiceService; private final AgentVoicePrintDao agentVoicePrintDao; @Override @@ -88,6 +91,7 @@ public class ConfigServiceImpl implements ConfigService { null, null, null, + null, result, isCache); @@ -124,6 +128,11 @@ public class ConfigServiceImpl implements ConfigService { voice = timbre.getTtsVoice(); referenceAudio = timbre.getReferenceAudio(); referenceText = timbre.getReferenceText(); + } else { + VoiceCloneEntity voice_print = cloneVoiceService.selectById(agent.getTtsVoiceId()); + if (voice_print != null) { + voice = voice_print.getVoiceId(); + } } // 构建返回数据 Map result = new HashMap<>(); @@ -187,6 +196,7 @@ public class ConfigServiceImpl implements ConfigService { agent.getTtsModelId(), agent.getMemModelId(), agent.getIntentModelId(), + null, result, true); @@ -363,12 +373,14 @@ public class ConfigServiceImpl implements ConfigService { String ttsModelId, String memModelId, String intentModelId, + String ragModelId, Map result, boolean isCache) { Map selectedModule = new HashMap<>(); - String[] modelTypes = { "VAD", "ASR", "TTS", "Memory", "Intent", "LLM", "VLLM" }; - String[] modelIds = { vadModelId, asrModelId, ttsModelId, memModelId, intentModelId, llmModelId, vllmModelId }; + String[] modelTypes = { "VAD", "ASR", "TTS", "Memory", "Intent", "LLM", "VLLM", "RAG" }; + String[] modelIds = { vadModelId, asrModelId, ttsModelId, memModelId, intentModelId, llmModelId, vllmModelId, + ragModelId }; String intentLLMModelId = null; String memLocalShortLLMModelId = null; @@ -392,6 +404,15 @@ public class ConfigServiceImpl implements ConfigService { ((Map) model.getConfigJson()).put("ref_audio", referenceAudio); if (referenceText != null) ((Map) model.getConfigJson()).put("ref_text", referenceText); + + // 火山引擎声音克隆需要替换resource_id + Map map = (Map) model.getConfigJson(); + if (Constant.VOICE_CLONE_HUOSHAN_DOUBLE_STREAM.equals(map.get("type"))) { + // 如果voice是”S_“开头的,使用seed-icl-1.0 + if (voice != null && voice.startsWith("S_")) { + map.put("resource_id", "seed-icl-1.0"); + } + } } // 如果是Intent类型,且type=intent_llm,则给他添加附加模型 if ("Intent".equals(modelTypes[i])) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java index e476dc326..a3f9d2366 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java @@ -93,7 +93,7 @@ public class DeviceController { } @PostMapping("/bind/{agentId}") - @Operation(summary = "转发POST请求到MQTT网关") + @Operation(summary = "设备在线接口") @RequiresPermissions("sys:role:normal") public Result forwardToMqttGateway(@PathVariable String agentId, @RequestBody String requestBody) { try { @@ -208,63 +208,4 @@ public class DeviceController { deviceService.manualAddDevice(user.getId(), dto); return new Result<>(); } - - @PostMapping("/commands/{deviceId}") - @Operation(summary = "发送设备指令") - @RequiresPermissions("sys:role:normal") - public Result sendDeviceCommand(@PathVariable String deviceId, @RequestBody String command) { - try { - // 从系统参数中获取MQTT网关地址 - String mqttGatewayUrl = sysParamsService.getValue("server.mqtt_manager_api", true); - if (StringUtils.isBlank(mqttGatewayUrl) || "null".equals(mqttGatewayUrl)) { - return new Result().error("MQTT网关地址未配置"); - } - - // 构建完整的URL - // 获取设备信息以构建mqttClientId - DeviceEntity deviceById = deviceService.selectById(deviceId); - - if (!deviceById.getUserId().equals(SecurityUser.getUser().getId())) { - return new Result().error("设备不存在"); - } - String macAddress = deviceById != null ? deviceById.getMacAddress() : "unknown"; - String groupId = deviceById != null ? deviceById.getBoard() : null; - if (groupId == null) { - groupId = "GID_default"; - } - groupId = groupId.replace(":", "_"); - macAddress = macAddress.replace(":", "_"); - - // 拼接为groupId@@@macAddress@@@deviceId格式 - String mqttClientId = groupId + "@@@" + macAddress + "@@@" + macAddress; - - String url = "http://" + mqttGatewayUrl + "/api/commands/" + mqttClientId; - - // 设置请求头 - HttpHeaders headers = new HttpHeaders(); - headers.set("Content-Type", "application/json"); - - // 生成Bearer令牌 - String dateStr = java.time.LocalDate.now() - .format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd")); - String signatureKey = sysParamsService.getValue("server.mqtt_signature_key", false); - if (StringUtils.isBlank(signatureKey)) { - return new Result().error("MQTT签名密钥未配置"); - } - String tokenContent = dateStr + signatureKey; - String token = org.apache.commons.codec.digest.DigestUtils.sha256Hex(tokenContent); - headers.set("Authorization", "Bearer " + token); - - // 构建请求体 - HttpEntity requestEntity = new HttpEntity<>(command, headers); - - // 发送POST请求 - ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class); - - // 返回响应 - return new Result().ok(response.getBody()); - } catch (Exception e) { - return new Result().error("发送指令失败: " + e.getMessage()); - } - } } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java index 423868ca1..85c8972af 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java @@ -19,7 +19,7 @@ public class DeviceReportRespDTO { @Schema(description = "固件版本信息") private Firmware firmware; - + @Schema(description = "WebSocket配置") private Websocket websocket; @@ -66,12 +66,14 @@ public class DeviceReportRespDTO { @Schema(description = "时区偏移量,单位为分钟") private Integer timezone_offset; } - + @Getter @Setter public static class Websocket { @Schema(description = "WebSocket服务器地址") private String url; + @Schema(description = "WebSocket 认证 token") + private String token; } @Getter diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java index a79d1f2e9..5c3f854df 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java @@ -169,6 +169,7 @@ public class DeviceServiceImpl extends BaseServiceImpl DeviceReportRespDTO.Websocket websocket = new DeviceReportRespDTO.Websocket(); // 从系统参数获取WebSocket URL,如果未配置则使用默认值 String wsUrl = sysParamsService.getValue(Constant.SERVER_WEBSOCKET, true); + websocket.setToken(""); if (StringUtils.isBlank(wsUrl) || wsUrl.equals("null")) { log.error("WebSocket地址未配置,请登录智控台,在参数管理找到【server.websocket】配置"); wsUrl = "ws://xiaozhi.server.com:8000/xiaozhi/v1/"; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeBaseController.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeBaseController.java new file mode 100644 index 000000000..cddfead53 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeBaseController.java @@ -0,0 +1,159 @@ +package xiaozhi.modules.knowledge.controller; + +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.AllArgsConstructor; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.page.PageData; +import xiaozhi.common.utils.Result; +import xiaozhi.modules.knowledge.dto.KnowledgeBaseDTO; +import xiaozhi.modules.knowledge.service.KnowledgeBaseService; +import xiaozhi.modules.security.user.SecurityUser; + +@AllArgsConstructor +@RestController +@RequestMapping("/datasets") +@Tag(name = "知识库管理") +public class KnowledgeBaseController { + + private final KnowledgeBaseService knowledgeBaseService; + + @GetMapping + @Operation(summary = "分页查询知识库列表") + @RequiresPermissions("sys:role:normal") + public Result> getPageList( + @RequestParam(required = false) String name, + @RequestParam(required = false, defaultValue = "1") Integer page, + @RequestParam(required = false, defaultValue = "10") Integer page_size) { + // 获取当前登录用户ID + Long currentUserId = SecurityUser.getUserId(); + + KnowledgeBaseDTO knowledgeBaseDTO = new KnowledgeBaseDTO(); + knowledgeBaseDTO.setName(name); + knowledgeBaseDTO.setCreator(currentUserId); // 设置创建者ID,用于权限过滤 + + PageData pageData = knowledgeBaseService.getPageList(knowledgeBaseDTO, page, page_size); + return new Result>().ok(pageData); + } + + @GetMapping("/{dataset_id}") + @Operation(summary = "根据知识库ID获取知识库详情") + @RequiresPermissions("sys:role:normal") + public Result getByDatasetId(@PathVariable("dataset_id") String datasetId) { + // 获取当前登录用户ID + Long currentUserId = SecurityUser.getUserId(); + + KnowledgeBaseDTO knowledgeBaseDTO = knowledgeBaseService.getByDatasetId(datasetId); + + // 检查权限:用户只能查看自己创建的知识库 + if (knowledgeBaseDTO.getCreator() == null || !knowledgeBaseDTO.getCreator().equals(currentUserId)) { + throw new RenException(ErrorCode.NO_PERMISSION); + } + + return new Result().ok(knowledgeBaseDTO); + } + + @PostMapping + @Operation(summary = "创建知识库") + @RequiresPermissions("sys:role:normal") + public Result save(@RequestBody @Validated KnowledgeBaseDTO knowledgeBaseDTO) { + KnowledgeBaseDTO resp = knowledgeBaseService.save(knowledgeBaseDTO); + return new Result().ok(resp); + } + + @PutMapping("/{dataset_id}") + @Operation(summary = "更新知识库") + @RequiresPermissions("sys:role:normal") + public Result update(@PathVariable("dataset_id") String datasetId, + @RequestBody @Validated KnowledgeBaseDTO knowledgeBaseDTO) { + // 获取当前登录用户ID + Long currentUserId = SecurityUser.getUserId(); + + // 先获取现有知识库信息以检查权限 + KnowledgeBaseDTO existingKnowledgeBase = knowledgeBaseService.getByDatasetId(datasetId); + + // 检查权限:用户只能更新自己创建的知识库 + if (existingKnowledgeBase.getCreator() == null || !existingKnowledgeBase.getCreator().equals(currentUserId)) { + throw new RenException(ErrorCode.NO_PERMISSION); + } + + knowledgeBaseDTO.setDatasetId(datasetId); + KnowledgeBaseDTO resp = knowledgeBaseService.update(knowledgeBaseDTO); + return new Result().ok(resp); + } + + @DeleteMapping("/{dataset_id}") + @Operation(summary = "删除单个知识库") + @Parameter(name = "dataset_id", description = "知识库ID", required = true) + @RequiresPermissions("sys:role:normal") + public Result delete(@PathVariable("dataset_id") String datasetId) { + // 获取当前登录用户ID + Long currentUserId = SecurityUser.getUserId(); + + // 先获取现有知识库信息以检查权限 + KnowledgeBaseDTO existingKnowledgeBase = knowledgeBaseService.getByDatasetId(datasetId); + + // 检查权限:用户只能删除自己创建的知识库 + if (existingKnowledgeBase.getCreator() == null || !existingKnowledgeBase.getCreator().equals(currentUserId)) { + throw new RenException(ErrorCode.NO_PERMISSION); + } + + knowledgeBaseService.deleteByDatasetId(datasetId); + return new Result<>(); + } + + @DeleteMapping("/batch") + @Operation(summary = "批量删除知识库") + @Parameter(name = "ids", description = "知识库ID列表,用逗号分隔", required = true) + @RequiresPermissions("sys:role:normal") + public Result deleteBatch(@RequestParam("ids") String ids) { + if (StringUtils.isBlank(ids)) { + throw new RenException(ErrorCode.PARAMS_GET_ERROR); + } + + // 获取当前登录用户ID + Long currentUserId = SecurityUser.getUserId(); + String[] idArray = ids.split(","); + for (String datasetId : idArray) { + if (StringUtils.isNotBlank(datasetId)) { + // 先获取现有知识库信息以检查权限 + KnowledgeBaseDTO existingKnowledgeBase = knowledgeBaseService.getByDatasetId(datasetId.trim()); + + // 检查权限:用户只能删除自己创建的知识库 + if (existingKnowledgeBase.getCreator() == null + || !existingKnowledgeBase.getCreator().equals(currentUserId)) { + throw new RenException(ErrorCode.NO_PERMISSION); + } + + knowledgeBaseService.deleteByDatasetId(datasetId.trim()); + } + } + return new Result<>(); + } + + @GetMapping("/rag-models") + @Operation(summary = "获取RAG模型列表") + @RequiresPermissions("sys:role:normal") + public Result>> getRAGModels() { + List> result = knowledgeBaseService.getRAGModels(); + return new Result>>().ok(result); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeFilesController.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeFilesController.java new file mode 100644 index 000000000..fbc623091 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/controller/KnowledgeFilesController.java @@ -0,0 +1,224 @@ +package xiaozhi.modules.knowledge.controller; + +import java.util.List; +import java.util.Map; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.AllArgsConstructor; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.page.PageData; +import xiaozhi.common.utils.Result; +import xiaozhi.modules.knowledge.dto.KnowledgeBaseDTO; +import xiaozhi.modules.knowledge.dto.KnowledgeFilesDTO; +import xiaozhi.modules.knowledge.service.KnowledgeBaseService; +import xiaozhi.modules.knowledge.service.KnowledgeFilesService; +import xiaozhi.modules.security.user.SecurityUser; + +@AllArgsConstructor +@RestController +@RequestMapping("/datasets/{dataset_id}") +@Tag(name = "知识库文档管理") +public class KnowledgeFilesController { + + private final KnowledgeFilesService knowledgeFilesService; + private final KnowledgeBaseService knowledgeBaseService; + + /** + * 验证当前用户是否有权限操作指定知识库 + * + * @param datasetId 知识库ID + */ + private void validateKnowledgeBasePermission(String datasetId) { + // 获取当前登录用户ID + Long currentUserId = SecurityUser.getUserId(); + + // 获取知识库信息 + KnowledgeBaseDTO knowledgeBase = knowledgeBaseService.getByDatasetId(datasetId); + + // 检查权限:用户只能操作自己创建的知识库 + if (knowledgeBase.getCreator() == null || !knowledgeBase.getCreator().equals(currentUserId)) { + throw new RenException(ErrorCode.NO_PERMISSION); + } + } + + @GetMapping("/documents") + @Operation(summary = "分页查询文档列表") + @RequiresPermissions("sys:role:normal") + public Result> getPageList( + @PathVariable("dataset_id") String datasetId, + @RequestParam(required = false) String name, + @RequestParam(required = false) Integer status, + @RequestParam(required = false, defaultValue = "1") Integer page, + @RequestParam(required = false, defaultValue = "10") Integer page_size) { + // 验证知识库权限 + validateKnowledgeBasePermission(datasetId); + + // 如果指定了状态参数,使用状态查询接口 + if (status != null) { + PageData pageData = knowledgeFilesService.getPageListByStatus(datasetId, status, page, page_size); + return new Result>().ok(pageData); + } + + // 否则使用通用查询接口 + KnowledgeFilesDTO knowledgeFilesDTO = new KnowledgeFilesDTO(); + knowledgeFilesDTO.setDatasetId(datasetId); + knowledgeFilesDTO.setName(name); + PageData pageData = knowledgeFilesService.getPageList(knowledgeFilesDTO, page, page_size); + return new Result>().ok(pageData); + } + + @GetMapping("/documents/status/{status}") + @Operation(summary = "根据状态分页查询文档列表") + @RequiresPermissions("sys:role:normal") + public Result> getPageListByStatus( + @PathVariable("dataset_id") String datasetId, + @PathVariable("status") Integer status, + @RequestParam(required = false, defaultValue = "1") Integer page, + @RequestParam(required = false, defaultValue = "10") Integer page_size) { + // 验证知识库权限 + validateKnowledgeBasePermission(datasetId); + + PageData pageData = knowledgeFilesService.getPageListByStatus(datasetId, status, page, page_size); + return new Result>().ok(pageData); + } + + @PostMapping("/documents") + @Operation(summary = "上传文档到知识库") + @RequiresPermissions("sys:role:normal") + public Result uploadDocument( + @PathVariable("dataset_id") String datasetId, + @RequestParam("file") MultipartFile file, + @RequestParam(required = false) String name, + @RequestParam(required = false) String chunkMethod, + @RequestParam(required = false) String metaFields, + @RequestParam(required = false) String parserConfig) { + + // 验证知识库权限 + validateKnowledgeBasePermission(datasetId); + + KnowledgeFilesDTO resp = knowledgeFilesService.uploadDocument(datasetId, file, name, + metaFields != null ? parseJsonMap(metaFields) : null, + chunkMethod, + parserConfig != null ? parseJsonMap(parserConfig) : null); + return new Result().ok(resp); + } + + @DeleteMapping("/documents/{document_id}") + @Operation(summary = "删除单个文档") + @Parameter(name = "document_id", description = "文档ID", required = true) + @RequiresPermissions("sys:role:normal") + public Result delete(@PathVariable("dataset_id") String datasetId, + @PathVariable("document_id") String documentId) { + // 验证知识库权限 + validateKnowledgeBasePermission(datasetId); + + knowledgeFilesService.deleteByDocumentId(documentId, datasetId); + return new Result<>(); + } + + @PostMapping("/chunks") + @Operation(summary = "解析文档(切块)") + @RequiresPermissions("sys:role:normal") + public Result parseDocuments(@PathVariable("dataset_id") String datasetId, + @RequestBody Map> requestBody) { + // 验证知识库权限 + validateKnowledgeBasePermission(datasetId); + + List documentIds = requestBody.get("document_ids"); + if (documentIds == null || documentIds.isEmpty()) { + return new Result().error("document_ids参数不能为空"); + } + + boolean success = knowledgeFilesService.parseDocuments(datasetId, documentIds); + if (success) { + return new Result(); + } else { + return new Result().error("文档解析失败,文档可能正在处理中"); + } + } + + @GetMapping("/documents/{document_id}/chunks") + @Operation(summary = "列出指定文档的切片") + @RequiresPermissions("sys:role:normal") + public Result> listChunks(@PathVariable("dataset_id") String datasetId, + @PathVariable("document_id") String documentId, + @RequestParam(required = false) String keywords, + @RequestParam(required = false, defaultValue = "1") Integer page, + @RequestParam(required = false, defaultValue = "1024") Integer page_size, + @RequestParam(required = false) String id) { + // 验证知识库权限 + validateKnowledgeBasePermission(datasetId); + + Map result = knowledgeFilesService.listChunks(datasetId, documentId, keywords, page, page_size, + id); + return new Result>().ok(result); + } + + /** + * 召回测试 + */ + @PostMapping("/retrieval-test") + @Operation(summary = "召回测试") + @RequiresPermissions("sys:role:normal") + public Result> retrievalTest(@PathVariable("dataset_id") String datasetId, + @RequestBody Map params) { + // 验证知识库权限 + validateKnowledgeBasePermission(datasetId); + + try { + // 提取参数 + String question = (String) params.get("question"); + if (question == null || question.trim().isEmpty()) { + return new Result>().error("问题不能为空"); + } + + List datasetIds = (List) params.get("dataset_ids"); + List documentIds = (List) params.get("document_ids"); + Integer page = (Integer) params.get("page"); + Integer pageSize = (Integer) params.get("page_size"); + Float similarityThreshold = (Float) params.get("similarity_threshold"); + Float vectorSimilarityWeight = (Float) params.get("vector_similarity_weight"); + Integer topK = (Integer) params.get("top_k"); + String rerankId = (String) params.get("rerank_id"); + Boolean keyword = (Boolean) params.get("keyword"); + Boolean highlight = (Boolean) params.get("highlight"); + List crossLanguages = (List) params.get("cross_languages"); + Map metadataCondition = (Map) params.get("metadata_condition"); + + // 如果未指定数据集ID,使用当前数据集 + if (datasetIds == null || datasetIds.isEmpty()) { + datasetIds = java.util.Arrays.asList(datasetId); + } + + Map result = knowledgeFilesService.retrievalTest( + question, datasetIds, documentIds, page, pageSize, similarityThreshold, + vectorSimilarityWeight, topK, rerankId, keyword, highlight, crossLanguages, metadataCondition); + + return new Result>().ok(result); + } catch (Exception e) { + return new Result>().error("召回测试失败: " + e.getMessage()); + } + } + /** + * 解析JSON字符串为Map对象 + */ + private Map parseJsonMap(String jsonString) { + try { + ObjectMapper objectMapper = new ObjectMapper(); + return objectMapper.readValue(jsonString, new TypeReference>() { + }); + } catch (Exception e) { + throw new RuntimeException("解析JSON字符串失败: " + jsonString, e); + } + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dao/KnowledgeBaseDao.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dao/KnowledgeBaseDao.java new file mode 100644 index 000000000..b9a8aa0c9 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dao/KnowledgeBaseDao.java @@ -0,0 +1,22 @@ +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; + +/** + * 知识库知识库 + */ +@Mapper +public interface KnowledgeBaseDao extends BaseDao { + + /** + * 根据知识库ID删除相关的插件映射记录 + * + * @param knowledgeBaseId 知识库ID + */ + void deletePluginMappingByKnowledgeBaseId(@Param("knowledgeBaseId") String knowledgeBaseId); + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeBaseDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeBaseDTO.java new file mode 100644 index 000000000..77f6d1981 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeBaseDTO.java @@ -0,0 +1,49 @@ +package xiaozhi.modules.knowledge.dto; + +import java.io.Serial; +import java.io.Serializable; +import java.util.Date; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "知识库知识库") +public class KnowledgeBaseDTO implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + @Schema(description = "唯一标识") + private String id; + + @Schema(description = "知识库ID") + private String datasetId; + + @Schema(description = "RAG模型配置ID") + private String ragModelId; + + @Schema(description = "知识库名称") + private String name; + + @Schema(description = "知识库描述") + private String description; + + @Schema(description = "状态(0:禁用 1:启用)") + private Integer status; + + @Schema(description = "创建者") + private Long creator; + + @Schema(description = "创建时间") + private Date createdAt; + + @Schema(description = "更新者") + private Long updater; + + @Schema(description = "更新时间") + private Date updatedAt; + + @Schema(description = "文档数量") + private Integer documentCount; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeFilesDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeFilesDTO.java new file mode 100644 index 000000000..84774bddb --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/dto/KnowledgeFilesDTO.java @@ -0,0 +1,96 @@ +package xiaozhi.modules.knowledge.dto; + +import java.io.Serial; +import java.io.Serializable; +import java.util.Date; +import java.util.Map; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@Schema(description = "知识库文档") +public class KnowledgeFilesDTO implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + @Schema(description = "唯一标识") + private String id; + + @Schema(description = "文档ID") + private String documentId; + + @Schema(description = "知识库ID") + private String datasetId; + + @Schema(description = "文档名称") + private String name; + + @Schema(description = "文档类型") + private String fileType; + + @Schema(description = "文件大小(字节)") + private Long fileSize; + + @Schema(description = "文件路径") + private String filePath; + + @Schema(description = "元数据字段") + private Map metaFields; + + @Schema(description = "分块方法") + private String chunkMethod; + + @Schema(description = "解析器配置") + private Map parserConfig; + + @Schema(description = "状态") + private Integer status; + + @Schema(description = "文档解析状态") + private String run; + + @Schema(description = "创建者") + private Long creator; + + @Schema(description = "创建时间") + private Date createdAt; + + @Schema(description = "更新者") + private Long updater; + + @Schema(description = "更新时间") + private Date updatedAt; + + // 文档解析状态常量定义 + private static final Integer STATUS_UNSTART = 0; + private static final Integer STATUS_RUNNING = 1; + private static final Integer STATUS_CANCEL = 2; + private static final Integer STATUS_DONE = 3; + private static final Integer STATUS_FAIL = 4; + + /** + * 获取文档解析状态码(基于run字段转换) + */ + public Integer getParseStatusCode() { + if (run == null) { + return STATUS_UNSTART; + } + + // 根据run字段的值直接映射到对应的状态码 + switch (run.toUpperCase()) { + case "RUNNING": + return STATUS_RUNNING; + case "CANCEL": + return STATUS_CANCEL; + case "DONE": + return STATUS_DONE; + case "FAIL": + return STATUS_FAIL; + case "UNSTART": + default: + return STATUS_UNSTART; + } + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/entity/KnowledgeBaseEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/entity/KnowledgeBaseEntity.java new file mode 100644 index 000000000..e6c897eac --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/entity/KnowledgeBaseEntity.java @@ -0,0 +1,53 @@ +package xiaozhi.modules.knowledge.entity; + +import java.util.Date; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +@Data +@TableName(value = "ai_rag_dataset", autoResultMap = true) +@Schema(description = "知识库知识库表") +public class KnowledgeBaseEntity { + + @TableId(type = IdType.ASSIGN_UUID) + @Schema(description = "唯一标识") + private String id; + + @Schema(description = "知识库ID") + private String datasetId; + + @Schema(description = "RAG模型配置ID") + private String ragModelId; + + @Schema(description = "知识库名称") + private String name; + + @Schema(description = "知识库描述") + private String description; + + @Schema(description = "状态(0:禁用 1:启用)") + private Integer status; + + @Schema(description = "创建者") + @TableField(fill = FieldFill.INSERT) + private Long creator; + + @Schema(description = "创建时间") + @TableField(fill = FieldFill.INSERT) + private Date createdAt; + + @Schema(description = "更新者") + @TableField(fill = FieldFill.UPDATE) + private Long updater; + + @Schema(description = "更新时间") + @TableField(fill = FieldFill.UPDATE) + private Date updatedAt; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeBaseService.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeBaseService.java new file mode 100644 index 000000000..b875e87df --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeBaseService.java @@ -0,0 +1,87 @@ +package xiaozhi.modules.knowledge.service; + +import java.util.List; +import java.util.Map; + +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.BaseService; +import xiaozhi.modules.knowledge.dto.KnowledgeBaseDTO; +import xiaozhi.modules.knowledge.entity.KnowledgeBaseEntity; + +/** + * 知识库知识库服务接口 + */ +public interface KnowledgeBaseService extends BaseService { + + /** + * 分页查询知识库列表 + * + * @param knowledgeBaseDTO 查询条件 + * @param page 页码 + * @param limit 每页数量 + * @return 分页数据 + */ + PageData getPageList(KnowledgeBaseDTO knowledgeBaseDTO, Integer page, Integer limit); + + /** + * 根据ID获取知识库详情 + * + * @param id 知识库ID + * @return 知识库详情 + */ + KnowledgeBaseDTO getById(String id); + + /** + * 新增知识库 + * + * @param knowledgeBaseDTO 知识库信息 + * @return 新增的知识库 + */ + KnowledgeBaseDTO save(KnowledgeBaseDTO knowledgeBaseDTO); + + /** + * 更新知识库 + * + * @param knowledgeBaseDTO 知识库信息 + * @return 更新的知识库 + */ + KnowledgeBaseDTO update(KnowledgeBaseDTO knowledgeBaseDTO); + + /** + * 根据知识库ID查询知识库 + * + * @param datasetId 知识库ID + * @return 知识库详情 + */ + KnowledgeBaseDTO getByDatasetId(String datasetId); + + /** + * 根据知识库ID删除知识库 + * + * @param datasetId 知识库ID + */ + void deleteByDatasetId(String datasetId); + + /** + * 获取RAG配置信息 + * + * @param ragModelId RAG模型配置ID + * @return RAG配置信息 + */ + Map getRAGConfig(String ragModelId); + + /** + * 根据知识库ID获取对应的RAG配置 + * + * @param datasetId 知识库ID + * @return RAG配置 + */ + Map getRAGConfigByDatasetId(String datasetId); + + /** + * 获取RAG模型列表 + * + * @return RAG模型列表 + */ + List> getRAGModels(); +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeFilesService.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeFilesService.java new file mode 100644 index 000000000..fe9c16b23 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/KnowledgeFilesService.java @@ -0,0 +1,123 @@ +package xiaozhi.modules.knowledge.service; + +import java.util.List; +import java.util.Map; + +import org.springframework.web.multipart.MultipartFile; + +import xiaozhi.common.page.PageData; +import xiaozhi.modules.knowledge.dto.KnowledgeFilesDTO; + +/** + * 知识库文档服务接口 + */ +public interface KnowledgeFilesService { + + /** + * 分页查询文档列表 + * + * @param knowledgeFilesDTO 查询条件 + * @param page 页码 + * @param limit 每页数量 + * @return 分页数据 + */ + PageData getPageList(KnowledgeFilesDTO knowledgeFilesDTO, Integer page, Integer limit); + + /** + * 根据文档ID和知识库ID获取文档详情 + * + * @param documentId 文档ID + * @param datasetId 知识库ID + * @return 文档详情 + */ + KnowledgeFilesDTO getByDocumentId(String documentId, String datasetId); + + /** + * 上传文档到知识库 + * + * @param datasetId 知识库ID + * @param file 上传的文件 + * @param name 文档名称 + * @param metaFields 元数据字段 + * @param chunkMethod 分块方法 + * @param parserConfig 解析器配置 + * @return 上传的文档信息 + */ + KnowledgeFilesDTO uploadDocument(String datasetId, MultipartFile file, String name, + Map metaFields, String chunkMethod, + Map parserConfig); + + /** + * 根据状态分页查询文档列表 + * + * @param datasetId 知识库ID + * @param status 文档解析状态(0-未开始,1-进行中,2-已取消,3-已完成,4-失败) + * @param page 页码 + * @param limit 每页数量 + * @return 分页数据 + */ + PageData getPageListByStatus(String datasetId, Integer status, Integer page, Integer limit); + + /** + * 根据文档ID和知识库ID删除文档 + * + * @param documentId 文档ID + * @param datasetId 知识库ID + */ + void deleteByDocumentId(String documentId, String datasetId); + + /** + * 获取RAG配置信息 + * + * @param ragModelId RAG模型配置ID + * @return RAG配置信息 + */ + Map getRAGConfig(String ragModelId); + + /** + * 解析文档(切块) + * + * @param datasetId 知识库ID + * @param documentIds 文档ID列表 + * @return 解析结果 + */ + boolean parseDocuments(String datasetId, List documentIds); + + /** + * 列出指定文档的切片 + * + * @param datasetId 知识库ID + * @param documentId 文档ID + * @param keywords 关键词过滤 + * @param page 页码 + * @param pageSize 每页数量 + * @param chunkId 切片ID + * @return 切片列表信息 + */ + Map listChunks(String datasetId, String documentId, String keywords, + Integer page, Integer pageSize, String chunkId); + + /** + * 召回测试 - 从指定数据集或文档中检索相关切片 + * + * @param question 用户查询或查询关键词 + * @param datasetIds 数据集ID列表 + * @param documentIds 文档ID列表 + * @param page 页码 + * @param pageSize 每页数量 + * @param similarityThreshold 最小相似度阈值 + * @param vectorSimilarityWeight 向量相似度权重 + * @param topK 参与向量余弦计算的切片数量 + * @param rerankId 重排模型ID + * @param keyword 是否启用关键词匹配 + * @param highlight 是否启用高亮显示 + * @param crossLanguages 跨语言翻译列表 + * @param metadataCondition 元数据过滤条件 + * @return 召回测试结果 + */ + Map retrievalTest(String question, List datasetIds, List documentIds, + Integer page, Integer pageSize, Float similarityThreshold, + Float vectorSimilarityWeight, Integer topK, String rerankId, + Boolean keyword, Boolean highlight, List crossLanguages, + Map metadataCondition); +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeBaseServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeBaseServiceImpl.java new file mode 100644 index 000000000..c61df49ba --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeBaseServiceImpl.java @@ -0,0 +1,851 @@ +package xiaozhi.modules.knowledge.service.impl; + +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +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.common.redis.RedisKeys; +import xiaozhi.common.redis.RedisUtils; +import xiaozhi.common.service.impl.BaseServiceImpl; +import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.common.utils.MessageUtils; +import xiaozhi.modules.knowledge.dao.KnowledgeBaseDao; +import xiaozhi.modules.knowledge.dto.KnowledgeBaseDTO; +import xiaozhi.modules.knowledge.entity.KnowledgeBaseEntity; +import xiaozhi.modules.knowledge.service.KnowledgeBaseService; +import xiaozhi.modules.model.dao.ModelConfigDao; +import xiaozhi.modules.model.entity.ModelConfigEntity; +import xiaozhi.modules.model.service.ModelConfigService; +import xiaozhi.modules.security.user.SecurityUser; + +@Service +@AllArgsConstructor +@Slf4j +public class KnowledgeBaseServiceImpl extends BaseServiceImpl + implements KnowledgeBaseService { + + private final KnowledgeBaseDao knowledgeBaseDao; + private final ModelConfigService modelConfigService; + 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) { + if (datasetId == null) { + return null; + } + + // 先从Redis获取缓存 + String key = RedisKeys.getKnowledgeBaseCacheKey(datasetId.toString()); + KnowledgeBaseEntity cachedEntity = (KnowledgeBaseEntity) redisUtils.get(key); + if (cachedEntity != null) { + return cachedEntity; + } + + // 如果缓存中没有,则从数据库获取 + KnowledgeBaseEntity entity = knowledgeBaseDao.selectById(datasetId); + if (entity == null) { + return null; + } + + // 存入Redis缓存 + redisUtils.set(key, entity); + + return entity; + } + + @Override + public PageData getPageList(KnowledgeBaseDTO knowledgeBaseDTO, Integer page, Integer limit) { + long curPage = page; + long pageSize = limit; + Page pageInfo = new Page<>(curPage, pageSize); + + QueryWrapper queryWrapper = new QueryWrapper<>(); + + // 添加查询条件 + if (knowledgeBaseDTO != null) { + queryWrapper.like(StringUtils.isNotBlank(knowledgeBaseDTO.getName()), "name", knowledgeBaseDTO.getName()); + queryWrapper.eq(knowledgeBaseDTO.getStatus() != null, "status", knowledgeBaseDTO.getStatus()); + queryWrapper.eq("creator", knowledgeBaseDTO.getCreator()); + } + + // 添加排序规则:按创建时间降序 + queryWrapper.orderByDesc("created_at"); + + IPage knowledgeBaseEntityIPage = knowledgeBaseDao.selectPage(pageInfo, queryWrapper); + + // 获取分页数据 + PageData pageData = getPageData(knowledgeBaseEntityIPage, KnowledgeBaseDTO.class); + + // 为每个知识库获取文档数量 + if (pageData != null && pageData.getList() != null) { + for (KnowledgeBaseDTO knowledgeBase : pageData.getList()) { + try { + Integer documentCount = getDocumentCountFromRAGFlow(knowledgeBase.getDatasetId(), + knowledgeBase.getRagModelId()); + knowledgeBase.setDocumentCount(documentCount); + } catch (Exception e) { + // 构建详细的错误信息,包含异常类型和消息 + String baseErrorMessage = e.getClass().getSimpleName() + " - 获取知识库文档数量失败"; + String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : ""); + log.warn("知识库 {} {}", knowledgeBase.getDatasetId(), errorMessage); + knowledgeBase.setDocumentCount(0); // 设置默认值 + } + } + } + + return pageData; + } + + @Override + public KnowledgeBaseDTO getById(String id) { + if (StringUtils.isBlank(id)) { + throw new RenException(ErrorCode.IDENTIFIER_NOT_NULL); + } + + KnowledgeBaseEntity entity = knowledgeBaseDao.selectById(id); + if (entity == null) { + throw new RenException(ErrorCode.Knowledge_Base_RECORD_NOT_EXISTS); + } + + return ConvertUtils.sourceToTarget(entity, KnowledgeBaseDTO.class); + } + + @Override + public KnowledgeBaseDTO save(KnowledgeBaseDTO knowledgeBaseDTO) { + if (knowledgeBaseDTO == null) { + throw new RenException(ErrorCode.PARAMS_GET_ERROR); + } + + // 检查是否存在同名知识库 + checkDuplicateKnowledgeBaseName(knowledgeBaseDTO, null); + + String datasetId = null; + // 调用RAGFlow API创建数据集 + try { + Map ragConfig = getValidatedRAGConfig(knowledgeBaseDTO.getRagModelId()); + datasetId = createDatasetInRAGFlow( + knowledgeBaseDTO.getName(), + knowledgeBaseDTO.getDescription(), + ragConfig); + } catch (Exception e) { + // 如果RAG API调用失败,直接抛出异常 + throw e; + } + + // 验证数据集ID是否已存在 + KnowledgeBaseEntity existingEntity = knowledgeBaseDao.selectOne( + new QueryWrapper().eq("dataset_id", datasetId)); + if (existingEntity != null) { + // 如果datasetId已存在,删除RAGFlow中的数据集并抛出异常 + try { + Map ragConfig = getValidatedRAGConfig(knowledgeBaseDTO.getRagModelId()); + deleteDatasetInRAGFlow(datasetId, ragConfig); + } catch (Exception deleteException) { + // 提供更详细的错误信息,包括异常类型和消息 + 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); + } + + // 创建本地实体并保存 + KnowledgeBaseEntity entity = ConvertUtils.sourceToTarget(knowledgeBaseDTO, KnowledgeBaseEntity.class); + entity.setDatasetId(datasetId); + knowledgeBaseDao.insert(entity); + + return ConvertUtils.sourceToTarget(entity, KnowledgeBaseDTO.class); + } + + @Override + public KnowledgeBaseDTO update(KnowledgeBaseDTO knowledgeBaseDTO) { + if (knowledgeBaseDTO == null || StringUtils.isBlank(knowledgeBaseDTO.getId())) { + throw new RenException(ErrorCode.IDENTIFIER_NOT_NULL); + } + + // 检查记录是否存在 + KnowledgeBaseEntity existingEntity = knowledgeBaseDao.selectById(knowledgeBaseDTO.getId()); + if (existingEntity == null) { + throw new RenException(ErrorCode.Knowledge_Base_RECORD_NOT_EXISTS); + } + + // 检查是否存在同名知识库(排除当前记录) + checkDuplicateKnowledgeBaseName(knowledgeBaseDTO, knowledgeBaseDTO.getId()); + + // 验证数据集ID是否与其他记录冲突 + if (StringUtils.isNotBlank(knowledgeBaseDTO.getDatasetId())) { + KnowledgeBaseEntity conflictEntity = knowledgeBaseDao.selectOne( + new QueryWrapper() + .eq("dataset_id", knowledgeBaseDTO.getDatasetId()) + .ne("id", knowledgeBaseDTO.getId())); + if (conflictEntity != null) { + throw new RenException(ErrorCode.DB_RECORD_EXISTS); + } + } + + boolean needRagValidation = StringUtils.isNotBlank(knowledgeBaseDTO.getDatasetId()) + && StringUtils.isNotBlank(knowledgeBaseDTO.getRagModelId()); + + if (needRagValidation) { + try { + // 先校验RAG配置 + Map 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); + + // 删除缓存 + if (entity.getDatasetId() != null) { + redisUtils.delete(RedisKeys.getKnowledgeBaseCacheKey(entity.getId())); + } + + return ConvertUtils.sourceToTarget(entity, KnowledgeBaseDTO.class); + } + + @Override + public KnowledgeBaseDTO getByDatasetId(String datasetId) { + if (StringUtils.isBlank(datasetId)) { + throw new RenException(ErrorCode.PARAMS_GET_ERROR); + } + + KnowledgeBaseEntity entity = knowledgeBaseDao.selectOne( + new QueryWrapper().eq("dataset_id", datasetId)); + + if (entity == null) { + throw new RenException(ErrorCode.Knowledge_Base_RECORD_NOT_EXISTS); + } + + return ConvertUtils.sourceToTarget(entity, KnowledgeBaseDTO.class); + } + + @Override + public void deleteByDatasetId(String datasetId) { + if (StringUtils.isBlank(datasetId)) { + throw new RenException(ErrorCode.PARAMS_GET_ERROR); + } + + log.info("=== 开始通过datasetId删除操作 ==="); + log.info("删除datasetId: {}", datasetId); + + KnowledgeBaseEntity entity = knowledgeBaseDao.selectOne( + new QueryWrapper().eq("dataset_id", datasetId)); + + if (entity == null) { + log.warn("记录不存在,datasetId: {}", datasetId); + throw new RenException(ErrorCode.Knowledge_Base_RECORD_NOT_EXISTS); + } + redisUtils.delete(RedisKeys.getKnowledgeBaseCacheKey(entity.getId())); + + log.info("找到记录: ID={}, datasetId={}, ragModelId={}", + entity.getId(), entity.getDatasetId(), entity.getRagModelId()); + + // 先调用RAGFlow API删除数据集 + boolean apiDeleteSuccess = false; + if (StringUtils.isNotBlank(entity.getDatasetId()) && StringUtils.isNotBlank(entity.getRagModelId())) { + try { + log.info("开始调用RAGFlow API删除数据集"); + // 在删除前进行RAG配置校验 + Map ragConfig = getValidatedRAGConfig(entity.getRagModelId()); + deleteDatasetInRAGFlow(entity.getDatasetId(), ragConfig); + log.info("RAGFlow API删除调用完成"); + apiDeleteSuccess = true; + } 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删除"); + 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删除操作结束 ==="); + } + + @Override + public Map 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 config = modelConfig.getConfigJson(); + + // 验证必要的配置参数 + validateRagConfig(config); + + // 返回配置信息 + return config; + } + + @Override + public Map getRAGConfigByDatasetId(String datasetId) { + if (StringUtils.isBlank(datasetId)) { + throw new RenException(ErrorCode.PARAMS_GET_ERROR, "datasetId不能为空"); + } + + // 根据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, "知识库未配置RAG模型"); + } + + // 获取并返回RAG配置 + return getRAGConfig(ragModelId); + } + + @Override + public List> getRAGModels() { + // 查询RAG类型的模型配置 + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("model_type", Constant.RAG_CONFIG_TYPE) + .eq("is_enabled", 1) + .orderByDesc("is_default") + .orderByDesc("create_date"); + + List modelConfigs = modelConfigDao.selectList(queryWrapper); + + List> modelList = new ArrayList<>(); + for (ModelConfigEntity modelConfig : modelConfigs) { + Map modelInfo = new HashMap<>(); + modelInfo.put("id", modelConfig.getId()); + modelInfo.put("modelName", modelConfig.getModelName()); + modelList.add(modelInfo); + } + return modelList; + } + + /** + * 验证RAG配置中是否包含必要的参数 + */ + private void validateRagConfig(Map config) { + if (config == null) { + throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND, "RAG配置为空,请检查配置"); + } + + // 从配置中提取必要的参数 + String baseUrl = (String) config.get("base_url"); + String apiKey = (String) config.get("api_key"); + + // 验证base_url是否存在且非空 + if (StringUtils.isBlank(baseUrl)) { + 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); + } + } + + /** + * 调用RAGFlow API创建数据集 + */ + private String createDatasetInRAGFlow(String name, String description, Map ragConfig) { + String datasetId = null; + String baseUrl = (String) ragConfig.get("base_url"); + String apiKey = (String) ragConfig.get("api_key"); + + log.info("开始调用RAGFlow API创建数据集, name: {}", name); + log.debug("RAGFlow配置 - baseUrl: {}, apiKey: {}", baseUrl, StringUtils.isBlank(apiKey) ? "未配置" : "已配置"); + + // 构建请求URL + String url = baseUrl + "/api/v1/datasets"; + log.debug("请求URL: {}", url); + + // 构建请求体 + Map requestBody = new HashMap<>(); + String username = SecurityUser.getUser().getUsername(); + requestBody.put("name", username + "_" + name); + if (StringUtils.isNotBlank(description)) { + requestBody.put("description", description); + } + log.debug("请求体: {}", requestBody); + + // 设置请求头 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Authorization", "Bearer " + apiKey); + + HttpEntity> requestEntity = new HttpEntity<>(requestBody, headers); + + // 发送POST请求 + log.info("发送POST请求到RAGFlow API..."); + ResponseEntity 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()) { + String errorMessage = response.getStatusCode() + ", 响应内容: " + response.getBody(); + log.error(errorMessage); + throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage); + } + + // 解析响应体,提取datasetId + String responseBody = response.getBody(); + if (StringUtils.isNotBlank(responseBody)) { + try { + // 解析RAGFlow API响应,支持多种可能的字段名 + ObjectMapper objectMapper = new ObjectMapper(); + Map responseMap = objectMapper.readValue(responseBody, Map.class); + + log.debug("RAGFlow API响应解析结果: {}", responseMap); + + // 首先检查响应码 + Integer code = (Integer) responseMap.get("code"); + String message = (String) responseMap.get("message"); + if (code != null && code == 0) { + // 响应码为0表示成功,从data字段中获取datasetId + Object dataObj = responseMap.get("data"); + if (dataObj instanceof Map) { + Map dataMap = (Map) dataObj; + datasetId = (String) dataMap.get("id"); + + if (StringUtils.isBlank(datasetId)) { + // 如果id字段为空,尝试其他可能的字段名 + datasetId = (String) dataMap.get("dataset_id"); + datasetId = (String) dataMap.get("datasetId"); + } + } + } else { + // 如果响应码不为0,说明API调用失败 + String errorMessage = "RAGFlow API调用失败,响应码: " + code + ", 消息: " + + (message != null ? message : "未知错误"); + 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() + " - 解析RAGFlow API响应时发生IO异常"; + String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : ""); + log.error(errorMessage, e); + throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API响应解析失败: " + errorMessage); + } catch (Exception e) { + // 构建详细的错误信息,包含异常类型和消息 + String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应失败"; + 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"); + } + log.info("RAGFlow数据集创建成功,datasetId: {}", datasetId); + + return datasetId; + } + + /** + * 调用RAGFlow API更新数据集 + */ + private void updateDatasetInRAGFlow(String datasetId, String name, String description, + Map ragConfig) { + String baseUrl = (String) ragConfig.get("base_url"); + String apiKey = (String) ragConfig.get("api_key"); + + log.info("开始调用RAGFlow API更新数据集,datasetId: {}, name: {}", datasetId, name); + log.debug("RAGFlow配置 - baseUrl: {}, apiKey: {}", baseUrl, StringUtils.isBlank(apiKey) ? "未配置" : "已配置"); + + // 构建请求URL + String url = baseUrl + "/api/v1/datasets/" + datasetId; + log.debug("请求URL: {}", url); + // 构建请求体 + Map requestBody = new HashMap<>(); + requestBody.put("dataset_id", datasetId); + String username = SecurityUser.getUser().getUsername(); + requestBody.put("name", username + "_" + name); + if (StringUtils.isNotBlank(description)) { + requestBody.put("description", description); + } + log.debug("请求体: {}", requestBody); + + // 设置请求头 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Authorization", "Bearer " + apiKey); + + HttpEntity> requestEntity = new HttpEntity<>(requestBody, headers); + + // 发送PUT请求 + log.info("发送PUT请求到RAGFlow API..."); + ResponseEntity 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()) { + 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 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 = "RAGFlow API调用失败,响应码: " + code + ", 消息: " + + (message != null ? message : "未知错误"); + log.error(errorMessage); + throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage); + } + } catch (IOException e) { + // 构建详细的错误信息,包含异常类型和消息 + String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应时发生IO异常"; + String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : ""); + log.error(errorMessage, e); + throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API响应解析失败: " + errorMessage); + } catch (Exception e) { + // 构建详细的错误信息,包含异常类型和消息 + String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应失败"; + 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); + + } + + /** + * 调用RAGFlow API删除数据集 + */ + private void deleteDatasetInRAGFlow(String datasetId, Map ragConfig) { + String baseUrl = (String) ragConfig.get("base_url"); + String apiKey = (String) ragConfig.get("api_key"); + + log.info("开始调用RAGFlow API删除数据集,datasetId: {}", datasetId); + log.debug("RAGFlow配置 - baseUrl: {}, apiKey: {}", baseUrl, StringUtils.isBlank(apiKey) ? "未配置" : "已配置"); + + // 构建请求URL + String url = baseUrl + "/api/v1/datasets"; + log.debug("请求URL: {}", url); + + // 构建请求体 + Map requestBody = new HashMap<>(); + requestBody.put("ids", List.of(datasetId)); + log.debug("请求体: {}", requestBody); + + // 设置请求头 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Authorization", "Bearer " + apiKey); + + HttpEntity> requestEntity = new HttpEntity<>(requestBody, headers); + + // 发送DELETE请求 + log.info("发送DELETE请求到RAGFlow API..."); + ResponseEntity 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()) { + 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 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 = "RAGFlow API调用失败,响应码: " + code + ", 消息: " + + (message != null ? message : "未知错误"); + log.error(errorMessage); + throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage); + } + } catch (IOException e) { + // 构建详细的错误信息,包含异常类型和消息 + String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应时发生IO异常"; + String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : ""); + log.error(errorMessage, e); + throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API响应解析失败: " + errorMessage); + } catch (Exception e) { + // 构建详细的错误信息,包含异常类型和消息 + String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应失败"; + 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); + + } + + /** + * 获取RAG配置并验证 + */ + private Map getValidatedRAGConfig(String ragModelId) { + if (StringUtils.isBlank(ragModelId)) { + throw new RenException(ErrorCode.PARAMS_GET_ERROR, "ragModelId不能为空"); + } + + Map ragConfig = getRAGConfig(ragModelId); + + // 验证RAG配置参数 + validateRagConfig(ragConfig); + + return ragConfig; + } + + /** + * 检查是否存在同名知识库 + * + * @param knowledgeBaseDTO 知识库DTO + * @param excludeId 排除的ID(更新时使用) + */ + private void checkDuplicateKnowledgeBaseName(KnowledgeBaseDTO knowledgeBaseDTO, String excludeId) { + if (StringUtils.isNotBlank(knowledgeBaseDTO.getName())) { + Long currentUserId = SecurityUser.getUserId(); + QueryWrapper queryWrapper = new QueryWrapper() + .eq("name", knowledgeBaseDTO.getName()) + .eq("creator", currentUserId); + + // 如果提供了排除ID,则排除该记录 + if (StringUtils.isNotBlank(excludeId)) { + queryWrapper.ne("id", excludeId); + } + + long count = knowledgeBaseDao.selectCount(queryWrapper); + if (count > 0) { + throw new RenException(ErrorCode.KNOWLEDGE_BASE_NAME_EXISTS, + MessageUtils.getMessage(ErrorCode.KNOWLEDGE_BASE_NAME_EXISTS)); + } + } + } + + /** + * 从RAGFlow API获取知识库的文档数量 + */ + private Integer getDocumentCountFromRAGFlow(String datasetId, String ragModelId) { + if (StringUtils.isBlank(datasetId) || StringUtils.isBlank(ragModelId)) { + log.warn("datasetId或ragModelId为空,无法获取文档数量"); + return 0; + } + + log.info("开始获取知识库 {} 的文档数量", datasetId); + + // 获取RAG配置 + Map ragConfig = getValidatedRAGConfig(ragModelId); + String baseUrl = (String) ragConfig.get("base_url"); + String apiKey = (String) ragConfig.get("api_key"); + + // 构建请求URL - 调用RAGFlow API获取文档列表,但不返回文档详情,只获取总数 + String url = baseUrl + "/api/v1/datasets/" + datasetId + "/documents?page=1&size=1"; + log.debug("请求URL: {}", url); + + // 设置请求头 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Authorization", "Bearer " + apiKey); + + HttpEntity requestEntity = new HttpEntity<>(headers); + + // 发送GET请求 + log.info("发送GET请求到RAGFlow API获取文档数量..."); + ResponseEntity 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()); + + if (!response.getStatusCode().is2xxSuccessful()) { + log.error("RAGFlow API调用失败,状态码: {}, 响应内容: {}", response.getStatusCode(), response.getBody()); + return 0; + } + + String responseBody = response.getBody(); + log.debug("RAGFlow API响应内容: {}", responseBody); + + // 解析响应 + try { + ObjectMapper objectMapper = new ObjectMapper(); + Map responseMap = objectMapper.readValue(responseBody, Map.class); + Integer code = (Integer) responseMap.get("code"); + + if (code != null && code == 0) { + Object dataObj = responseMap.get("data"); + if (dataObj instanceof Map) { + Map dataMap = (Map) dataObj; + Object totalObj = dataMap.get("total"); + if (totalObj instanceof Integer) { + Integer documentCount = (Integer) totalObj; + log.info("获取知识库 {} 的文档数量成功: {}", datasetId, documentCount); + return documentCount; + } else if (totalObj instanceof Long) { + Long documentCount = (Long) totalObj; + log.info("获取知识库 {} 的文档数量成功: {}", datasetId, documentCount); + return documentCount.intValue(); + } + } + } 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) { + // 构建详细的错误信息,包含异常类型和消息 + String baseErrorMessage = e.getClass().getSimpleName() + " - 解析RAGFlow API响应失败"; + String errorMessage = baseErrorMessage + (e.getMessage() != null ? ": " + e.getMessage() : ""); + log.error(errorMessage, e); + } + return 0; + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeFilesServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeFilesServiceImpl.java new file mode 100644 index 000000000..edf6238e5 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/knowledge/service/impl/KnowledgeFilesServiceImpl.java @@ -0,0 +1,1686 @@ +package xiaozhi.modules.knowledge.service.impl; + +import java.io.IOException; +import java.io.InputStream; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; +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.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.RestTemplate; +import org.springframework.web.multipart.MultipartFile; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +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; + +@Service +@AllArgsConstructor +@Slf4j +public class KnowledgeFilesServiceImpl implements KnowledgeFilesService { + + private final KnowledgeBaseService knowledgeBaseService; + private RestTemplate restTemplate = new RestTemplate(); + private ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public Map getRAGConfig(String ragModelId) { + return knowledgeBaseService.getRAGConfig(ragModelId); + } + + @Override + public PageData getPageList(KnowledgeFilesDTO knowledgeFilesDTO, Integer page, Integer limit) { + try { + + log.info("=== 开始获取文档列表 ==="); + log.info("查询条件: datasetId={}, name={}, status={}, page={}, limit={}", + knowledgeFilesDTO != null ? knowledgeFilesDTO.getDatasetId() : null, + knowledgeFilesDTO != null ? knowledgeFilesDTO.getName() : null, + knowledgeFilesDTO != null ? knowledgeFilesDTO.getStatus() : null, + page, limit); + + // 构建请求URL - 根据RAGFlow API文档,获取文档列表的接口 + String datasetId = knowledgeFilesDTO != null ? knowledgeFilesDTO.getDatasetId() : null; + if (StringUtils.isBlank(datasetId)) { + throw new RenException(ErrorCode.PARAMS_GET_ERROR, "datasetId不能为空"); + } + + // 获取RAG配置 + Map 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"; + + // 添加查询参数 + StringBuilder urlBuilder = new StringBuilder(url); + List params = new ArrayList<>(); + + if (knowledgeFilesDTO != null && StringUtils.isNotBlank(knowledgeFilesDTO.getName())) { + params.add("keywords=" + knowledgeFilesDTO.getName()); + } + if (page > 0) { + params.add("page=" + page); + } + if (limit > 0) { + params.add("page_size=" + limit); + } + + if (!params.isEmpty()) { + urlBuilder.append("?").append(String.join("&", params)); + } + + url = urlBuilder.toString(); + log.debug("请求URL: {}", url); + + // 设置请求头 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Authorization", "Bearer " + apiKey); + + HttpEntity requestEntity = new HttpEntity<>(headers); + + // 发送GET请求 + log.info("发送GET请求到RAGFlow API获取文档列表..."); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class); + + log.info("RAGFlow API响应状态码: {}", response.getStatusCode()); + + if (!response.getStatusCode().is2xxSuccessful()) { + log.error("RAGFlow API调用失败,状态码: {}", response.getStatusCode()); + throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API调用失败,HTTP状态码: " + response.getStatusCode()); + } + + String responseBody = response.getBody(); + log.debug("RAGFlow API响应内容: {}", responseBody); + + // 解析响应 + Map responseMap = objectMapper.readValue(responseBody, Map.class); + Integer code = (Integer) responseMap.get("code"); + + if (code != null && code == 0) { + Object dataObj = responseMap.get("data"); + return parseDocumentListResponse(dataObj, page, limit); + } else { + 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 (Exception e) { + log.error("获取文档列表失败: {}", e.getMessage(), e); + String errorMessage = e.getMessage() != null ? e.getMessage() : "未知错误"; + if (e instanceof RenException) { + throw (RenException) e; + } + + throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage); + } finally { + log.info("=== 获取文档列表操作结束 ==="); + } + } + + /** + * 解析RAGFlow API返回的文档列表响应 + */ + private PageData parseDocumentListResponse(Object dataObj, long curPage, long pageSize) { + try { + List documents = new ArrayList<>(); + long totalCount = 0; + + if (dataObj instanceof Map) { + Map dataMap = (Map) dataObj; + + // 获取文档列表 - 支持多种可能的字段名 + Object documentsObj = null; + + // 支持多种可能的文档列表字段名 + String[] possibleDocumentFields = { "docs", "documents", "items", "list", "data" }; + + for (String fieldName : possibleDocumentFields) { + if (dataMap.containsKey(fieldName) && dataMap.get(fieldName) instanceof List) { + documentsObj = dataMap.get(fieldName); + log.debug("使用字段名'{}'获取文档列表", fieldName); + break; + } + } + + // 如果标准字段不存在,尝试自动检测 + if (documentsObj == null) { + for (Map.Entry entry : dataMap.entrySet()) { + if (entry.getValue() instanceof List) { + List list = (List) entry.getValue(); + if (!list.isEmpty() && list.get(0) instanceof Map) { + documentsObj = entry.getValue(); + log.warn("自动检测到文档列表字段: '{}',建议检查RAGFlow API文档", entry.getKey()); + break; + } + } + } + } + + if (documentsObj instanceof List) { + List> documentList = (List>) documentsObj; + + for (Map docMap : documentList) { + KnowledgeFilesDTO dto = convertRAGDocumentToDTO(docMap); + if (dto != null) { + // 在文档列表获取时也进行状态同步检查 + syncDocumentStatusWithRAGFlow(dto); + documents.add(dto); + } + } + } + + // 解析总数 - 支持多种可能的字段名 + Object totalObj = null; + String[] possibleTotalFields = { "total", "totalCount", "total_count", "count" }; + + for (String fieldName : possibleTotalFields) { + if (dataMap.containsKey(fieldName)) { + totalObj = dataMap.get(fieldName); + log.debug("使用字段名'{}'获取总数", fieldName); + break; + } + } + + if (totalObj instanceof Integer) { + totalCount = ((Integer) totalObj).longValue(); + } else if (totalObj instanceof Long) { + totalCount = (Long) totalObj; + } else if (totalObj instanceof String) { + try { + totalCount = Long.parseLong((String) totalObj); + } catch (NumberFormatException e) { + log.warn("无法解析总数字段: {}", totalObj); + } + } + } + + // 创建分页数据 + PageData pageData = new PageData<>(documents, totalCount); + + log.info("获取文档列表成功,共{}个文档,总数: {}", documents.size(), totalCount); + return pageData; + + } catch (Exception e) { + log.error("获取文档列表响应失败: {}", e.getMessage(), e); + throw new RenException(ErrorCode.RAG_API_ERROR, "获取文档列表响应失败: " + e.getMessage()); + } + } + + /** + * 同步文档状态与RAGFlow实际状态 + * 优化状态同步逻辑,确保解析中状态能够正常显示 + * 只有当文档有切片且解析时间超过30秒时,才更新为完成状态 + */ + private void syncDocumentStatusWithRAGFlow(KnowledgeFilesDTO dto) { + if (dto == null || StringUtils.isBlank(dto.getDocumentId())) { + return; + } + + String documentId = dto.getDocumentId(); + Integer currentStatus = dto.getStatus(); + + // 只有当状态明确为处理中(1)时,才进行状态同步检查 + // 避免在状态不确定或已完成的文档上重复检查 + if (currentStatus != null && currentStatus == 1) { + try { + long currentTime = System.currentTimeMillis(); + + // 调用RAGFlow API获取文档切片信息 + String datasetId = dto.getDatasetId(); + Map ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); + String baseUrl = (String) ragConfig.get("base_url"); + String apiKey = (String) ragConfig.get("api_key"); + + String url = baseUrl + "/api/v1/documents/" + documentId + "/chunks"; + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Authorization", "Bearer " + apiKey); + + HttpEntity requestEntity = new HttpEntity<>(headers); + + log.debug("检查文档切片状态,documentId: {}", documentId); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, + String.class); + + if (response.getStatusCode().is2xxSuccessful()) { + String responseBody = response.getBody(); + Map responseMap = objectMapper.readValue(responseBody, Map.class); + + Integer code = (Integer) responseMap.get("code"); + if (code != null && code == 0) { + Object dataObj = responseMap.get("data"); + if (dataObj instanceof Map) { + Map dataMap = (Map) dataObj; + + // 检查是否有切片数据 + Object chunksObj = getValueFromMultipleKeys(dataMap, "chunks", "items", "list", "data"); + if (chunksObj instanceof List) { + List chunks = (List) chunksObj; + + // 如果有切片且数量大于0,说明解析已完成 + if (!chunks.isEmpty()) { + // 检查文档创建时间,确保解析过程有足够的时间显示 + Date createdAt = dto.getCreatedAt(); + long parseDuration = currentTime + - (createdAt != null ? createdAt.getTime() : currentTime); + + // 只有当解析时间超过30秒时,才更新为完成状态 + // 这样可以确保解析中状态有足够的时间显示 + if (parseDuration > 30000) { + log.info("状态同步:文档已有切片且解析时间超过30秒,更新为完成状态,documentId: {}, 切片数量: {}, 解析时长: {}ms", + documentId, chunks.size(), parseDuration); + + // 更新状态为完成(3) + dto.setStatus(3); + } else { + log.debug("文档已有切片但解析时间不足30秒,保持解析中状态,documentId: {}, 解析时长: {}ms", + documentId, parseDuration); + } + } + } + } + } + } + } catch (Exception e) { + log.debug("检查文档切片状态失败,documentId: {}, 错误: {}", documentId, e.getMessage()); + // 忽略检查失败,保持原状态 + } + } + } + + /** + * 将RAGFlow文档数据转换为KnowledgeFilesDTO + */ + private KnowledgeFilesDTO convertRAGDocumentToDTO(Map docMap) { + try { + if (docMap == null) + return null; + + KnowledgeFilesDTO dto = new KnowledgeFilesDTO(); + + // 设置基本字段 - 支持多种可能的字段名 + dto.setId(getStringValueFromMultipleKeys(docMap, "id", "document_id", "doc_id")); // 使用RAGFlow的文档ID作为本地ID + dto.setDocumentId(getStringValueFromMultipleKeys(docMap, "id", "document_id", "doc_id")); // RAGFlow文档ID + dto.setName(getStringValueFromMultipleKeys(docMap, "name", "filename", "file_name", "title")); + dto.setDatasetId(getStringValueFromMultipleKeys(docMap, "dataset_id", "dataset", "knowledge_base_id")); + + // 设置文件信息 - 支持多种可能的字段名 + dto.setFileType(getStringValueFromMultipleKeys(docMap, "file_type", "type", "format", "extension")); + + // 文件大小 - 支持多种可能的字段名 + Object sizeObj = getValueFromMultipleKeys(docMap, "size", "file_size", "size_bytes"); + if (sizeObj instanceof Integer) { + dto.setFileSize(((Integer) sizeObj).longValue()); + } else if (sizeObj instanceof Long) { + dto.setFileSize((Long) sizeObj); + } else if (sizeObj instanceof String) { + try { + dto.setFileSize(Long.parseLong((String) sizeObj)); + } catch (NumberFormatException e) { + log.warn("无法解析文件大小: {}", sizeObj); + } + } + + // 设置元数据和配置 - 支持多种可能的字段名 + Object metaFieldsObj = getValueFromMultipleKeys(docMap, "meta_fields", "metadata", "meta", "properties"); + if (metaFieldsObj instanceof Map) { + dto.setMetaFields((Map) metaFieldsObj); + } + + Object parserConfigObj = getValueFromMultipleKeys(docMap, "parser_config", "parser", "parse_config", + "config"); + if (parserConfigObj instanceof Map) { + dto.setParserConfig((Map) parserConfigObj); + } + + dto.setChunkMethod(getStringValueFromMultipleKeys(docMap, "chunk_method", "chunking", "chunk_strategy")); + + // 设置时间信息 - 支持多种可能的字段名 + Object createTimeObj = getValueFromMultipleKeys(docMap, "create_time", "created_at", "creation_time", + "created"); + if (createTimeObj instanceof Long) { + dto.setCreatedAt(new Date((Long) createTimeObj)); + } else if (createTimeObj instanceof String) { + // 尝试解析时间字符串 + try { + // 这里可以根据实际的时间格式进行调整 + dto.setCreatedAt(new Date(Long.parseLong((String) createTimeObj))); + } catch (NumberFormatException e) { + log.warn("无法解析创建时间: {}", createTimeObj); + } + } + + Object updateTimeObj = getValueFromMultipleKeys(docMap, "update_time", "updated_at", "modified_time", + "modified"); + if (updateTimeObj instanceof Long) { + dto.setUpdatedAt(new Date((Long) updateTimeObj)); + } else if (updateTimeObj instanceof String) { + try { + dto.setUpdatedAt(new Date(Long.parseLong((String) updateTimeObj))); + } catch (NumberFormatException e) { + log.warn("无法解析更新时间: {}", updateTimeObj); + } + } + + // 设置文档解析状态信息 - 直接使用RAGFlow最新状态 + String documentId = dto.getDocumentId(); + if (StringUtils.isNotBlank(documentId)) { + // 获取RAGFlow的最新状态 + Object runObj = getValueFromMultipleKeys(docMap, "run", "status", "parse_status"); + Integer ragFlowStatus = null; + if (runObj != null) { + dto.setRun(runObj.toString()); + ragFlowStatus = dto.getParseStatusCode(); + log.debug("获取RAGFlow最新状态,documentId: {}, run: {}, status: {}", + documentId, runObj, ragFlowStatus); + } + + } + + return dto; + + } catch (Exception e) { + log.error("转换RAGFlow文档数据失败: {}", e.getMessage(), e); + return null; + } + } + + /** + * 从多个可能的字段名中获取字符串值 + */ + private String getStringValueFromMultipleKeys(Map map, String... keys) { + for (String key : keys) { + Object value = map.get(key); + if (value != null) { + return value.toString(); + } + } + return null; + } + + /** + * 从多个可能的字段名中获取值 + */ + private Object getValueFromMultipleKeys(Map map, String... keys) { + for (String key : keys) { + Object value = map.get(key); + if (value != null) { + return value; + } + } + return null; + } + + @Override + public KnowledgeFilesDTO getByDocumentId(String documentId, String datasetId) { + if (StringUtils.isBlank(documentId) || StringUtils.isBlank(datasetId)) { + throw new RenException(ErrorCode.PARAMS_GET_ERROR, "documentId和datasetId不能为空"); + } + + log.info("=== 开始根据documentId获取文档 ==="); + log.info("documentId: {}, datasetId: {}", documentId, datasetId); + + try { + // 获取RAG配置 + Map ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); + String baseUrl = (String) ragConfig.get("base_url"); + String apiKey = (String) ragConfig.get("api_key"); + + // 修正API路径 - 根据RAGFlow API规范,获取单个文档需要datasetId + String url = baseUrl + "/api/v1/datasets/" + datasetId + "/documents/" + documentId; + log.debug("请求URL: {}", url); + + // 设置请求头 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Authorization", "Bearer " + apiKey); + + HttpEntity requestEntity = new HttpEntity<>(headers); + + // 发送GET请求 + log.info("发送GET请求到RAGFlow API获取文档详情..."); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class); + + log.info("RAGFlow API响应状态码: {}", response.getStatusCode()); + + if (!response.getStatusCode().is2xxSuccessful()) { + log.error("RAGFlow API调用失败,状态码: {}", response.getStatusCode()); + String responseBody = response.getBody(); + throw new RenException(ErrorCode.RAG_API_ERROR, + "RAGFlow API调用失败,HTTP状态码: " + response.getStatusCode() + + ", 响应内容: " + (responseBody != null ? responseBody : "无响应内容")); + } + + String responseBody = response.getBody(); + log.debug("RAGFlow API响应内容: {}", responseBody); + + // 解析响应 + Map responseMap = objectMapper.readValue(responseBody, Map.class); + Integer code = (Integer) responseMap.get("code"); + + if (code != null && code == 0) { + Object dataObj = responseMap.get("data"); + if (dataObj instanceof Map) { + KnowledgeFilesDTO dto = convertRAGDocumentToDTO((Map) dataObj); + if (dto != null) { + log.info("获取文档详情成功,documentId: {}", documentId); + return dto; + } + } + throw new RenException(ErrorCode.Knowledge_Base_RECORD_NOT_EXISTS); + } else { + 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 (Exception e) { + log.error("根据documentId获取文档失败: {}", e.getMessage(), e); + String errorMessage = e.getMessage() != null ? e.getMessage() : "未知错误"; + if (e instanceof RenException) { + throw (RenException) e; + } + throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage); + } finally { + log.info("=== 根据documentId获取文档操作结束 ==="); + } + } + + @Override + public PageData getPageListByStatus(String datasetId, Integer status, Integer page, + Integer limit) { + if (StringUtils.isBlank(datasetId)) { + throw new RenException(ErrorCode.PARAMS_GET_ERROR, "datasetId不能为空"); + } + + log.info("=== 开始根据状态查询文档列表 ==="); + log.info("datasetId: {}, status: {}, page: {}, limit: {}", datasetId, status, page, limit); + + try { + // 获取RAG配置 + Map ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); + String baseUrl = (String) ragConfig.get("base_url"); + String apiKey = (String) ragConfig.get("api_key"); + + // 构建请求URL - 获取文档列表 + StringBuilder urlBuilder = new StringBuilder(); + urlBuilder.append(baseUrl).append("/api/v1/datasets/").append(datasetId).append("/documents"); + + // 构建查询参数 + List params = new ArrayList<>(); + if (page != null && page > 0) { + params.add("page=" + page); + } + if (limit != null && limit > 0) { + params.add("page_size=" + limit); + } + + if (!params.isEmpty()) { + urlBuilder.append("?").append(String.join("&", params)); + } + + String url = urlBuilder.toString(); + log.debug("请求URL: {}", url); + + // 设置请求头 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Authorization", "Bearer " + apiKey); + + HttpEntity requestEntity = new HttpEntity<>(headers); + + // 发送GET请求 + log.info("发送GET请求到RAGFlow API获取文档列表..."); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class); + + log.info("RAGFlow API响应状态码: {}", response.getStatusCode()); + + if (!response.getStatusCode().is2xxSuccessful()) { + log.error("RAGFlow API调用失败,状态码: {}", response.getStatusCode()); + throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API调用失败,HTTP状态码: " + response.getStatusCode()); + } + + String responseBody = response.getBody(); + log.debug("RAGFlow API响应内容: {}", responseBody); + + // 解析响应 + Map responseMap = objectMapper.readValue(responseBody, Map.class); + Integer code = (Integer) responseMap.get("code"); + + if (code != null && code == 0) { + Object dataObj = responseMap.get("data"); + + // 解析文档列表并过滤状态 + PageData pageData = parseDocumentListResponse(dataObj, page, limit); + + if (status != null) { + // 根据状态过滤文档列表 + List filteredDocuments = pageData.getList().stream() + .filter(doc -> status.equals(doc.getStatus())) + .collect(Collectors.toList()); + + // 更新分页数据 + pageData.setList(filteredDocuments); + pageData.setTotal(filteredDocuments.size()); + } + + log.info("根据状态查询文档列表成功,datasetId: {}, 状态: {}, 文档数量: {}", + datasetId, status, pageData.getList().size()); + return pageData; + } else { + log.error("RAGFlow API调用失败,响应码: {}", code); + throw new RenException(ErrorCode.RAG_API_ERROR, "RAGFlow API调用失败,响应码: " + code); + } + + } catch (Exception e) { + log.error("根据状态查询文档列表失败: {}", e.getMessage(), e); + throw new RenException(ErrorCode.RAG_API_ERROR, "查询文档列表失败: " + e.getMessage()); + } finally { + log.info("=== 根据状态查询文档列表操作结束 ==="); + } + } + + @Override + public KnowledgeFilesDTO uploadDocument(String datasetId, MultipartFile file, String name, + Map metaFields, String chunkMethod, + Map parserConfig) { + if (StringUtils.isBlank(datasetId) || file == null || file.isEmpty()) { + throw new RenException(ErrorCode.PARAMS_GET_ERROR); + } + + log.info("=== 开始文档上传操作 ==="); + log.info("上传文档到数据集: {}, 文件名: {}", datasetId, file.getOriginalFilename()); + + try { + // 在文件上传前添加详细日志 + log.info("1. 开始处理文件信息"); + String fileName = file.getOriginalFilename(); + String fileType = getFileType(fileName); + long fileSize = file.getSize(); + + log.info("文件信息 - 文件名: {}, 文件类型: {}, 文件大小: {} bytes", + fileName, fileType, fileSize); + + // 检查文件基本信息 + if (StringUtils.isBlank(fileName)) { + log.error("文件名为空"); + throw new RenException(ErrorCode.PARAMS_GET_ERROR, "文件名不能为空"); + } + + if (fileSize == 0) { + log.error("文件大小为0"); + throw new RenException(ErrorCode.PARAMS_GET_ERROR, "文件内容为空"); + } + + log.info("2. 开始流式上传到RAGFlow"); + // 直接调用RAGFlow API上传文档 - 使用流式上传 + String documentId = uploadDocumentToRAGFlow(datasetId, file, name, metaFields, chunkMethod, parserConfig); + + log.info("文档上传成功,documentId: {}", documentId); + + // 返回上传的文档信息 + KnowledgeFilesDTO result = new KnowledgeFilesDTO(); + result.setId(documentId); // 使用documentId作为ID + result.setDocumentId(documentId); + result.setDatasetId(datasetId); + result.setName(StringUtils.isNotBlank(name) ? name : fileName); + result.setFileType(fileType); + result.setFileSize(fileSize); + result.setStatus(1); // 上传成功,设置为处理中状态 + + return result; + + } catch (Exception e) { + log.error("文档上传失败: {}", e.getMessage()); + log.error("文档上传失败详细异常: ", e); + if (e instanceof RenException) { + throw (RenException) e; + } + throw new RenException(ErrorCode.INTERNAL_SERVER_ERROR); + } finally { + log.info("=== 文档上传操作结束 ==="); + } + } + + @Override + public void deleteByDocumentId(String documentId, String datasetId) { + if (StringUtils.isBlank(documentId) || StringUtils.isBlank(datasetId)) { + throw new RenException(ErrorCode.PARAMS_GET_ERROR, "documentId和datasetId不能为空"); + } + + log.info("=== 开始根据documentId删除文档 ==="); + log.info("删除文档documentId: {}, datasetId: {}", documentId, datasetId); + + try { + // 直接调用RAGFlow API删除文档,不进行前置验证 + // 因为即使文档不存在,RAGFlow API也会返回相应的错误信息 + log.info("开始调用RAGFlow API删除文档"); + deleteDocumentInRAGFlow(documentId, datasetId); + log.info("RAGFlow API删除调用完成"); + + } catch (Exception e) { + log.error("删除文档失败: {}", e.getMessage(), e); + String errorMessage = e.getMessage() != null ? e.getMessage() : "未知错误"; + if (e instanceof RenException) { + throw (RenException) e; + } + throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage); + } finally { + log.info("=== 根据documentId删除文档操作结束 ==="); + } + } + + /** + * 获取文件类型 - 支持RAGFlow四种文档格式类型 + */ + private String getFileType(String fileName) { + if (StringUtils.isBlank(fileName)) { + log.warn("文件名为空,返回unknown类型"); + return "unknown"; + } + + try { + int lastDotIndex = fileName.lastIndexOf('.'); + if (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1) { + String extension = fileName.substring(lastDotIndex + 1).toLowerCase(); + + // 文档格式类型 + String[] documentTypes = { "pdf", "doc", "docx", "txt", "md", "mdx" }; + String[] spreadsheetTypes = { "csv", "xls", "xlsx" }; + String[] presentationTypes = { "ppt", "pptx" }; + + // 检查文档类型 + for (String type : documentTypes) { + if (type.equals(extension)) { + return "document"; + } + } + + // 检查表格类型 + for (String type : spreadsheetTypes) { + if (type.equals(extension)) { + return "spreadsheet"; + } + } + // 检查幻灯片类型 + for (String type : presentationTypes) { + if (type.equals(extension)) { + return "presentation"; + } + } + // 返回原始扩展名作为文件类型 + return extension; + } + return "unknown"; + } catch (Exception e) { + log.error("获取文件类型失败: ", e); + return "unknown"; + } + } + + /** + * 验证RAG配置中是否包含必要的参数 + */ + private void validateRagConfig(Map config) { + if (config == null) { + throw new RenException(ErrorCode.RAG_CONFIG_NOT_FOUND); + } + + // 从配置中提取必要的参数 + String baseUrl = (String) config.get("base_url"); + String apiKey = (String) config.get("api_key"); + + // 验证base_url是否存在且非空 + if (StringUtils.isBlank(baseUrl)) { + throw new RenException(ErrorCode.RAG_API_ERROR, "RAG配置缺少必要参数: base_url"); + } + } + + /** + * 调用RAGFlow API上传文档 - 流式上传版本 + */ + private String uploadDocumentToRAGFlow(String datasetId, MultipartFile file, String name, + Map metaFields, String chunkMethod, + Map parserConfig) { + try { + // 获取RAG配置 + Map ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); + String baseUrl = (String) ragConfig.get("base_url"); + String apiKey = (String) ragConfig.get("api_key"); + + log.info("开始调用RAGFlow API流式上传文档,datasetId: {}, 文件名: {}", datasetId, file.getOriginalFilename()); + log.debug("RAGFlow配置 - baseUrl: {}, apiKey: {}", baseUrl, StringUtils.isBlank(apiKey) ? "未配置" : "已配置"); + + // 构建请求URL + String url = baseUrl + "/api/v1/datasets/" + datasetId + "/documents"; + log.debug("请求URL: {}", url); + + // 构建multipart/form-data请求 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + headers.set("Authorization", "Bearer " + apiKey); + + // 创建多部分请求体 - 使用MultipartFileResource进行流式上传 + MultiValueMap body = new LinkedMultiValueMap<>(); + body.add("file", new MultipartFileResource(file, file.getOriginalFilename())); + + // 添加其他参数 + if (StringUtils.isNotBlank(name)) { + body.add("name", name); + } else { + body.add("name", file.getOriginalFilename()); + } + + if (metaFields != null && !metaFields.isEmpty()) { + try { + body.add("meta_fields", objectMapper.writeValueAsString(metaFields)); + } catch (Exception e) { + log.warn("序列化meta_fields失败: {}", e.getMessage()); + } + } + + if (StringUtils.isNotBlank(chunkMethod)) { + body.add("chunk_method", chunkMethod); + } + + if (parserConfig != null && !parserConfig.isEmpty()) { + try { + body.add("parser_config", objectMapper.writeValueAsString(parserConfig)); + } catch (Exception e) { + log.warn("序列化parser_config失败: {}", e.getMessage()); + } + } + + log.debug("multipart请求体参数数量: {}", body.size()); + log.debug("multipart请求体参数: {}", body.keySet()); + + HttpEntity> requestEntity = new HttpEntity<>(body, headers); + + // 发送POST请求 + log.info("发送multipart/form-data POST请求到RAGFlow API..."); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class); + + log.info("RAGFlow API响应状态码: {}", response.getStatusCode()); + log.debug("RAGFlow API响应内容: {}", response.getBody()); + + String responseBody = response.getBody(); + String documentId = null; + + if (response.getStatusCode().is2xxSuccessful()) { + try { + Map responseMap = objectMapper.readValue(responseBody, Map.class); + + log.debug("RAGFlow API响应解析结果: {}", responseMap); + + // 首先检查响应码 + Integer code = (Integer) responseMap.get("code"); + if (code != null && code == 0) { + // 响应码为0表示成功,从data字段中获取documentId + Object dataObj = responseMap.get("data"); + + // 增强的documentId提取逻辑 + documentId = extractDocumentIdFromResponse(dataObj); + + // 如果从data字段无法提取,尝试从根级别提取 + if (StringUtils.isBlank(documentId)) { + documentId = extractDocumentIdFromRoot(responseMap); + } + + log.info("文档上传成功,documentId: {}", documentId); + } else { + // 如果响应码不为0,说明API调用失败 + 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()); + throw new RenException(ErrorCode.RAG_API_ERROR, responseBody); + } + } else { + log.error("RAGFlow API调用失败,状态码: {}", response.getStatusCode()); + throw new RenException(ErrorCode.RAG_API_ERROR, + "RAGFlow API调用失败,HTTP状态码: " + response.getStatusCode() + + ", 响应内容: " + (responseBody != null ? responseBody : "无响应内容")); + } + + if (StringUtils.isBlank(documentId)) { + log.error("无法从RAGFlow API响应中获取documentId"); + throw new RenException(ErrorCode.RAG_API_ERROR, responseBody); + } + log.info("RAGFlow文档上传成功,documentId: {},文档已开始自动解析切片", documentId); + return documentId; + + } catch (Exception e) { + log.error("RAGFlow API调用失败: {}", e.getMessage(), e); + String errorMessage = e.getMessage() != null ? e.getMessage() : "未知错误"; + if (e instanceof RenException) { + throw (RenException) e; + } + throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage); + } + } + + /** + * 从响应数据中提取documentId + */ + private String extractDocumentIdFromResponse(Object dataObj) { + String documentId = null; + + if (dataObj instanceof List) { + // data是一个数组,取第一个元素的id字段 + List> dataList = (List>) dataObj; + if (!dataList.isEmpty()) { + Map firstItem = dataList.get(0); + documentId = extractDocumentIdFromMap(firstItem); + } + } else if (dataObj instanceof Map) { + // data是一个对象 + Map dataMap = (Map) dataObj; + documentId = extractDocumentIdFromMap(dataMap); + } + + return documentId; + } + + /** + * 从Map中提取documentId,支持多种可能的字段名 + */ + private String extractDocumentIdFromMap(Map map) { + if (map == null) + return null; + + // 尝试多种可能的字段名 + String[] possibleFieldNames = { "id", "document_id", "documentId", "doc_id", "documentId" }; + + for (String fieldName : possibleFieldNames) { + Object value = map.get(fieldName); + if (value != null && value instanceof String && StringUtils.isNotBlank((String) value)) { + return (String) value; + } + } + + return null; + } + + /** + * 从根级别响应中提取documentId + */ + private String extractDocumentIdFromRoot(Map responseMap) { + if (responseMap == null) + return null; + + // 尝试从根级别提取 + String[] possibleFieldNames = { "id", "document_id", "documentId", "doc_id", "documentId" }; + + for (String fieldName : possibleFieldNames) { + Object value = responseMap.get(fieldName); + if (value != null && value instanceof String && StringUtils.isNotBlank((String) value)) { + return (String) value; + } + } + + return null; + } + + /** + * 调用RAGFlow API删除文档 + */ + private void deleteDocumentInRAGFlow(String documentId, String datasetId) { + try { + // 获取RAG配置 + Map ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); + String baseUrl = (String) ragConfig.get("base_url"); + String apiKey = (String) ragConfig.get("api_key"); + + log.info("开始调用RAGFlow API删除文档,documentId: {}, datasetId: {}", documentId, datasetId); + log.debug("RAGFlow配置 - baseUrl: {}, apiKey: {}", baseUrl, StringUtils.isBlank(apiKey) ? "未配置" : "已配置"); + + // 构建请求URL - 根据RAGFlow API文档,使用正确的路径参数名称 + String url = baseUrl + "/api/v1/datasets/" + datasetId + "/documents"; + log.debug("请求URL: {}", url); + + // 构建请求体 - 严格按照API文档格式 + Map requestBody = new HashMap<>(); + requestBody.put("ids", Arrays.asList(documentId)); // 使用Arrays.asList确保序列化正确 + log.debug("请求体: {}", requestBody); + + // 设置请求头 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Authorization", "Bearer " + apiKey); + + HttpEntity> requestEntity = new HttpEntity<>(requestBody, headers); + + // 发送DELETE请求 + log.info("发送DELETE请求到RAGFlow API..."); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, + String.class); + + log.info("RAGFlow API响应状态码: {}", response.getStatusCode()); + log.debug("RAGFlow API响应内容: {}", response.getBody()); + + String responseBody = response.getBody(); + + if (response.getStatusCode().is2xxSuccessful()) { + // 验证响应格式 + if (responseBody != null) { + try { + Map responseMap = objectMapper.readValue(responseBody, Map.class); + Integer code = (Integer) responseMap.get("code"); + + if (code != null && code == 0) { + log.info("RAGFlow文档删除成功,documentId: {}", documentId); + return; + } else { + String message = (String) responseMap.get("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()); + log.info("RAGFlow文档删除成功,documentId: {}", documentId); + return; + } + } else { + log.info("RAGFlow文档删除成功(无响应体),documentId: {}", documentId); + return; + } + } else { + log.error("RAGFlow API调用失败,状态码: {}", response.getStatusCode()); + throw new RenException(ErrorCode.RAG_API_ERROR, + "RAGFlow API调用失败,HTTP状态码: " + response.getStatusCode() + + ", 响应内容: " + (responseBody != null ? responseBody : "无响应内容")); + } + + } catch (Exception e) { + log.error("RAGFlow API调用失败: {}", e.getMessage(), e); + String errorMessage = e.getMessage() != null ? e.getMessage() : "未知错误"; + if (e instanceof RenException) { + throw (RenException) e; + } + throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage); + } + } + + /** + * 辅助类:将MultipartFile转换为Resource用于流式上传 + */ + private static class MultipartFileResource extends AbstractResource { + private final MultipartFile multipartFile; + private final String filename; + + public MultipartFileResource(MultipartFile multipartFile, String filename) { + this.multipartFile = multipartFile; + this.filename = filename; + } + + @Override + public String getFilename() { + return this.filename; + } + + @Override + public InputStream getInputStream() throws IOException { + return this.multipartFile.getInputStream(); + } + + @Override + public long contentLength() throws IOException { + return this.multipartFile.getSize(); + } + + @Override + public boolean exists() { + return true; + } + + @Override + public String getDescription() { + return "MultipartFile resource for " + this.filename; + } + } + + @Override + public boolean parseDocuments(String datasetId, List documentIds) { + if (StringUtils.isBlank(datasetId) || documentIds == null || documentIds.isEmpty()) { + throw new RenException(ErrorCode.PARAMS_GET_ERROR, "datasetId和documentIds不能为空"); + } + + log.info("=== 开始解析文档(切块) ==="); + log.info("datasetId: {}, documentIds: {}", datasetId, documentIds); + + try { + // 获取RAG配置 + Map ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); + String baseUrl = (String) ragConfig.get("base_url"); + String apiKey = (String) ragConfig.get("api_key"); + + // 构建请求URL - 根据RAGFlow API文档,解析文档的接口 + String url = baseUrl + "/api/v1/datasets/" + datasetId + "/chunks"; + log.debug("请求URL: {}", url); + + // 构建请求体 + Map requestBody = new HashMap<>(); + requestBody.put("document_ids", documentIds); + log.debug("请求体: {}", requestBody); + + // 设置请求头 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Authorization", "Bearer " + apiKey); + + HttpEntity> requestEntity = new HttpEntity<>(requestBody, headers); + + // 发送POST请求 + log.info("发送POST请求到RAGFlow API解析文档..."); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class); + + log.info("RAGFlow API响应状态码: {}", response.getStatusCode()); + + 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, + "RAGFlow API调用失败,HTTP状态码: " + response.getStatusCode() + ", 响应内容: " + errorDetail); + } + + // 解析响应 + Map responseMap = objectMapper.readValue(responseBody, Map.class); + Integer code = (Integer) responseMap.get("code"); + + if (code != null && code == 0) { + log.info("文档解析成功,datasetId: {}, documentIds: {}", datasetId, documentIds); + return true; + } else { + // 获取错误消息,如果存在的话 + String message = (String) responseMap.get("message"); + String errorDetail = message != null ? message : "无详细错误信息"; + log.error("RAGFlow API调用失败,响应码: {}, 错误信息: {}", code, errorDetail); + throw new RenException(ErrorCode.RAG_API_ERROR, responseBody); + } + + } catch (Exception e) { + log.error("解析文档失败: {}", e.getMessage(), e); + String errorMessage = e.getMessage() != null ? e.getMessage() : "未知错误"; + if (e instanceof RenException) { + throw (RenException) e; + } + throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage); + } finally { + log.info("=== 解析文档操作结束 ==="); + } + } + + @Override + public Map 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不能为空"); + } + + log.info("=== 开始列出切片 ==="); + log.info("datasetId: {}, documentId: {}, keywords: {}, page: {}, pageSize: {}, chunkId: {}", + datasetId, documentId, keywords, page, pageSize, chunkId); + + try { + // 获取RAG配置 + Map ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetId); + String baseUrl = (String) ragConfig.get("base_url"); + String apiKey = (String) ragConfig.get("api_key"); + + // 构建请求URL - 根据RAGFlow API文档,列出切片的接口 + StringBuilder urlBuilder = new StringBuilder(); + urlBuilder.append(baseUrl).append("/api/v1/datasets/").append(datasetId) + .append("/documents/").append(documentId).append("/chunks"); + + // 添加查询参数 + List params = new ArrayList<>(); + + if (StringUtils.isNotBlank(keywords)) { + params.add("keywords=" + keywords); + } + + if (page != null && page > 0) { + params.add("page=" + page); + } + + if (pageSize != null && pageSize > 0) { + params.add("page_size=" + pageSize); + } + + if (StringUtils.isNotBlank(chunkId)) { + params.add("id=" + chunkId); + } + + if (!params.isEmpty()) { + urlBuilder.append("?").append(String.join("&", params)); + } + + String url = urlBuilder.toString(); + log.debug("请求URL: {}", url); + + // 设置请求头 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Authorization", "Bearer " + apiKey); + + HttpEntity requestEntity = new HttpEntity<>(headers); + + // 发送GET请求 + log.info("发送GET请求到RAGFlow API列出切片..."); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class); + + log.info("RAGFlow API响应状态码: {}", response.getStatusCode()); + + 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, + "RAGFlow API调用失败,HTTP状态码: " + response.getStatusCode() + ", 响应内容: " + errorDetail); + } + + // 解析响应 + Map responseMap = objectMapper.readValue(responseBody, Map.class); + Integer code = (Integer) responseMap.get("code"); + + if (code != null && code == 0) { + log.info("切片列表获取成功,datasetId: {}, documentId: {}", datasetId, documentId); + + // 解析切片数据并格式化返回 + return parseChunkListResponse(responseMap); + } else { + // 获取错误消息,如果存在的话 + String message = (String) responseMap.get("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); + String errorMessage = e.getMessage() != null ? e.getMessage() : "未知错误"; + throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage); + } catch (Exception e) { + log.error("列出切片失败: {}", e.getMessage(), e); + String errorMessage = e.getMessage() != null ? e.getMessage() : "未知错误"; + if (e instanceof RenException) { + throw (RenException) e; + } + throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage); + } finally { + log.info("=== 列出切片操作结束 ==="); + } + } + + /** + * 解析RAGFlow API返回的切片列表响应 + */ + private Map parseChunkListResponse(Map responseMap) { + Map result = new HashMap<>(); + List> chunkList = new ArrayList<>(); + long totalCount = 0; + + try { + // 首先检查是否有data字段 + Object dataObj = responseMap.get("data"); + if (dataObj instanceof Map) { + Map dataMap = (Map) dataObj; + + // 解析切片列表 - 支持多种可能的字段名 + Object chunksObj = null; + + // 支持多种可能的切片列表字段名 + String[] possibleChunkFields = { "chunks", "items", "list", "data", "docs" }; + + for (String fieldName : possibleChunkFields) { + if (dataMap.containsKey(fieldName) && dataMap.get(fieldName) instanceof List) { + chunksObj = dataMap.get(fieldName); + log.debug("使用字段名'{}'获取切片列表", fieldName); + break; + } + } + + // 如果标准字段不存在,尝试自动检测 + if (chunksObj == null) { + for (Map.Entry entry : dataMap.entrySet()) { + if (entry.getValue() instanceof List) { + List list = (List) entry.getValue(); + if (!list.isEmpty() && list.get(0) instanceof Map) { + chunksObj = entry.getValue(); + log.warn("自动检测到切片列表字段: '{}',建议检查RAGFlow API文档", entry.getKey()); + break; + } + } + } + } + + if (chunksObj instanceof List) { + List> rawChunkList = (List>) chunksObj; + + for (Map chunkMap : rawChunkList) { + Map formattedChunk = formatChunkData(chunkMap); + if (formattedChunk != null) { + chunkList.add(formattedChunk); + } + } + } + + // 解析总数 - 支持多种可能的字段名 + Object totalObj = null; + String[] possibleTotalFields = { "total", "totalCount", "total_count", "count" }; + + for (String fieldName : possibleTotalFields) { + if (dataMap.containsKey(fieldName)) { + totalObj = dataMap.get(fieldName); + log.debug("使用字段名'{}'获取总数", fieldName); + break; + } + } + + if (totalObj instanceof Integer) { + totalCount = ((Integer) totalObj).longValue(); + } else if (totalObj instanceof Long) { + totalCount = (Long) totalObj; + } else if (totalObj instanceof String) { + try { + totalCount = Long.parseLong((String) totalObj); + } catch (NumberFormatException e) { + log.warn("无法解析总数字段: {}", totalObj); + } + } + + // 如果没有找到总数,使用切片列表的大小 + if (totalCount == 0 && !chunkList.isEmpty()) { + totalCount = chunkList.size(); + } + } else { + log.warn("RAGFlow API响应缺少data字段,尝试直接解析响应"); + + // 如果没有data字段,尝试直接解析响应 + Object chunksObj = null; + String[] possibleChunkFields = { "chunks", "items", "list", "data", "docs" }; + + for (String fieldName : possibleChunkFields) { + if (responseMap.containsKey(fieldName) && responseMap.get(fieldName) instanceof List) { + chunksObj = responseMap.get(fieldName); + log.debug("使用字段名'{}'获取切片列表", fieldName); + break; + } + } + + if (chunksObj instanceof List) { + List> rawChunkList = (List>) chunksObj; + + for (Map chunkMap : rawChunkList) { + Map formattedChunk = formatChunkData(chunkMap); + if (formattedChunk != null) { + chunkList.add(formattedChunk); + } + } + } + + // 解析总数 + Object totalObj = responseMap.get("total"); + if (totalObj instanceof Integer) { + totalCount = ((Integer) totalObj).longValue(); + } else if (totalObj instanceof Long) { + totalCount = (Long) totalObj; + } + + if (totalCount == 0 && !chunkList.isEmpty()) { + totalCount = chunkList.size(); + } + } + + } catch (Exception e) { + log.error("解析切片列表响应失败: {}", e.getMessage(), e); + } + + result.put("list", chunkList); + result.put("total", totalCount); + + log.debug("解析后的切片列表: {} 条记录", chunkList.size()); + return result; + } + + /** + * 格式化切片数据 + */ + private Map formatChunkData(Map chunkMap) { + if (chunkMap == null || chunkMap.isEmpty()) { + return null; + } + + Map formattedChunk = new HashMap<>(); + + try { + // 提取切片ID - 支持多种可能的字段名 + String chunkId = extractChunkId(chunkMap); + if (StringUtils.isBlank(chunkId)) { + log.warn("切片数据缺少ID字段,跳过处理: {}", chunkMap); + return null; + } + formattedChunk.put("id", chunkId); + + // 提取切片内容 - 支持多种可能的字段名 + String content = extractChunkContent(chunkMap); + formattedChunk.put("content", content != null ? content : ""); + + // 提取重要关键词 - 支持多种可能的字段名 + List importantKeywords = extractImportantKeywords(chunkMap); + formattedChunk.put("important_keywords", importantKeywords); + + // 提取问题列表 - 支持多种可能的字段名 + List questions = extractQuestions(chunkMap); + formattedChunk.put("questions", questions); + + // 提取创建时间 - 支持多种可能的字段名 + String createTime = extractCreateTime(chunkMap); + formattedChunk.put("create_time", createTime != null ? createTime : ""); + + } catch (Exception e) { + log.error("格式化切片数据失败: {}", e.getMessage(), e); + return null; + } + + return formattedChunk; + } + + /** + * 提取切片ID + */ + private String extractChunkId(Map chunkMap) { + String[] possibleIdFields = { "id", "chunk_id", "chunkId", "chunkId" }; + + for (String fieldName : possibleIdFields) { + Object value = chunkMap.get(fieldName); + if (value != null && value instanceof String && StringUtils.isNotBlank((String) value)) { + return (String) value; + } + } + + return null; + } + + /** + * 提取切片内容 + */ + private String extractChunkContent(Map chunkMap) { + String[] possibleContentFields = { "content", "text", "chunk_content", "chunkContent" }; + + for (String fieldName : possibleContentFields) { + Object value = chunkMap.get(fieldName); + if (value != null && value instanceof String && StringUtils.isNotBlank((String) value)) { + return (String) value; + } + } + + return null; + } + + /** + * 提取重要关键词 + */ + private List extractImportantKeywords(Map chunkMap) { + String[] possibleKeywordFields = { "important_keywords", "keywords", "importantKeywords", "key_words" }; + + for (String fieldName : possibleKeywordFields) { + Object value = chunkMap.get(fieldName); + if (value instanceof List) { + List list = (List) value; + List keywords = new ArrayList<>(); + for (Object item : list) { + if (item instanceof String && StringUtils.isNotBlank((String) item)) { + keywords.add((String) item); + } + } + return keywords; + } else if (value instanceof String && StringUtils.isNotBlank((String) value)) { + // 如果是逗号分隔的字符串,分割成列表 + String[] parts = ((String) value).split(","); + List keywords = new ArrayList<>(); + for (String part : parts) { + String trimmed = part.trim(); + if (StringUtils.isNotBlank(trimmed)) { + keywords.add(trimmed); + } + } + return keywords; + } + } + + return new ArrayList<>(); + } + + /** + * 提取问题列表 + */ + private List extractQuestions(Map chunkMap) { + String[] possibleQuestionFields = { "questions", "question_list", "questionList", "qas" }; + + for (String fieldName : possibleQuestionFields) { + Object value = chunkMap.get(fieldName); + if (value instanceof List) { + List list = (List) value; + List questions = new ArrayList<>(); + for (Object item : list) { + if (item instanceof String && StringUtils.isNotBlank((String) item)) { + questions.add((String) item); + } + } + return questions; + } else if (value instanceof String && StringUtils.isNotBlank((String) value)) { + // 如果是逗号分隔的字符串,分割成列表 + String[] parts = ((String) value).split(","); + List questions = new ArrayList<>(); + for (String part : parts) { + String trimmed = part.trim(); + if (StringUtils.isNotBlank(trimmed)) { + questions.add(trimmed); + } + } + return questions; + } + } + + return new ArrayList<>(); + } + + /** + * 提取创建时间 + */ + private String extractCreateTime(Map chunkMap) { + String[] possibleTimeFields = { "create_time", "created_at", "createTime", "timestamp" }; + + for (String fieldName : possibleTimeFields) { + Object value = chunkMap.get(fieldName); + if (value != null) { + if (value instanceof String && StringUtils.isNotBlank((String) value)) { + return (String) value; + } else if (value instanceof Long) { + // 如果是时间戳,转换为字符串 + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date((Long) value)); + } + } + } + + return null; + } + + @Override + public Map retrievalTest(String question, List datasetIds, List documentIds, + Integer page, Integer pageSize, Float similarityThreshold, + Float vectorSimilarityWeight, Integer topK, String rerankId, + Boolean keyword, Boolean highlight, List crossLanguages, + Map metadataCondition) { + + log.info("=== 开始召回测试 ==="); + log.info("问题: {}, 数据集ID: {}, 文档ID: {}, 页码: {}, 每页数量: {}", + question, datasetIds, documentIds, page, pageSize); + + try { + // 获取RAG配置 + Map ragConfig = knowledgeBaseService.getRAGConfigByDatasetId(datasetIds.get(0)); + String baseUrl = (String) ragConfig.get("base_url"); + String apiKey = (String) ragConfig.get("api_key"); + + // 构建请求URL + String url = baseUrl + "/api/v1/retrieval"; + log.debug("请求URL: {}", url); + + // 构建请求体 + Map requestBody = new HashMap<>(); + requestBody.put("question", question); + + if (datasetIds != null && !datasetIds.isEmpty()) { + requestBody.put("dataset_ids", datasetIds); + } + + if (documentIds != null && !documentIds.isEmpty()) { + requestBody.put("document_ids", documentIds); + } + + if (page != null && page > 0) { + requestBody.put("page", page); + } + + if (pageSize != null && pageSize > 0) { + requestBody.put("page_size", pageSize); + } + + if (similarityThreshold != null) { + requestBody.put("similarity_threshold", similarityThreshold); + } + + if (vectorSimilarityWeight != null) { + requestBody.put("vector_similarity_weight", vectorSimilarityWeight); + } + + if (topK != null && topK > 0) { + requestBody.put("top_k", topK); + } + + if (rerankId != null) { + requestBody.put("rerank_id", rerankId); + } + + if (keyword != null) { + requestBody.put("keyword", keyword); + } + + if (highlight != null) { + requestBody.put("highlight", highlight); + } + + if (crossLanguages != null && !crossLanguages.isEmpty()) { + requestBody.put("cross_languages", crossLanguages); + } + + if (metadataCondition != null) { + requestBody.put("metadata_condition", metadataCondition); + } + + log.debug("请求体: {}", requestBody); + + // 设置请求头 + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.set("Authorization", "Bearer " + apiKey); + + HttpEntity> requestEntity = new HttpEntity<>(requestBody, headers); + + // 发送POST请求 + log.info("发送POST请求到RAGFlow API进行召回测试..."); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class); + + log.info("RAGFlow API响应状态码: {}", response.getStatusCode()); + + 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, + "RAGFlow API调用失败,HTTP状态码: " + response.getStatusCode() + ", 响应内容: " + errorDetail); + } + + // 解析响应 + Map responseMap = objectMapper.readValue(responseBody, Map.class); + Integer code = (Integer) responseMap.get("code"); + + if (code != null && code == 0) { + Object dataObj = responseMap.get("data"); + if (dataObj instanceof Map) { + Map result = (Map) dataObj; + log.info("召回测试成功,返回 {} 条切片", result.get("total")); + return result; + } else { + log.error("RAGFlow API响应格式错误,data字段不是Map类型"); + throw new RenException(ErrorCode.RAG_API_ERROR, responseBody); + } + } else { + // 获取错误消息,如果存在的话 + String message = (String) responseMap.get("message"); + String errorDetail = message != null ? message : "无详细错误信息"; + log.error("RAGFlow API调用失败,响应码: {}, 错误信息: {}", code, errorDetail); + throw new RenException(ErrorCode.RAG_API_ERROR, responseBody); + } + + } catch (Exception e) { + log.error("召回测试失败: {}", e.getMessage(), e); + String errorMessage = e.getMessage() != null ? e.getMessage() : "未知错误"; + if (e instanceof RenException) { + throw (RenException) e; + } + throw new RenException(ErrorCode.RAG_API_ERROR, errorMessage); + } finally { + log.info("=== 召回测试操作结束 ==="); + } + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java index 32a5c0cc6..d4984530c 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java @@ -21,7 +21,12 @@ import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.Result; import xiaozhi.modules.agent.service.AgentTemplateService; import xiaozhi.modules.config.service.ConfigService; -import xiaozhi.modules.model.dto.*; +import xiaozhi.modules.model.dto.LlmModelBasicInfoDTO; +import xiaozhi.modules.model.dto.ModelBasicInfoDTO; +import xiaozhi.modules.model.dto.ModelConfigBodyDTO; +import xiaozhi.modules.model.dto.ModelConfigDTO; +import xiaozhi.modules.model.dto.ModelProviderDTO; +import xiaozhi.modules.model.dto.VoiceDTO; import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; import xiaozhi.modules.model.service.ModelProviderService; @@ -124,6 +129,8 @@ public class ModelController { if (entity == null) { return new Result().error("模型配置不存在"); } + // 不更新ConfigJson字段 + entity.setConfigJson(null); entity.setIsEnabled(status); modelConfigService.updateById(entity); return new Result(); @@ -141,6 +148,8 @@ public class ModelController { modelConfigService.setDefaultModel(entity.getModelType(), 0); entity.setIsEnabled(1); entity.setIsDefault(1); + // 不更新ConfigJson字段 + entity.setConfigJson(null); modelConfigService.updateById(entity); // 更新模板表中对应的模型ID diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigBodyDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigBodyDTO.java index 07758def1..eb1197b14 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigBodyDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/dto/ModelConfigBodyDTO.java @@ -13,9 +13,9 @@ public class ModelConfigBodyDTO { @Serial private static final long serialVersionUID = 1L; - // @Schema(description = "模型类型(Memory/ASR/VAD/LLM/TTS)") - // private String modelType; - // + @Schema(description = "模型ID,未填写将自动生成") + private String id; + @Schema(description = "模型编码(如AliLLM、DoubaoTTS)") private String modelCode; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelConfigEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelConfigEntity.java index 32ff911fb..aba2c8f2e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelConfigEntity.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/entity/ModelConfigEntity.java @@ -3,9 +3,7 @@ package xiaozhi.modules.model.entity; import java.util.Date; import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler; @@ -18,7 +16,6 @@ import lombok.Data; @Schema(description = "模型配置表") public class ModelConfigEntity { - @TableId(type = IdType.ASSIGN_UUID) @Schema(description = "主键") private String id; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java index d17948a6d..fbfc77232 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/service/impl/ModelConfigServiceImpl.java @@ -11,6 +11,7 @@ import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.OrderItem; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; @@ -252,6 +253,12 @@ public class ModelConfigServiceImpl extends BaseServiceImpl getPluginList() { + // 1. 获取插件列表 LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(ModelProviderEntity::getModelType, "Plugin"); List providerEntities = modelProviderDao.selectList(queryWrapper); - return ConvertUtils.sourceToTarget(providerEntities, ModelProviderDTO.class); + List resultList = ConvertUtils.sourceToTarget(providerEntities, ModelProviderDTO.class); + + // 2. 获取当前用户的知识库列表并追加到结果中 + UserDetail userDetail = SecurityUser.getUser(); + if (userDetail != null && userDetail.getId() != null) { + // 查询当前用户的知识库 + LambdaQueryWrapper kbQueryWrapper = new LambdaQueryWrapper<>(); + kbQueryWrapper.eq(KnowledgeBaseEntity::getCreator, userDetail.getId()); + kbQueryWrapper.eq(KnowledgeBaseEntity::getStatus, 1); // 只获取启用状态的知识库 + List knowledgeBases = knowledgeBaseDao.selectList(kbQueryWrapper); + + // 将知识库转换为ModelProviderDTO格式并添加到结果列表 + for (KnowledgeBaseEntity kb : knowledgeBases) { + ModelProviderDTO dto = new ModelProviderDTO(); + dto.setId(kb.getId()); + dto.setModelType("Rag"); + dto.setName("[知识库]" + kb.getName()); + dto.setProviderCode("ragflow"); // 假设所有RAG都使用ragflow + dto.setFields("[]"); + dto.setSort(0); + dto.setCreateDate(kb.getCreatedAt()); + dto.setUpdateDate(kb.getUpdatedAt()); + dto.setCreator(0L); + dto.setUpdater(0L); + resultList.add(dto); + } + } + + return resultList; } @Override diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java index eebd55be0..d8025b3c2 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/TimbreService.java @@ -64,4 +64,13 @@ public interface TimbreService extends BaseService { * @return 音色名称 */ String getTimbreNameById(String id); + + /** + * 根据音色编码获取音色信息 + * + * @param ttsModelId 音色模型ID + * @param voiceCode 音色编码 + * @return 音色信息 + */ + VoiceDTO getByVoiceCode(String ttsModelId, String voiceCode); } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java index 2ed5b1ab0..8ebb21552 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/service/impl/TimbreServiceImpl.java @@ -1,9 +1,11 @@ package xiaozhi.modules.timbre.service.impl; +import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; @@ -15,18 +17,23 @@ import com.baomidou.mybatisplus.core.metadata.IPage; import cn.hutool.core.collection.CollectionUtil; import lombok.AllArgsConstructor; import xiaozhi.common.constant.Constant; +import xiaozhi.common.exception.ErrorCode; import xiaozhi.common.page.PageData; import xiaozhi.common.redis.RedisKeys; import xiaozhi.common.redis.RedisUtils; import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.common.utils.MessageUtils; import xiaozhi.modules.model.dto.VoiceDTO; +import xiaozhi.modules.security.user.SecurityUser; import xiaozhi.modules.timbre.dao.TimbreDao; import xiaozhi.modules.timbre.dto.TimbreDataDTO; import xiaozhi.modules.timbre.dto.TimbrePageDTO; import xiaozhi.modules.timbre.entity.TimbreEntity; import xiaozhi.modules.timbre.service.TimbreService; import xiaozhi.modules.timbre.vo.TimbreDetailsVO; +import xiaozhi.modules.voiceclone.dao.VoiceCloneDao; +import xiaozhi.modules.voiceclone.entity.VoiceCloneEntity; /** * 音色的业务层的实现 @@ -39,6 +46,7 @@ import xiaozhi.modules.timbre.vo.TimbreDetailsVO; public class TimbreServiceImpl extends BaseServiceImpl implements TimbreService { private final TimbreDao timbreDao; + private final VoiceCloneDao voiceCloneDao; private final RedisUtils redisUtils; @Override @@ -121,11 +129,30 @@ public class TimbreServiceImpl extends BaseServiceImpl queryWrapper.like("name", voiceName); } List timbreEntities = timbreDao.selectList(queryWrapper); - if (CollectionUtil.isEmpty(timbreEntities)) { - return null; + if (timbreEntities == null) { + timbreEntities = new ArrayList<>(); + } + List voiceDTOs = timbreEntities.stream() + .map(entity -> new VoiceDTO(entity.getId(), entity.getName())) + .collect(Collectors.toList()); + + // 获取当前登录用户ID + Long currentUserId = SecurityUser.getUser().getId(); + if (currentUserId != null) { + // 查询用户的所有克隆音色记录 + List cloneEntities = voiceCloneDao.getTrainSuccess(ttsModelId, currentUserId); + for (VoiceDTO entity : cloneEntities) { + // 只添加训练成功的克隆音色,且模型ID匹配 + VoiceDTO voiceDTO = new VoiceDTO(); + voiceDTO.setId(entity.getId()); + voiceDTO.setName(MessageUtils.getMessage(ErrorCode.VOICE_CLONE_PREFIX) + entity.getName()); + redisUtils.set(RedisKeys.getTimbreNameById(voiceDTO.getId()), voiceDTO.getName(), + RedisUtils.NOT_EXPIRE); + voiceDTOs.add(0, voiceDTO); + } } - return ConvertUtils.sourceToTarget(timbreEntities, VoiceDTO.class); + return CollectionUtil.isEmpty(voiceDTOs) ? null : voiceDTOs; } /** @@ -154,8 +181,30 @@ public class TimbreServiceImpl extends BaseServiceImpl redisUtils.set(RedisKeys.getTimbreNameById(id), name); } return name; + } else { + VoiceCloneEntity cloneEntity = voiceCloneDao.selectById(id); + if (cloneEntity != null) { + String name = MessageUtils.getMessage(ErrorCode.VOICE_CLONE_PREFIX) + cloneEntity.getName(); + redisUtils.set(RedisKeys.getTimbreNameById(id), name); + return name; + } } return null; } + + @Override + public VoiceDTO getByVoiceCode(String ttsModelId, String voiceCode) { + if (StringUtils.isBlank(voiceCode)) { + return null; + } + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("tts_model_id", ttsModelId); + queryWrapper.eq("tts_voice", voiceCode); + List list = timbreDao.selectList(queryWrapper); + if (list.isEmpty()) { + return null; + } + return new VoiceDTO(list.get(0).getId(), list.get(0).getName()); + } } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceCloneController.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceCloneController.java index 5e166b659..b7de9332c 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceCloneController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceCloneController.java @@ -116,6 +116,7 @@ public class VoiceCloneController { checkPermission(id); voiceCloneService.updateName(id, name); + redisUtils.delete(RedisKeys.getTimbreNameById(id)); return new Result(); } catch (Exception e) { return new Result().error(ErrorCode.UPDATE_DATA_FAILED, "更新失败: " + e.getMessage()); @@ -175,6 +176,8 @@ public class VoiceCloneController { public Result cloneAudio(@RequestBody Map params) { String cloneId = params.get("cloneId"); checkPermission(cloneId); + // 调用服务层进行语音克隆训练 + voiceCloneService.cloneAudio(cloneId); return new Result(); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceResourceController.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceResourceController.java index eff10c18d..a4cfa4798 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceResourceController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/controller/VoiceResourceController.java @@ -80,6 +80,8 @@ public class VoiceResourceController { try { voiceCloneService.save(dto); return new Result(); + } catch (xiaozhi.common.exception.RenException e) { + return new Result().error(e.getCode(), e.getMsg()); } catch (RuntimeException e) { return new Result().error(ErrorCode.ADD_DATA_FAILED, e.getMessage()); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dao/VoiceCloneDao.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dao/VoiceCloneDao.java index f866c46f4..08e0e0129 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dao/VoiceCloneDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/dao/VoiceCloneDao.java @@ -1,9 +1,12 @@ package xiaozhi.modules.voiceclone.dao; +import java.util.List; + import org.apache.ibatis.annotations.Mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import xiaozhi.modules.model.dto.VoiceDTO; import xiaozhi.modules.voiceclone.entity.VoiceCloneEntity; /** @@ -11,5 +14,13 @@ import xiaozhi.modules.voiceclone.entity.VoiceCloneEntity; */ @Mapper public interface VoiceCloneDao extends BaseMapper { + /** + * 获取用户训练成功的音色列表 + * + * @param modelId 模型ID + * @param userId 用户ID + * @return 训练成功的音色列表 + */ + List getTrainSuccess(String modelId, Long userId); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/VoiceCloneService.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/VoiceCloneService.java index bdfd5ed0d..ea8fd61d8 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/VoiceCloneService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/VoiceCloneService.java @@ -33,19 +33,22 @@ public interface VoiceCloneService extends BaseService { /** * 根据用户ID查询声音克隆列表 + * + * @param userId 用户ID + * @return 声音克隆列表 */ List getByUserId(Long userId); - + /** * 分页查询带模型名称和用户名称的声音克隆列表 */ PageData pageWithNames(Map params); - + /** * 根据ID查询带模型名称和用户名称的声音克隆信息 */ VoiceCloneResponseDTO getByIdWithNames(String id); - + /** * 根据用户ID查询带模型名称的声音克隆列表 */ @@ -65,4 +68,11 @@ public interface VoiceCloneService extends BaseService { * 获取音频数据 */ byte[] getVoiceData(String id); + + /** + * 克隆音频,调用火山引擎进行语音复刻训练 + * + * @param cloneId 语音克隆记录ID + */ + void cloneAudio(String cloneId); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/impl/VoiceCloneServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/impl/VoiceCloneServiceImpl.java index 32b3c88f1..bc13d2aa1 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/impl/VoiceCloneServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/voiceclone/service/impl/VoiceCloneServiceImpl.java @@ -1,7 +1,13 @@ package xiaozhi.modules.voiceclone.service.impl; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; import java.util.ArrayList; import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -12,14 +18,19 @@ import org.springframework.web.multipart.MultipartFile; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import xiaozhi.common.constant.Constant; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; import xiaozhi.common.page.PageData; import xiaozhi.common.service.impl.BaseServiceImpl; import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.DateUtils; -import xiaozhi.common.exception.ErrorCode; -import xiaozhi.common.exception.RenException; +import xiaozhi.modules.model.entity.ModelConfigEntity; import xiaozhi.modules.model.service.ModelConfigService; import xiaozhi.modules.sys.service.SysUserService; import xiaozhi.modules.voiceclone.dao.VoiceCloneDao; @@ -28,6 +39,7 @@ import xiaozhi.modules.voiceclone.dto.VoiceCloneResponseDTO; import xiaozhi.modules.voiceclone.entity.VoiceCloneEntity; import xiaozhi.modules.voiceclone.service.VoiceCloneService; +@Slf4j @Service @RequiredArgsConstructor public class VoiceCloneServiceImpl extends BaseServiceImpl @@ -35,6 +47,7 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl page(Map params) { @@ -61,6 +74,36 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl config = modelConfig.getConfigJson(); + String type = (String) config.get("type"); + if (StringUtils.isBlank(type)) { + throw new RenException(ErrorCode.VOICE_CLONE_MODEL_TYPE_NOT_FOUND); + } + + // 检查Voice ID是否已经被使用 + for (String voiceId : dto.getVoiceIds()) { + if (StringUtils.isBlank(voiceId)) { + continue; + } + if (Constant.VOICE_CLONE_HUOSHAN_DOUBLE_STREAM.equals(type)) { + if (voiceId.indexOf("S_") == -1) { + throw new RenException(ErrorCode.VOICE_CLONE_HUOSHAN_VOICE_ID_ERROR); + } + } + + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("voice_id", voiceId); + wrapper.eq("model_id", dto.getModelId()); + Long count = baseDao.selectCount(wrapper); + if (count > 0) { + throw new RenException(ErrorCode.VOICE_ID_ALREADY_EXISTS, "音色ID " + voiceId + " 已存在"); + } + } + // 遍历选择的音色ID,为每个音色ID创建一条记录 int index = 0; String namePrefix = DateUtils.format(new java.util.Date(), "MMddHHmm"); @@ -207,4 +250,125 @@ public class VoiceCloneServiceImpl extends BaseServiceImpl config = modelConfig.getConfigJson(); + String type = (String) config.get("type"); + if (StringUtils.isBlank(type)) { + throw new RenException(ErrorCode.VOICE_CLONE_MODEL_TYPE_NOT_FOUND); + } + if (Constant.VOICE_CLONE_HUOSHAN_DOUBLE_STREAM.equals(type)) { + huoshanClone(config, entity); + } + } catch (RenException re) { + entity.setTrainStatus(3); + entity.setTrainError(re.getMsg()); + baseDao.updateById(entity); + throw re; + } catch (Exception e) { + e.printStackTrace(); + entity.setTrainStatus(3); + entity.setTrainError(e.getMessage()); + baseDao.updateById(entity); + throw new RenException(ErrorCode.VOICE_CLONE_TRAINING_FAILED, e.getMessage()); + } + } + + /** + * 调用火山引擎进行语音复刻训练 + * + * @param config 模型配置 + * @param entity 语音克隆记录实体 + * @throws Exception + */ + private void huoshanClone(Map config, VoiceCloneEntity entity) throws Exception { + String appid = (String) config.get("appid"); + String accessToken = (String) config.get("access_token"); + + if (StringUtils.isAnyBlank(appid, accessToken)) { + throw new RenException(ErrorCode.VOICE_CLONE_HUOSHAN_CONFIG_MISSING); + } + + String audioBase64 = Base64.getEncoder().encodeToString(entity.getVoice()); + Map reqBody = new HashMap<>(); + reqBody.put("appid", appid); + List> audios = new ArrayList<>(); + Map audioMap = new HashMap<>(); + audioMap.put("audio_bytes", audioBase64); + audioMap.put("audio_format", "wav"); + audios.add(audioMap); + reqBody.put("audios", audios); + reqBody.put("source", 2); + reqBody.put("language", 0); + reqBody.put("model_type", 1); + reqBody.put("speaker_id", entity.getVoiceId()); + + String apiUrl = "https://openspeech.bytedance.com/api/v1/mega_tts/audio/upload"; + + HttpClient client = HttpClient.newHttpClient(); + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(apiUrl)) + .header("Content-Type", "application/json") + .header("Authorization", "Bearer;" + accessToken) + .header("Resource-Id", "seed-icl-1.0") + .POST(HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(reqBody))) + .build(); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + + System.out.println(">>> HTTP status = " + response.statusCode()); + System.out.println(">>> response body = " + response.body()); + + Map rsp = objectMapper.readValue(response.body(), + new TypeReference>() { + }); + + // 获取BaseResp对象 + Map baseResp = objectMapper.convertValue(rsp.get("BaseResp"), + new TypeReference>() { + }); + if (baseResp != null) { + Integer statusCode = objectMapper.convertValue(baseResp.get("StatusCode"), Integer.class); + String statusMessage = objectMapper.convertValue(baseResp.getOrDefault("StatusMessage", ""), + String.class); + + // 获取speaker_id + String speakerId = objectMapper.convertValue(rsp.get("speaker_id"), String.class); + + // StatusCode == 0 表示成功 + if (statusCode != null && statusCode == 0 && StringUtils.isNotBlank(speakerId)) { + entity.setTrainStatus(2); + entity.setVoiceId(speakerId); + entity.setTrainError(""); + baseDao.updateById(entity); + } else { + // 失败时使用StatusMessage作为错误信息 + String errorMsg = StringUtils.isNotBlank(statusMessage) ? statusMessage : "训练失败"; + throw new RenException(errorMsg); + } + } else { + String errorMsg = objectMapper.convertValue(rsp.get("message"), + new TypeReference() { + }); + if (StringUtils.isNotBlank(errorMsg)) { + throw new RenException(errorMsg); + } + throw new RenException(ErrorCode.VOICE_CLONE_RESPONSE_FORMAT_ERROR); + } + } } diff --git a/main/manager-api/src/main/resources/db/changelog/202510071521.sql b/main/manager-api/src/main/resources/db/changelog/202510071522.sql similarity index 71% rename from main/manager-api/src/main/resources/db/changelog/202510071521.sql rename to main/manager-api/src/main/resources/db/changelog/202510071522.sql index 06ffa0061..f53d42279 100644 --- a/main/manager-api/src/main/resources/db/changelog/202510071521.sql +++ b/main/manager-api/src/main/resources/db/changelog/202510071522.sql @@ -11,5 +11,9 @@ CREATE TABLE `ai_voice_clone` ( `train_error` VARCHAR(255) COMMENT '训练错误原因', `creator` BIGINT COMMENT '创建者 ID', `create_date` DATETIME COMMENT '创建时间', - PRIMARY KEY (`id`) + PRIMARY KEY (`id`), + INDEX idx_ai_voice_clone_user_id_model_id_train_status (model_id,user_id, train_status), + INDEX idx_ai_voice_clone_voice_id (voice_id), + INDEX idx_ai_voice_clone_user_id (user_id), + INDEX idx_ai_voice_clone_model_id_voice_id (model_id, voice_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='声音克隆表'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202510191042.sql b/main/manager-api/src/main/resources/db/changelog/202510191042.sql new file mode 100644 index 000000000..1511645bd --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202510191042.sql @@ -0,0 +1,2 @@ +UPDATE `ai_model_config` SET model_code = 'XunfeiSparkLLM' WHERE id = 'LLM_XunfeiSparkLLM'; +UPDATE `ai_model_config` SET model_code = 'XunfeiStreamASR' WHERE id = 'ASR_XunfeiStream'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202510250956.sql b/main/manager-api/src/main/resources/db/changelog/202510250956.sql new file mode 100644 index 000000000..b4129af1f --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202510250956.sql @@ -0,0 +1,24 @@ +-- 添加RAG模型供应器和配置 +-- ------------------------------------------------------- + +-- 添加RAG模型供应器 +delete from `ai_model_provider` where id = 'SYSTEM_RAG_ragflow'; +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES +('SYSTEM_RAG_ragflow', 'RAG', 'ragflow', 'RAGFlow', '[{"key": "base_url", "type": "string", "label": "服务地址"}, {"key": "api_key", "type": "string", "label": "API密钥"}]', 1, 1, NOW(), 1, NOW()); + +-- 添加RAG模型配置 +delete from `ai_model_config` where id = 'RAG_RAGFlow'; +INSERT INTO `ai_model_config` VALUES ('RAG_RAGFlow', 'RAG', 'ragflow', 'RAGFlow', 1, 1, '{"type": "ragflow", "base_url": "http://localhost", "api_key": "你的RAG密钥"}', 'https://github.com/infiniflow/ragflow/blob/main/README_zh.md', 'RAGFlow配置说明: +一、快速部署教程(docker部署) +1.$ sysctl vm.max_map_count +2.$ sysctl -w vm.max_map_count=262144 +3.$ git clone https://github.com/infiniflow/ragflow.git +4.docker compose -f docker-compose.yml up -d +5.$ docker logs -f docker-ragflow-cpu-1 +6.注冊登录后,点击右上角头像,获得RAGFlow的API KEY和API服务器地址。使用RAGFlow前请在Model Provider中添加模型和设置默认模型。 +二、如果您希望关掉注册功能 +1.停止服务 docker compose down +2. sed -i ''s/REGISTER_ENABLED=1/REGISTER_ENABLED=0/g'' .env +3.cat .env | grep -i register +4.看到REGISTER_ENABLED=0 重启服务即可。', 1, NULL, NULL, NULL, NULL); + diff --git a/main/manager-api/src/main/resources/db/changelog/202510251150.sql b/main/manager-api/src/main/resources/db/changelog/202510251150.sql new file mode 100644 index 000000000..4dea2bec4 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202510251150.sql @@ -0,0 +1,19 @@ +-- 知识库表 +DROP TABLE IF EXISTS `ai_rag_dataset`; +CREATE TABLE `ai_rag_dataset` ( + `id` VARCHAR(32) NOT NULL COMMENT '唯一标识', + `dataset_id` VARCHAR(64) NOT NULL COMMENT '知识库ID', + `rag_model_id` VARCHAR(64) COMMENT 'RAG模型配置ID', + `name` VARCHAR(100) NOT NULL COMMENT '知识库名称', + `description` TEXT COMMENT '知识库描述', + `status` TINYINT(1) DEFAULT 1 COMMENT '状态:0停用 1启用', + `creator` BIGINT COMMENT '创建者', + `created_at` DATETIME COMMENT '创建时间', + `updater` BIGINT COMMENT '更新者', + `updated_at` DATETIME COMMENT '更新时间', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_dataset_id` (`dataset_id`), + INDEX `idx_ai_rag_dataset_status` (`status`), + INDEX `idx_ai_rag_dataset_creator` (`creator`), + INDEX `idx_ai_rag_dataset_created_at` (`created_at`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='知识库表'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202511131023.sql b/main/manager-api/src/main/resources/db/changelog/202511131023.sql new file mode 100644 index 000000000..4efb12124 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202511131023.sql @@ -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"%'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index b3845b4d2..3c14eb7f0 100755 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -389,9 +389,37 @@ databaseChangeLog: encoding: utf8 path: classpath:db/changelog/202509220958.sql - changeSet: - id: 202510071521 + id: 202510071522 author: hrz changes: - sqlFile: encoding: utf8 - path: classpath:db/changelog/202510071521.sql + path: classpath:db/changelog/202510071522.sql + - changeSet: + id: 202510191042 + author: hrz + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202510191042.sql + - changeSet: + id: 202510250956 + author: rainv123 + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202510250956.sql + - changeSet: + id: 202510251150 + author: rainv123 + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202510251150.sql + - changeSet: + id: 202511131023 + author: hrz + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202511131023.sql diff --git a/main/manager-api/src/main/resources/i18n/messages.properties b/main/manager-api/src/main/resources/i18n/messages.properties index 816a1a8b6..ebde5cdf1 100644 --- a/main/manager-api/src/main/resources/i18n/messages.properties +++ b/main/manager-api/src/main/resources/i18n/messages.properties @@ -135,7 +135,9 @@ 10124=\u60A8\u7684mqtt\u5BC6\u94A5\u957F\u5EA6\u4E0D\u5B89\u5168\uFF0Cmqtt\u5BC6\u94A5\u5FC5\u987B\u540C\u65F6\u5305\u542B\u5927\u5C0F\u5199\u5B57\u6BCD 10125=\u60A8\u7684mqtt\u5BC6\u94A5\u5305\u542B\u5F31\u5BC6\u7801 10128=\u5B57\u5178\u6807\u7B7E\u91CD\u590D -10129=modelType\u548CprovideCode\u4E0D\u80FD\u4E3A\u7A7A +10129=SM2\u5BC6\u94A5\u672A\u914D\u7F6E +10130=SM2\u89E3\u5BC6\u5931\u8D25 +10131=modelType\u548CprovideCode\u4E0D\u80FD\u4E3A\u7A7A 10132=\u6CA1\u6709\u6743\u9650\u67E5\u770B\u8BE5\u667A\u80FD\u4F53\u7684\u804A\u5929\u8BB0\u5F55 10133=\u4F1A\u8BDDID\u4E0D\u80FD\u4E3A\u7A7A 10134=\u667A\u80FD\u4F53ID\u4E0D\u80FD\u4E3A\u7A7A @@ -154,4 +156,24 @@ 10147=\u97F3\u8272ID\u4E0D\u80FD\u4E3A\u7A7A 10148=\u5F52\u5C5E\u8D26\u53F7\u4E0D\u80FD\u4E3A\u7A7A 10149=\u5220\u9664\u7684\u97F3\u8272\u8D44\u6E90ID\u4E0D\u80FD\u4E3A\u7A7A -10150=\u60A8\u6CA1\u6709\u6743\u9650\u64CD\u4F5C\u8BE5\u8BB0\u5F55 \ No newline at end of file +10150=\u60A8\u6CA1\u6709\u6743\u9650\u64CD\u4F5C\u8BE5\u8BB0\u5F55 +10151=\u8BF7\u5148\u4E0A\u4F20\u97F3\u9891\u6587\u4EF6 +10152=\u6A21\u578B\u914D\u7F6E\u672A\u627E\u5230 +10153=\u6A21\u578B\u7C7B\u578B\u672A\u627E\u5230 +10154=\u8BAD\u7EC3\u5931\u8D25 +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} +10159=\u97F3\u8272ID\u5DF2\u5B58\u5728 +10160=\u706B\u5C71\u5F15\u64CE\u97F3\u8272ID\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5S_\u5F00\u5934 +10161=Mac\u5730\u5740\u5DF2\u5B58\u5728 +10162=\u6A21\u578B\u4F9B\u5E94\u5668\u4E0D\u5B58\u5728 +10163=\u77E5\u8BC6\u5E93\u8BB0\u5F55\u4E0D\u5B58\u5728 +10164=RAG\u914D\u7F6E\u672A\u627E\u5230 +10165=RAG\u914D\u7F6E\u7C7B\u578B\u9519\u8BEF +10166=\u9ED8\u8BA4RAG\u914D\u7F6E\u672A\u627E\u5230 +10167=\u0052\u0041\u0047\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 \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/messages_en_US.properties b/main/manager-api/src/main/resources/i18n/messages_en_US.properties index d338896c1..5774b8f62 100644 --- a/main/manager-api/src/main/resources/i18n/messages_en_US.properties +++ b/main/manager-api/src/main/resources/i18n/messages_en_US.properties @@ -156,4 +156,28 @@ 10147=Voice ID cannot be empty 10148=Owner account cannot be empty 10149=Voice resource ID to delete cannot be empty -10150=You do not have permission to operate this record \ No newline at end of file +10150=You do not have permission to operate this record +10151=Please upload audio file first +10152=Model configuration not found +10153=Model type not found +10154=Training failed: {0} +10155=Huoshan Engine configuration missing +10156=Response format error, missing BaseResp field +10157=Request failed +10158=Clone Voice: +10159=Voice ID already exists +10160=Huoshan Engine voice ID format error, must start with S_ +10161=Mac address already exists +10162=Model provider does not exist +10163=Knowledge base record does not exist +10164=RAG configuration not found +10165=RAG configuration type error +10166=Default RAG configuration not found +10167=RAG API call failed: {0} +10168=Upload file failed +10169=No permission to operate this knowledge base +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 diff --git a/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties b/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties index 175de7031..573d61428 100644 --- a/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties +++ b/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties @@ -156,4 +156,28 @@ 10147=\u97F3\u8272ID\u4E0D\u80FD\u4E3A\u7A7A 10148=\u5F52\u5C5E\u8D26\u53F7\u4E0D\u80FD\u4E3A\u7A7A 10149=\u5220\u9664\u7684\u97F3\u8272\u8D44\u6E90ID\u4E0D\u80FD\u4E3A\u7A7A -10150=\u60A8\u6CA1\u6709\u6743\u9650\u64CD\u4F5C\u8BE5\u8BB0\u5F55 \ No newline at end of file +10150=\u60A8\u6CA1\u6709\u6743\u9650\u64CD\u4F5C\u8BE5\u8BB0\u5F55 +10151=\u8BF7\u5148\u4E0A\u4F20\u97F3\u9891\u6587\u4EF6 +10152=\u6A21\u578B\u914D\u7F6E\u672A\u627E\u5230 +10153=\u6A21\u578B\u7C7B\u578B\u672A\u627E\u5230 +10154=\u8BAD\u7EC3\u5931\u8D25 +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: +10159=\u97F3\u8272ID\u5DF2\u5B58\u5728 +10160=\u706B\u5C71\u5F15\u64CE\u97F3\u8272ID\u683C\u5F0F\u9519\u8BEF\uFF0C\u5FC5\u987B\u4EE5S_\u5F00\u5934 +10161=Mac\u5730\u5740\u5DF2\u5B58\u5728 +10162=\u6A21\u578B\u4F9B\u5E94\u5668\u4E0D\u5B58\u5728 +10163=\u77E5\u8BC6\u5E93\u8BB0\u5F55\u4E0D\u5B58\u5728 +10164=RAG\u914D\u7F6E\u672A\u627E\u5230 +10165=RAG\u914D\u7F6E\u7C7B\u578B\u9519\u8BEF +10166=\u9ED8\u8BA4RAG\u914D\u7F6E\u672A\u627E\u5230 +10167=\u0052\u0041\u0047\u8c03\u7528\u5931\u8d25\uFF0C{0} +10168=\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25 +10169=\u60A8\u6CA1\u6709\u6743\u9650\u64CD\u4F5C\u8BE5\u8BB0\u5F55 +10170=\u77E5\u8BC6\u5E93\u540D\u79F0\u91CD\u590D +10171=\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 \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties b/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties index 3ed347428..c57f9e2c6 100644 --- a/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties +++ b/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties @@ -156,4 +156,28 @@ 10147=\u97F3\u8272ID\u4E0D\u80FD\u70BA\u7A7A 10148=\u6B78\u5C6C\u5E33\u865F\u4E0D\u80FD\u70BA\u7A7A 10149=\u522A\u9664\u7684\u97F3\u8272\u8CC7\u6E90ID\u4E0D\u80FD\u70BA\u7A7A -10150=\u60A8\u6C92\u6709\u6B0A\u9650\u64CD\u4F5C\u8A72\u8A18\u9304 \ No newline at end of file +10150=\u60A8\u6C92\u6709\u6B0A\u9650\u64CD\u4F5C\u8A72\u8A18\u9304 +10151=\u8ACB\u5148\u4E0A\u50B3\u97F3\u983B\u6587\u4EF6 +10152=\u6A21\u578B\u914D\u7F6E\u672A\u627E\u5230 +10153=\u6A21\u578B\u985E\u578B\u672A\u627E\u5230 +10154=\u6A21\u578B\u8AB2\u7DF4\u5931\u6557: {0} +10155=\u706B\u5C71\u5F15\u64CE\u7F3A\u5C11appid\u6216access_token +10156=\u97FF\u61C9\u683C\u5F0F\u932F\u8AA4\uFF0C\u7F3A\u5C11BaseResp\u5B57\u6BB5 +10157=\u8ACB\u6C42\u5931\u6557 +10158=\u514B\u9686\u8A9E\u97F3: +10159=\u97F3\u8272ID\u5DF2\u5B58\u5728 +10160=\u706B\u5C71\u5F15\u64CE\u97F3\u8272ID\u683C\u5F0F\u932F\u8AA4\uFF0C\u5FC5\u9808\u4EE5S_\u958B\u982D +10161=Mac\u5730\u5740\u5DF2\u5B58\u5728 +10162=\u6A21\u578B\u63D0\u4F9B\u5546\u4E0D\u5B58\u5728 +10163=\u77E5\u8B58\u5EAB\u8A18\u9304\u4E0D\u5B58\u5728 +10164=RAG\u914D\u7F6E\u672A\u627E\u5230 +10165=RAG\u914D\u7F6E\u985E\u578B\u932F\u8AA4 +10166=\u9810\u8A2DRAG\u914D\u7F6E\u672A\u627E\u5230 +10167=\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 diff --git a/main/manager-api/src/main/resources/mapper/knowledge/KnowledgeBaseDao.xml b/main/manager-api/src/main/resources/mapper/knowledge/KnowledgeBaseDao.xml new file mode 100644 index 000000000..e85a96747 --- /dev/null +++ b/main/manager-api/src/main/resources/mapper/knowledge/KnowledgeBaseDao.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + DELETE FROM ai_agent_plugin_mapping + WHERE plugin_id = #{knowledgeBaseId} + + + \ No newline at end of file diff --git a/main/manager-api/src/main/resources/mapper/voiceclone/VoiceCloneDao.xml b/main/manager-api/src/main/resources/mapper/voiceclone/VoiceCloneDao.xml new file mode 100644 index 000000000..d76585920 --- /dev/null +++ b/main/manager-api/src/main/resources/mapper/voiceclone/VoiceCloneDao.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/main/manager-mobile/src/api/auth.ts b/main/manager-mobile/src/api/auth.ts index 8b3b2d2b2..f9750a089 100644 --- a/main/manager-mobile/src/api/auth.ts +++ b/main/manager-mobile/src/api/auth.ts @@ -123,3 +123,21 @@ export function register(data: RegisterData) { }, }) } + +// 忘记密码数据类型 +export interface ForgotPasswordData { + phone: string + code: string + password: string + captchaId: string +} + +// 忘记密码(找回密码) +export function retrievePassword(data: ForgotPasswordData) { + return http.Put('/user/retrieve-password', data, { + meta: { + ignoreAuth: true, + toast: true, + }, + }) +} diff --git a/main/manager-mobile/src/i18n/en.ts b/main/manager-mobile/src/i18n/en.ts index 54b86c713..1d6e4beba 100644 --- a/main/manager-mobile/src/i18n/en.ts +++ b/main/manager-mobile/src/i18n/en.ts @@ -19,8 +19,7 @@ export default { 'login.enterCaptcha': 'Please enter verification code', 'login.loginButton': 'Login', 'login.loggingIn': 'Logging in...', - 'login.noAccount': 'did not have an account?', - 'login.registerNow': 'Register Now', + 'login.noAccount': 'Sign Up', 'login.enterPhone': 'Please enter phone number', 'login.selectCountry': 'Select Country/Region', 'login.confirm': 'Confirm', @@ -30,6 +29,7 @@ export default { 'login.requiredCaptcha': 'Verification code cannot be empty', 'login.requiredMobile': 'Please enter a valid phone number', 'login.captchaError': 'Graphic verification code error', + 'login.forgotPassword': 'Forgot Password', // Register page 'register.pageTitle': 'Register', @@ -189,6 +189,27 @@ export default { 'common.unknownError': 'Unknown error', 'common.networkError': 'Network error', + // Retrieve Password page + 'retrievePassword.title': 'Reset Password', + 'retrievePassword.subtitle': 'Recover your account password via mobile number', + 'retrievePassword.mobileRequired': 'Please enter mobile number', + 'retrievePassword.inputCorrectMobile': 'Please enter a valid mobile number', + 'retrievePassword.captchaRequired': 'Please enter graphic verification code', + 'retrievePassword.mobileCaptchaRequired': 'Please enter SMS verification code', + 'retrievePassword.newPasswordRequired': 'Please enter new password', + 'retrievePassword.confirmNewPasswordRequired': 'Please confirm new password', + 'retrievePassword.passwordsNotMatch': 'Passwords do not match', + 'retrievePassword.mobilePlaceholder': 'Please enter mobile number', + 'retrievePassword.captchaPlaceholder': 'Please enter graphic verification code', + 'retrievePassword.mobileCaptchaPlaceholder': 'Please enter SMS verification code', + 'retrievePassword.newPasswordPlaceholder': 'Please enter new password', + 'retrievePassword.confirmNewPasswordPlaceholder': 'Please confirm new password', + 'retrievePassword.getMobileCaptcha': 'Get Code', + 'retrievePassword.captchaSendSuccess': 'Verification code sent successfully', + 'retrievePassword.passwordUpdateSuccess': 'Password reset successfully', + 'retrievePassword.resetButton': 'Reset Password', + 'retrievePassword.goToLogin': 'Back to Login', + // SM2 encryption related error messages 'sm2.publicKeyNotConfigured': 'SM2 public key not configured, please contact administrator', 'sm2.encryptionFailed': 'Password encryption failed', diff --git a/main/manager-mobile/src/i18n/zh_CN.ts b/main/manager-mobile/src/i18n/zh_CN.ts index 5b25c57b6..c1e9b8560 100644 --- a/main/manager-mobile/src/i18n/zh_CN.ts +++ b/main/manager-mobile/src/i18n/zh_CN.ts @@ -19,8 +19,7 @@ export default { 'login.enterCaptcha': '请输入验证码', 'login.loginButton': '登录', 'login.loggingIn': '登录中...', - 'login.noAccount': '还没有账户?', - 'login.registerNow': '立即注册', + 'login.noAccount': '新用户注册', 'login.enterPhone': '请输入手机号码', 'login.selectCountry': '选择国家/地区', 'login.confirm': '确认', @@ -30,6 +29,7 @@ export default { 'login.requiredCaptcha': '验证码不能为空', 'login.requiredMobile': '请输入正确的手机号码', 'login.captchaError': '图形验证码错误', + 'login.forgotPassword': '忘记密码', // 注册页面 'register.pageTitle': '注册', @@ -265,6 +265,27 @@ export default { 'settings.selectLanguage': '选择语言', 'settings.languageChanged': '语言切换成功', + // 重置密码页面 + 'retrievePassword.title': '重置密码', + 'retrievePassword.subtitle': '通过手机号找回您的账户密码', + 'retrievePassword.mobileRequired': '请输入手机号码', + 'retrievePassword.inputCorrectMobile': '请输入正确的手机号码', + 'retrievePassword.captchaRequired': '请输入图形验证码', + 'retrievePassword.mobileCaptchaRequired': '请输入短信验证码', + 'retrievePassword.newPasswordRequired': '请输入新密码', + 'retrievePassword.confirmNewPasswordRequired': '请确认新密码', + 'retrievePassword.passwordsNotMatch': '两次输入的密码不一致', + 'retrievePassword.mobilePlaceholder': '请输入手机号码', + 'retrievePassword.captchaPlaceholder': '请输入图形验证码', + 'retrievePassword.mobileCaptchaPlaceholder': '请输入短信验证码', + 'retrievePassword.newPasswordPlaceholder': '请输入新密码', + 'retrievePassword.confirmNewPasswordPlaceholder': '请确认新密码', + 'retrievePassword.getMobileCaptcha': '获取验证码', + 'retrievePassword.captchaSendSuccess': '验证码发送成功', + 'retrievePassword.passwordUpdateSuccess': '密码重置成功', + 'retrievePassword.resetButton': '重置密码', + 'retrievePassword.goToLogin': '返回登录', + // 消息提示 'message.loginSuccess': '登录成功!', 'message.loginFail': '登录失败', diff --git a/main/manager-mobile/src/i18n/zh_TW.ts b/main/manager-mobile/src/i18n/zh_TW.ts index fde04bc62..4873f5362 100644 --- a/main/manager-mobile/src/i18n/zh_TW.ts +++ b/main/manager-mobile/src/i18n/zh_TW.ts @@ -19,8 +19,7 @@ export default { 'login.enterCaptcha': '請輸入驗證碼', 'login.loginButton': '登錄', 'login.loggingIn': '登錄中...', - 'login.noAccount': '還沒有賬戶?', - 'login.registerNow': '立即註冊', + 'login.noAccount': '新用戶註冊', 'login.enterPhone': '請輸入手機號碼', 'login.selectCountry': '選擇國家/地區', 'login.confirm': '確認', @@ -30,6 +29,32 @@ export default { 'login.requiredCaptcha': '驗證碼不能為空', 'login.requiredMobile': '請輸入正確的手機號碼', 'login.captchaError': '圖形驗證碼錯誤', + 'login.forgotPassword': '忘記密碼', + + // 忘記密碼頁面 + 'retrievePassword.title': '重置密碼', + 'retrievePassword.subtitle': '請輸入您的手機號碼以重置密碼', + 'retrievePassword.mobileRequired': '請輸入手機號碼', + 'retrievePassword.inputCorrectMobile': '請輸入正確的手機號碼', + 'retrievePassword.captchaRequired': '請輸入圖形驗證碼', + 'retrievePassword.mobileCaptchaRequired': '請輸入手機驗證碼', + 'retrievePassword.newPasswordRequired': '請輸入新密碼', + 'retrievePassword.confirmNewPasswordRequired': '請確認新密碼', + 'retrievePassword.passwordsNotMatch': '兩次輸入的密碼不一致', + 'retrievePassword.mobilePlaceholder': '請輸入手機號碼', + 'retrievePassword.captchaPlaceholder': '請輸入圖形驗證碼', + 'retrievePassword.mobileCaptchaPlaceholder': '請輸入手機驗證碼', + 'retrievePassword.newPasswordPlaceholder': '請輸入新密碼', + 'retrievePassword.confirmNewPasswordPlaceholder': '請確認新密碼', + 'retrievePassword.confirmPasswordPlaceholder': '請確認新密碼', + 'retrievePassword.captchaSendSuccess': '驗證碼發送成功', + 'retrievePassword.passwordUpdateSuccess': '密碼更新成功', + 'retrievePassword.getCaptcha': '獲取驗證碼', + 'retrievePassword.getMobileCaptcha': '獲取驗證碼', + 'retrievePassword.resend': '重新發送', + 'retrievePassword.resetPasswordButton': '重置密碼', + 'retrievePassword.resetButton': '重置密碼', + 'retrievePassword.goToLogin': '返回登錄', // 註冊頁面 'register.pageTitle': '註冊', diff --git a/main/manager-mobile/src/pages.json b/main/manager-mobile/src/pages.json index ac7da2ce8..554a0a20b 100644 --- a/main/manager-mobile/src/pages.json +++ b/main/manager-mobile/src/pages.json @@ -108,6 +108,15 @@ "navigationStyle": "custom" } }, + { + "path": "pages/forgot-password/index", + "type": "page", + "layout": "default", + "style": { + "navigationStyle": "custom", + "navigationBarTitleText": "ForgotPassword" + } + }, { "path": "pages/login/index", "type": "page", diff --git a/main/manager-mobile/src/pages/forgot-password/index.vue b/main/manager-mobile/src/pages/forgot-password/index.vue new file mode 100644 index 000000000..f574d0e91 --- /dev/null +++ b/main/manager-mobile/src/pages/forgot-password/index.vue @@ -0,0 +1,848 @@ + +{ + "layout": "default", + "style": { + "navigationStyle": "custom", + "navigationBarTitleText": "ForgotPassword" + } +} + + + + + + + diff --git a/main/manager-mobile/src/pages/login/index.vue b/main/manager-mobile/src/pages/login/index.vue index 0a87707ec..462dccee8 100644 --- a/main/manager-mobile/src/pages/login/index.vue +++ b/main/manager-mobile/src/pages/login/index.vue @@ -9,15 +9,15 @@ \ No newline at end of file + +/* 添加倒三角旋转样式 */ +.rotate-down { + transform: rotate(180deg); + transition: transform 0.3s ease; +} + +.el-icon-arrow-down { + transition: transform 0.3s ease; +} + diff --git a/main/manager-web/src/components/KnowledgeBaseDialog.vue b/main/manager-web/src/components/KnowledgeBaseDialog.vue new file mode 100644 index 000000000..6e72d2da2 --- /dev/null +++ b/main/manager-web/src/components/KnowledgeBaseDialog.vue @@ -0,0 +1,243 @@ + + + + + \ No newline at end of file diff --git a/main/manager-web/src/components/McpToolCallDialog.vue b/main/manager-web/src/components/McpToolCallDialog.vue deleted file mode 100644 index d271c3ff8..000000000 --- a/main/manager-web/src/components/McpToolCallDialog.vue +++ /dev/null @@ -1,1604 +0,0 @@ - - - - - diff --git a/main/manager-web/src/components/ProviderDialog.vue b/main/manager-web/src/components/ProviderDialog.vue index 469458328..61e5b9de9 100644 --- a/main/manager-web/src/components/ProviderDialog.vue +++ b/main/manager-web/src/components/ProviderDialog.vue @@ -88,6 +88,7 @@ + @@ -82,9 +79,9 @@ {{ $t('device.manualAdd') }} - {{ - $t('device.unbind') - }} + + {{ $t('device.unbind') }} +
@@ -92,20 +89,22 @@ :label="$t('dictManagement.itemsPerPage').replace('{items}', item)" :value="item"> - - + + - - {{ $t('dictManagement.totalRecords').replace('{total}', deviceList.length) - }} + + + {{ $t('dictManagement.totalRecords').replace('{total}', deviceList.length) }} +
@@ -117,7 +116,6 @@ @refresh="fetchBindDevices(currentAgentId)" /> - @@ -127,20 +125,17 @@ import Api from '@/apis/api'; import AddDeviceDialog from "@/components/AddDeviceDialog.vue"; import HeaderBar from "@/components/HeaderBar.vue"; import ManualAddDeviceDialog from "@/components/ManualAddDeviceDialog.vue"; -import McpToolCallDialog from "@/components/McpToolCallDialog.vue"; export default { components: { HeaderBar, AddDeviceDialog, - ManualAddDeviceDialog, - McpToolCallDialog + ManualAddDeviceDialog }, data() { return { addDeviceDialogVisible: false, manualAddDeviceDialogVisible: false, - mcpToolCallDialogVisible: false, selectedDeviceId: '', searchKeyword: "", activeSearchKeyword: "", @@ -280,11 +275,6 @@ export default { handleManualAddDevice() { this.manualAddDeviceDialogVisible = true; }, - - handleMcpToolCall(deviceId) { - this.selectedDeviceId = deviceId; - this.mcpToolCallDialogVisible = true; - }, submitRemark(row) { if (row._submitting) return; @@ -383,7 +373,7 @@ export default { .sort((a, b) => a.rawBindTime - b.rawBindTime); this.activeSearchKeyword = ""; this.searchKeyword = ""; - + // 获取设备列表后,立即获取设备状态 this.fetchDeviceStatus(agentId); } else { @@ -391,7 +381,7 @@ export default { } }); }, - + // 获取设备状态 fetchDeviceStatus(agentId) { Api.device.getDeviceStatus(agentId, ({ data }) => { @@ -399,7 +389,7 @@ export default { try { // 解析后端返回的设备状态JSON const statusData = JSON.parse(data.data); - + // 直接使用解析后的数据作为设备状态映射(不需要devices字段包装) if (statusData && typeof statusData === 'object') { // 更新设备状态 @@ -411,7 +401,7 @@ export default { } }); }, - + // 根据API响应更新设备状态 updateDeviceStatusFromResponse(deviceStatusMap) { this.deviceList.forEach(device => { @@ -419,11 +409,11 @@ export default { const macAddress = device.macAddress ? device.macAddress.replace(/:/g, '_') : 'unknown'; const groupId = device.model ? device.model.replace(/:/g, '_') : 'GID_default'; const mqttClientId = `${groupId}@@@${macAddress}@@@${macAddress}`; - + // 从状态映射中获取设备状态 if (deviceStatusMap[mqttClientId]) { const statusInfo = deviceStatusMap[mqttClientId]; - + let isOnline = false; if (statusInfo.isAlive === true) { isOnline = true; @@ -434,7 +424,7 @@ export default { } else { isOnline = false; } - + device.deviceStatus = isOnline ? 'online' : 'offline'; } else { // 如果没有找到对应的状态信息,默认为离线 diff --git a/main/manager-web/src/views/KnowledgeBaseManagement.vue b/main/manager-web/src/views/KnowledgeBaseManagement.vue new file mode 100644 index 000000000..a672e3243 --- /dev/null +++ b/main/manager-web/src/views/KnowledgeBaseManagement.vue @@ -0,0 +1,827 @@ + + + + + diff --git a/main/manager-web/src/views/KnowledgeFileUpload.vue b/main/manager-web/src/views/KnowledgeFileUpload.vue new file mode 100644 index 000000000..dec0da856 --- /dev/null +++ b/main/manager-web/src/views/KnowledgeFileUpload.vue @@ -0,0 +1,2102 @@ + + + + + diff --git a/main/manager-web/src/views/ModelConfig.vue b/main/manager-web/src/views/ModelConfig.vue index a0f5036df..20ca8f60d 100644 --- a/main/manager-web/src/views/ModelConfig.vue +++ b/main/manager-web/src/views/ModelConfig.vue @@ -52,6 +52,9 @@ {{ $t("modelConfig.memory") }} + + {{ $t("modelConfig.rag") }} + @@ -471,6 +474,7 @@ export default { const id = formData.id; if (this.editModelData.duplicateMode) { + formData.id = ""; Api.model.addModel({ modelType, provideCode, formData }, ({ data }) => { if (data.code === 0) { this.$message.success(this.$t("modelConfig.duplicateSuccess")); diff --git a/main/manager-web/src/views/ProviderManagement.vue b/main/manager-web/src/views/ProviderManagement.vue index a467f0a2b..3c55c4b4f 100644 --- a/main/manager-web/src/views/ProviderManagement.vue +++ b/main/manager-web/src/views/ProviderManagement.vue @@ -147,7 +147,8 @@ export default { { value: "Intent", labelKey: 'providerManagement.modelType.Intent' }, { value: "Memory", labelKey: 'providerManagement.modelType.Memory' }, { value: "VAD", labelKey: 'providerManagement.modelType.VAD' }, - { value: "Plugin", labelKey: 'providerManagement.modelType.Plugin' } + { value: "Plugin", labelKey: 'providerManagement.modelType.Plugin' }, + { value: "RAG", labelKey: 'providerManagement.modelType.RAG' } ], currentPage: 1, loading: false, @@ -369,7 +370,8 @@ export default { 'LLM': 'danger', 'Intent': 'info', 'Memory': '', - 'VAD': 'primary' + 'VAD': 'primary', + 'RAG': 'warning' }; return typeMap[type] || ''; }, diff --git a/main/manager-web/src/views/VoiceCloneManagement.vue b/main/manager-web/src/views/VoiceCloneManagement.vue index a0e68ebcb..71282ad7e 100644 --- a/main/manager-web/src/views/VoiceCloneManagement.vue +++ b/main/manager-web/src/views/VoiceCloneManagement.vue @@ -36,20 +36,33 @@ - + + + + + + @@ -136,7 +149,10 @@ export default { modelId: "", voiceIds: [], userId: null - } + }, + // 音频播放相关 + currentAudio: null, // 当前正在播放的音频对象 + playingRowId: null // 当前正在播放的行 ID }; }, created() { @@ -164,6 +180,29 @@ export default { }, }, methods: { + getTooltipContent(row) { + if (!row.hasVoice) { + return '待上传'; + } + switch (row.trainStatus) { + case 0: + return '待复刻'; + case 2: + return '训练成功'; + case 3: + // 训练失败时,根据错误信息智能展示 + if (row.trainError) { + return `训练失败:${row.trainError}`; + } + return '训练失败'; + default: + return ''; + } + }, + handleViewDetails(row) { + console.log('查看详情:', row); + // 可以在这里添加查看详情的逻辑 + }, handlePageSizeChange(val) { this.pageSize = val; this.currentPage = 1; @@ -226,8 +265,6 @@ export default { switch (row.trainStatus) { case 0: return this.$t('voiceClone.waitingTraining'); - case 1: - return this.$t('voiceClone.training'); case 2: return this.$t('voiceClone.trainSuccess'); case 3: @@ -236,19 +273,100 @@ export default { return ''; } }, + // 获取状态按钮样式 + getStatusButtonClass(row) { + if (!row.hasVoice || row.trainStatus === 0) { + return 'status-waiting'; + } else if (row.trainStatus === 2) { + return 'status-success'; + } else if (row.trainStatus === 3) { + return 'status-failed'; + } + return ''; + }, // 处理复刻操作 handleClone(row) { + // 防止重复提交 + if (row._cloning) { + return; + } + this.$set(row, '_cloning', true); + const params = { cloneId: row.id }; - Api.voiceClone.cloneAudio(params, (res) => { - res = res.data; - if (res.code === 0) { - this.$message.success(this.$t('message.success')); - } else { - this.$message.error(res.msg || this.$t('message.error')); + try { + Api.voiceClone.cloneAudio(params, (res) => { + try { + res = res.data; + if (res.code === 0) { + this.$message.success(this.$t('message.success')); + // 复刻成功后刷新列表 + this.fetchVoiceCloneList(); + } else { + // 复刻失败时刷新列表以获取完整的错误信息 + console.log('API返回错误,刷新列表获取详细错误信息'); + this.$message.error(res.msg || this.$t('message.error')); + // 刷新列表以获取后端保存的完整错误详情 + this.fetchVoiceCloneList(); + } + } catch (error) { + // 处理响应时出错,刷新列表 + console.error('处理响应时出错:', error); + this.$message.error('处理响应时出错'); + this.fetchVoiceCloneList(); + } finally { + this.$set(row, '_cloning', false); + } + }, (error) => { + // API调用失败,刷新列表以获取最新状态 + console.error('API调用失败:', error); + this.$message.error('克隆失败,请将鼠标悬停在错误提示上,查看错误详情'); + this.fetchVoiceCloneList(); + this.$set(row, '_cloning', false); + }); + } catch (error) { + // 调用API时出错,刷新列表 + console.error('调用API时出错:', error); + this.$message.error('调用API时出错'); + this.fetchVoiceCloneList(); + this.$set(row, '_cloning', false); + } + }, + + // 更新行状态并触发视图更新 + updateRowStatus(row, status, statusCode = null) { + // 在Vue中直接修改数组中的对象属性可能不会触发视图更新 + const index = this.voiceCloneList.findIndex(item => item.id === row.id); + const updateData = { + trainStatus: status + }; + + // 如果提供了状态码,也更新状态码信息 + if (statusCode !== null) { + updateData.statusCode = statusCode; + } + + if (index !== -1) { + // 使用Vue.set来确保响应式更新 + this.$set(this.voiceCloneList, index, { + ...this.voiceCloneList[index], + ...updateData + }); + // 强制表格重新渲染 + if (this.$refs.paramsTable) { + this.$refs.paramsTable.doLayout(); } - }); + } else { + // 如果找不到索引,直接更新row对象 + row.trainStatus = status; + if (statusCode !== null) { + row.statusCode = statusCode; + } + // 强制整个表格重新渲染 + this.$forceUpdate(); + } + console.log('更新行状态:', row.id, '状态:', status, '状态码:', statusCode); }, // 复刻成功后的回调 handleCloneSuccess() { @@ -312,6 +430,15 @@ export default { }, // 播放音频 handlePlay(row) { + // 如果点击的是正在播放的行,则停止播放 + if (this.playingRowId === row.id && this.currentAudio) { + this.stopCurrentAudio(); + return; + } + + // 停止当前正在播放的音频(如果有) + this.stopCurrentAudio(); + // 先获取音频下载ID Api.voiceClone.getAudioId(row.id, (res) => { res = res.data; @@ -320,15 +447,43 @@ export default { // 使用获取到的uuid播放音频 const audioUrl = Api.voiceClone.getPlayVoiceUrl(uuid); const audio = new Audio(audioUrl); + + // 设置当前播放状态 + this.currentAudio = audio; + this.playingRowId = row.id; + + // 播放结束时清除状态 + audio.addEventListener('ended', () => { + this.playingRowId = null; + this.currentAudio = null; + }); + + // 播放出错时清除状态 + audio.addEventListener('error', () => { + this.playingRowId = null; + this.currentAudio = null; + }); + audio.play().catch(err => { console.error('播放失败:', err); this.$message.error(this.$t('voiceClone.playFailed') || '播放失败'); + this.playingRowId = null; + this.currentAudio = null; }); } else { this.$message.error(res.msg || this.$t('voiceClone.audioNotExist') || '音频不存在'); } }); }, + // 停止当前音频播放 + stopCurrentAudio() { + if (this.currentAudio) { + this.currentAudio.pause(); + this.currentAudio.currentTime = 0; + this.currentAudio = null; + } + this.playingRowId = null; + }, // 上传音频 handleUpload(row) { this.currentVoiceClone = row; @@ -619,6 +774,35 @@ export default { color: #5a64b5 !important; } +/* 状态按钮样式 */ +.status-button { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 4px 10px; + border-radius: 4px; + font-size: 12px; + font-weight: 500; +} + +.status-waiting { + background-color: #f5f7fa; + color: #909399; + border: 1px solid #e4e7ed; +} + +.status-success { + background-color: #f6ffed; + color: #52c41a; + border: 1px solid #b7eb8f; +} + +.status-failed { + background-color: #fff2f0; + color: #ff4d4f; + border: 1px solid #ffccc7; +} + .name-view { display: inline-flex; align-items: center; diff --git a/main/manager-web/src/views/VoiceResourceManagement.vue b/main/manager-web/src/views/VoiceResourceManagement.vue index efcba4139..cce107e11 100644 --- a/main/manager-web/src/views/VoiceResourceManagement.vue +++ b/main/manager-web/src/views/VoiceResourceManagement.vue @@ -249,9 +249,9 @@ export default { } const itemCount = items.length; - this.$confirm(this.$t('voiceClone.confirmDelete', { count: itemCount }), 'Warning', { - confirmButtonText: 'OK', - cancelButtonText: 'Cancel', + this.$confirm(this.$t('voiceClone.confirmDelete', { count: itemCount }), this.$t('voiceClone.warning'), { + confirmButtonText: this.$t('voiceClone.ok'), + cancelButtonText: this.$t('voiceClone.cancel'), type: 'warning', distinguishCancelAndClose: true }).then(() => { diff --git a/main/manager-web/src/views/roleConfig.vue b/main/manager-web/src/views/roleConfig.vue index bc561f94b..8e0eee080 100644 --- a/main/manager-web/src/views/roleConfig.vue +++ b/main/manager-web/src/views/roleConfig.vue @@ -104,8 +104,8 @@
功能名称: {{ func.name }}
-
- {{ func.name.charAt(0) }} +
+ {{ getFunctionDisplayChar(func.name) }}
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' && @@ -755,11 +760,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 { diff --git a/main/xiaozhi-server/agent-base-prompt.txt b/main/xiaozhi-server/agent-base-prompt.txt index 34245291e..5b2fa792a 100644 --- a/main/xiaozhi-server/agent-base-prompt.txt +++ b/main/xiaozhi-server/agent-base-prompt.txt @@ -63,11 +63,11 @@ - 查询**详细农历信息**(宜忌、八字、节气等)。 - 除上述例外外的**任何其他信息或操作请求**(如查新闻、订闹钟、算数学、查非本地天气等)。 - 我已经给你装了摄像头,如果用户说“拍照”,你需要调用self_camera_take_photo工具说一下你看到了什么。默认question的参数是“描述一下看到的物品” + - 当工具列表包含search_from_ragflow,说明可以使用知识库,你应该结合用户上下文意图并结合知识库的使用描述,推断是否要调用调用知识库。 【重要!以下信息已实时提供,无需调用工具查询,请直接使用:】 -- **设备ID:** {{device_id}} - **当前时间:** {{current_time}} - **今天日期:** {{today_date}} ({{today_weekday}}) - **今天农历:** {{lunar_date}} diff --git a/main/xiaozhi-server/app.py b/main/xiaozhi-server/app.py index 0edb475be..bc6f0b545 100644 --- a/main/xiaozhi-server/app.py +++ b/main/xiaozhi-server/app.py @@ -46,12 +46,18 @@ async def main(): check_ffmpeg_installed() config = load_config() - # 默认使用manager-api的secret作为auth_key - # 如果secret为空,则生成随机密钥 - # auth_key用于jwt认证,比如视觉分析接口的jwt认证 - auth_key = config.get("manager-api", {}).get("secret", "") + # auth_key优先级:配置文件server.auth_key > manager-api.secret > 自动生成 + # auth_key用于jwt认证,比如视觉分析接口的jwt认证、ota接口的token生成与websocket认证 + # 获取配置文件中的auth_key + auth_key = config["server"].get("auth_key", "") + + # 验证auth_key,无效则尝试使用manager-api.secret if not auth_key or len(auth_key) == 0 or "你" in auth_key: - auth_key = str(uuid.uuid4().hex) + auth_key = config.get("manager-api", {}).get("secret", "") + # 验证secret,无效则生成随机密钥 + if not auth_key or len(auth_key) == 0 or "你" in auth_key: + auth_key = str(uuid.uuid4().hex) + config["server"]["auth_key"] = auth_key # 添加 stdin 监控任务 diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 69c8ebb64..60d5da50b 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -31,17 +31,11 @@ server: auth: # Whether to enable authentication enabled: false - # The token of the device can be written into your own defined token during the firmware compilation process - # Only if the token on the firmware matches the following token can you connect to this server - tokens: - - token: "your-token1" # Device 1's token - name: "your-device-name1" # Device 1 ID - - token: "your-token2" # Device 2's token - name: "your-device-name2" # Device 2 ID - # Optional: Device whitelist. If a whitelist is set, all devices on the whitelist can connect regardless of their token. - #allowed_devices: - # - "24:0A:C4:1D:3B:F0" # MAC address list - #MQTT gateway configuration, used to send data to the device via OTA, configured according to the .env file of mqtt_gateway, in the format of host:port + # 白名单设备ID列表 + # 如果属于白名单内的设备,不校验token,直接放行 + allowed_devices: + - "11:22:33:44:55:66" + # MQTT网关配置,用于通过OTA下发到设备,根据mqtt_gateway的.env文件配置,格式为host:port mqtt_gateway: null #MQTT signature key, used to generate the MQTT connection password, configured according to the .env file of mqtt_gateway mqtt_signature_key: null @@ -76,6 +70,12 @@ enable_stop_tts_notify: false # Whether to turn on the prompt sound after speaking, sound effect address stop_tts_notify_voice: "config/assets/tts_notify.mp3" +# TTS音频发送延迟配置 +# tts_audio_send_delay: 控制音频包发送间隔 +# 0: 使用精确时间控制,严格匹配音频帧率(默认,运行时按音频帧率计算) +# > 0: 使用固定延迟(毫秒)发送,例如: 60 +tts_audio_send_delay: 0 + exit_commands: - "quit" - "closure" @@ -146,9 +146,17 @@ plugins: - ".mp3" - ".wav" - ".p3" - refresh_time: 300 # The time interval for refreshing the music list, in seconds - -# Voiceprint Recognition Configuration + refresh_time: 300 # 刷新音乐列表的时间间隔,单位为秒 + search_from_ragflow: + # 知识库的描述信息,方便大语言模型知道什么时候调用 + description: "当用户问xxx时,调用本方法,使用知识库中的信息回答问题" + # ragflow接口配置 + base_url: "http://192.168.0.8" + # ragflow api访问令牌 + api_key: "ragflow-xxx" + # ragflow知识库id + dataset_ids: ["123456789"] +# 声纹识别配置 voiceprint: # Voiceprint interface address url: @@ -179,7 +187,10 @@ prompt: | - Long-winded, rambling speeches - Long and serious conversations -# Ending prompt +# 默认系统提示词模板文件 +prompt_template: agent-base-prompt.txt + +# 结束语prompt end_prompt: enable: true # Whether to enable the closing statement # Conclusion @@ -236,6 +247,7 @@ Intent: functions: -change_role - get_weather + # - search_from_ragflow # - get_news_from_chinanews - get_news_from_newsnow # play_music is the music player that comes with the server, hass_play_music is an independent external program music player controlled by home assistant @@ -984,13 +996,13 @@ TTS: api_key: your api_key voice: x5_lingxiaoxuan_flow output_dir: tmp/ - # The following settings are not required, use the default settings, please note that V5 timbre does not support spoken language configuration - # oral_level: mid # Oral level: high, mid, low - # spark_assist: 1 # Whether to use the large model for spoken language: open: 1, close: 0 - # stop_split: 0 # Turn off server-side splitting. Do not turn off: 0, turn off: 1 - # remain: 0 # Whether to keep the original written language: 1, not: 0 - # format: raw # Audio formats: raw(PCM), lame(MP3), speex, opus, opus-wb, opus-swb, speex-wb - # sample_rate: 24000 # Sampling rate: 16000, 8000, 24000 - # volume: 50 # Volume: 0-100 - # speed: 50 # Speech speed: 0-100 - # pitch: 50 # Intonation: 0-100 + # 以下可不用设置,使用默认设置,注意V5音色不支持口语化配置 + # oral_level: mid # 口语化等级:high, mid, low + # spark_assist: 1 # 是否通过大模型进行口语化 开启:1, 关闭:0 + # stop_split: 0 # 关闭服务端拆句 不关闭:0,关闭:1 + # remain: 0 # 是否保留原书面语的样子 保留:1, 不保留:0 + # format: raw # 音频格式:raw(PCM), lame(MP3), speex, opus, opus-wb, opus-swb, speex-wb + # sample_rate: 24000 # 采样率:16000, 8000, 24000 + # volume: 50 # 音量:0-100 + # speed: 50 # 语速:0-100 + # pitch: 50 # 语调:0-100 diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py index 1bb34be97..0464738eb 100644 --- a/main/xiaozhi-server/config/config_loader.py +++ b/main/xiaozhi-server/config/config_loader.py @@ -68,6 +68,9 @@ def get_config_from_api(config): "vision_explain": config["server"].get("vision_explain", ""), "auth_key": config["server"].get("auth_key", ""), } + # 如果服务器没有prompt_template,则从本地配置读取 + if not config_data.get("prompt_template"): + config_data["prompt_template"] = config.get("prompt_template") return config_data diff --git a/main/xiaozhi-server/config/logger.py b/main/xiaozhi-server/config/logger.py index 58a605643..90d27ac31 100644 --- a/main/xiaozhi-server/config/logger.py +++ b/main/xiaozhi-server/config/logger.py @@ -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.4" +SERVER_VERSION = "0.8.8" _logger_initialized = False diff --git a/main/xiaozhi-server/config_from_api.yaml b/main/xiaozhi-server/config_from_api.yaml index 283178d7f..1f40d6c7c 100644 --- a/main/xiaozhi-server/config_from_api.yaml +++ b/main/xiaozhi-server/config_from_api.yaml @@ -22,4 +22,6 @@ manager-api: # 如果使用docker部署,请使用填写成 http://xiaozhi-esp32-server-web:8002/xiaozhi url: http://127.0.0.1:8002/xiaozhi # 你的manager-api的token,就是刚才复制出来的server.secret - secret: 你的server.secret值 \ No newline at end of file + secret: 你的server.secret值 +# 默认系统提示词模板文件 +prompt_template: agent-base-prompt.txt \ No newline at end of file diff --git a/main/xiaozhi-server/core/api/ota_handler.py b/main/xiaozhi-server/core/api/ota_handler.py index a2edd0c6e..c696262ea 100644 --- a/main/xiaozhi-server/core/api/ota_handler.py +++ b/main/xiaozhi-server/core/api/ota_handler.py @@ -17,18 +17,18 @@ class OTAHandler(BaseHandler): super().__init__(config) auth_config = config["server"].get("auth", {}) self.auth_enable = auth_config.get("enabled", False) - # Device whitelist + # 设备白名单 self.allowed_devices = set(auth_config.get("allowed_devices", [])) secret_key = config["server"]["auth_key"] expire_seconds = auth_config.get("expire_seconds") self.auth = AuthManager(secret_key=secret_key, expire_seconds=expire_seconds) def generate_password_signature(self, content: str, secret_key: str) -> str: - """Generate MQTT cryptographic signature + """生成MQTT密码签名 Args: - content: signature content (clientId + '|' + username) - secret_key: key + content: 签名内容 (clientId + '|' + username) + secret_key: 密钥 Returns: str: Base64 encoded HMAC-SHA256 signature @@ -81,6 +81,12 @@ class OTAHandler(BaseHandler): else: raise Exception("Ota request client id is empty") + client_id = request.headers.get("client-id", "") + if client_id: + self.logger.bind(tag=TAG).info(f"OTA请求ClientID: {client_id}") + else: + raise Exception("OTA请求ClientID为空") + data_json = json.loads(data) server_config = self.config["server"] @@ -100,8 +106,8 @@ class OTAHandler(BaseHandler): mqtt_gateway_endpoint = server_config.get("mqtt_gateway") - if mqtt_gateway_endpoint: # If a non-empty string is configured - # Try to get the device model from the request data + if mqtt_gateway_endpoint: # 如果配置了非空字符串 + # 尝试从请求数据中获取设备型号 device_model = "default" try: if "device" in data_json and isinstance(data_json["device"], dict): @@ -116,7 +122,7 @@ class OTAHandler(BaseHandler): mac_address_safe = device_id.replace(":", "_") mqtt_client_id = f"{group_id}@@@{mac_address_safe}@@@{mac_address_safe}" - # Build user data + # 构建用户数据 user_data = {"ip": "unknown"} try: user_data_json = json.dumps(user_data) @@ -139,8 +145,8 @@ class OTAHandler(BaseHandler): else: self.logger.bind(tag=TAG).warning("缺少MQTT签名密钥,密码留空") - #Build MQTT configuration (using mqtt_gateway string directly) - return_json["mqtt_gateway"] = { + # 构建MQTT配置(直接使用 mqtt_gateway 字符串) + return_json["mqtt"] = { "endpoint": mqtt_gateway_endpoint, "client_id": mqtt_client_id, "username": username, @@ -150,8 +156,8 @@ class OTAHandler(BaseHandler): } self.logger.bind(tag=TAG).info(f"为设备 {device_id} 下发MQTT网关配置") - else: # mqtt_gateway is not configured, and WebSocket is delivered - # If authentication is turned on, perform authentication verification + else: # 未配置 mqtt_gateway,下发 WebSocket + # 如果开启了认证,则进行认证校验 token = "" if self.auth_enable: if self.allowed_devices: @@ -164,7 +170,7 @@ class OTAHandler(BaseHandler): "token": token, } self.logger.bind(tag=TAG).info( - f"The MQTT gateway is not configured, and the WebSocket configuration is delivered to the device {device_id}." + f"未配置MQTT网关,为设备 {device_id} 下发WebSocket配置" ) self.logger.bind(tag=TAG).info(f"{return_json}") diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 4337a488a..0a4bb63b4 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -115,9 +115,9 @@ class ConnectionHandler: # vad相关变量 self.client_audio_buffer = bytearray() self.client_have_voice = False + self.client_voice_window = deque(maxlen=5) self.last_activity_time = 0.0 # 统一的活动时间戳(毫秒) self.client_voice_stop = False - self.client_voice_window = deque(maxlen=5) self.last_is_voice = False # asr相关变量 @@ -446,7 +446,7 @@ class ConnectionHandler: ) if enhanced_prompt: self.change_system_prompt(enhanced_prompt) - self.logger.bind(tag=TAG).info("系统提示词已增强更新") + self.logger.bind(tag=TAG).debug("系统提示词已增强更新") def _init_report_threads(self): """初始化ASR和TTS上报线程""" @@ -798,9 +798,9 @@ class ConnectionHandler: if tools_call is not None and len(tools_call) > 0: tool_call_flag = True - if tools_call[0].id is not None: + if tools_call[0].id is not None and tools_call[0].id != "": function_id = tools_call[0].id - if tools_call[0].function.name is not None: + if tools_call[0].function.name is not None and tools_call[0].function.name != "": function_name = tools_call[0].function.name if tools_call[0].function.arguments is not None: function_arguments += tools_call[0].function.arguments diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py index 75a5c41cc..a8591549e 100644 --- a/main/xiaozhi-server/core/handle/helloHandle.py +++ b/main/xiaozhi-server/core/handle/helloHandle.py @@ -19,15 +19,15 @@ TAG = __name__ WAKEUP_CONFIG = { "refresh_time": 10, "responses": [ - "I'm always here, please tell me.", - "I'm here, please give me orders at any time.", - "Come on, come on, please tell me.", - "Please speak, I am listening.", - "Please speak, I'm ready.", - "Please give the command.", - "I'm listening carefully. Please speak.", - "What help do you need?", - "I'm here, waiting for your instructions.", + "我一直都在呢,您请说。", + "在的呢,请随时吩咐我。", + "来啦来啦,请告诉我吧。", + "您请说,我正听着。", + "请您讲话,我准备好了。", + "请您说出指令吧。", + "我认真听着呢,请讲。", + "请问您需要什么帮助?", + "我在这里,等候您的指令。", ], } @@ -43,15 +43,15 @@ async def handleHelloMessage(conn, msg_json): audio_params = msg_json.get("audio_params") if audio_params: format = audio_params.get("format") - conn.logger.bind(tag=TAG).info(f"Client audio format: {format}") + conn.logger.bind(tag=TAG).debug(f"客户端音频格式: {format}") conn.audio_format = format conn.welcome_msg["audio_params"] = audio_params features = msg_json.get("features") if features: - conn.logger.bind(tag=TAG).info(f"Client features: {features}") + conn.logger.bind(tag=TAG).debug(f"客户端特性: {features}") conn.features = features if features.get("mcp"): - conn.logger.bind(tag=TAG).info("Client supports mcp") + conn.logger.bind(tag=TAG).debug("客户端支持MCP") conn.mcp_client = MCPClient() # Send initialization asyncio.create_task(send_mcp_initialize_message(conn)) @@ -97,7 +97,7 @@ async def checkWakeupWords(conn, text): "voice": "default", "file_path": "config/assets/wakeup_words_short.wav", "time": 0, - "text": "I'm here!", + "text": "我在这里哦!", } # Get audio data @@ -128,7 +128,7 @@ async def wakeupWordsResponse(conn): if not await _wakeup_response_lock.acquire(): return - # Randomly select a reply from a list of predefined replies + # 从预定义回复列表中随机选择一个回复 result = random.choice(WAKEUP_CONFIG["responses"]) if not result or len(result) == 0: return diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 10c3238bd..936dd8d4d 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -13,7 +13,7 @@ TAG = __name__ async def handleAudioMessage(conn, audio): # Is anyone speaking in the current segment? have_voice = conn.vad.is_vad(conn, audio) - # If the device has just been woken up, briefly ignore vad detection + # 如果设备刚刚被唤醒,短暂忽略VAD检测 if hasattr(conn, "just_woken_up") and conn.just_woken_up: have_voice = False # Resume vad detection after setting a short delay @@ -21,7 +21,7 @@ async def handleAudioMessage(conn, audio): if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done(): conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn)) return - # manual Do not interrupt the content being played in mode + # manual 模式下不打断正在播放的内容 if have_voice: if conn.client_is_speaking and conn.client_listen_mode != "manual": await handleAbortMessage(conn) @@ -32,8 +32,8 @@ async def handleAudioMessage(conn, audio): async def resume_vad_detection(conn): - # Wait 2 seconds before resuming vad detection - await asyncio.sleep(1) + # 等待2秒后恢复VAD检测 + await asyncio.sleep(2) conn.just_woken_up = False @@ -74,7 +74,7 @@ async def startToChat(conn, text): ): await max_out_size(conn) return - # manual Do not interrupt the content being played in mode + # manual 模式下不打断正在播放的内容 if conn.client_is_speaking and conn.client_listen_mode != "manual": await handleAbortMessage(conn) diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py index 7dd82bae0..868bb1e5d 100644 --- a/main/xiaozhi-server/core/handle/sendAudioHandle.py +++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py @@ -90,33 +90,47 @@ async def sendAudio(conn, audios, frame_duration=60): if audios is None or len(audios) == 0: return + # 获取发送延迟配置 + send_delay = conn.config.get("tts_audio_send_delay", -1) / 1000.0 + if isinstance(audios, bytes): + # 重置流控状态,第一次读取和会话发生转变时 + if not hasattr(conn, "audio_flow_control") or conn.audio_flow_control.get("sentence_id") != conn.sentence_id: + conn.audio_flow_control = { + "last_send_time": 0, + "packet_count": 0, + "start_time": time.perf_counter(), + "sequence": 0, # 添加序列号 + "sentence_id": conn.sentence_id, + } + if conn.client_abort: return conn.last_activity_time = time.time() * 1000 - # Get or initialize flow control status - if not hasattr(conn, "audio_flow_control"): - conn.audio_flow_control = { - "last_send_time": 0, - "packet_count": 0, - "start_time": time.perf_counter(), - "sequence": 0, # Add serial number - } - + # 预缓冲:前5个包直接发送,不做延迟 + pre_buffer_count = 5 flow_control = conn.audio_flow_control current_time = time.perf_counter() - # Calculate expected delivery time - expected_time = flow_control["start_time"] + ( - flow_control["packet_count"] * frame_duration / 1000 - ) - delay = expected_time - current_time - if delay > 0: - await asyncio.sleep(delay) + + if flow_control["packet_count"] < pre_buffer_count: + # 预缓冲阶段,直接发送不延迟 + pass + elif send_delay > 0: + # 使用固定延迟 + await asyncio.sleep(send_delay) else: - # correct errors - flow_control["start_time"] += abs(delay) + effective_packet = flow_control["packet_count"] - pre_buffer_count + expected_time = flow_control["start_time"] + ( + effective_packet * frame_duration / 1000 + ) + delay = expected_time - current_time + if delay > 0: + await asyncio.sleep(delay) + else: + # 纠正误差 + flow_control["start_time"] += abs(delay) if conn.conn_from_mqtt_gateway: # Calculate timestamps and sequence numbers @@ -141,8 +155,8 @@ async def sendAudio(conn, audios, frame_duration=60): start_time = time.perf_counter() play_position = 0 - # Perform prebuffering - pre_buffer_frames = min(3, len(audios)) + # 执行预缓冲 + pre_buffer_frames = min(5, len(audios)) for i in range(pre_buffer_frames): if conn.conn_from_mqtt_gateway: # Calculate timestamps and sequence numbers @@ -164,12 +178,16 @@ async def sendAudio(conn, audios, frame_duration=60): # Reset no sound status conn.last_activity_time = time.time() * 1000 - # Calculate expected delivery time - expected_time = start_time + (play_position / 1000) - current_time = time.perf_counter() - delay = expected_time - current_time - if delay > 0: - await asyncio.sleep(delay) + if send_delay > 0: + # 固定延迟模式 + await asyncio.sleep(send_delay) + else: + # 计算预期发送时间 + expected_time = start_time + (play_position / 1000) + current_time = time.perf_counter() + delay = expected_time - current_time + if delay > 0: + await asyncio.sleep(delay) if conn.conn_from_mqtt_gateway: # Calculate timestamps and sequence numbers (using current packet index to ensure continuity) diff --git a/main/xiaozhi-server/core/providers/asr/aliyun_stream.py b/main/xiaozhi-server/core/providers/asr/aliyun_stream.py index dc172bc22..e3d658f92 100644 --- a/main/xiaozhi-server/core/providers/asr/aliyun_stream.py +++ b/main/xiaozhi-server/core/providers/asr/aliyun_stream.py @@ -96,7 +96,9 @@ class ASRProvider(ASRProviderBase): self.delete_audio_file = delete_audio_file self.expire_time = None - # Token management + self.task_id = uuid.uuid4().hex + + # Token管理 if self.access_key_id and self.access_key_secret: self._refresh_token() elif not self.token: @@ -169,19 +171,23 @@ class ASRProvider(ASRProviderBase): ping_timeout=None, close_timeout=5, ) - + + self.task_id = uuid.uuid4().hex + + logger.bind(tag=TAG).debug(f"WebSocket连接建立成功, task_id: {self.task_id}") + self.is_processing = True self.server_ready = False # Reset server readiness status self.forward_task = asyncio.create_task(self._forward_results(conn)) - - # Send start request + + # 发送开始请求 start_request = { "header": { "namespace": "SpeechTranscriber", "name": "StartTranscription", "status": 20000000, - "message_id": ''.join(random.choices('0123456789abcdef', k=32)), - "task_id": ''.join(random.choices('0123456789abcdef', k=32)), + "message_id": uuid.uuid4().hex, + "task_id": self.task_id, "status_text": "Gateway:SUCCESS:Success.", "appkey": self.appkey }, @@ -196,7 +202,7 @@ class ASRProvider(ASRProviderBase): } } await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False)) - logger.bind(tag=TAG).info("Start request sent, waiting for server to prepare...") + logger.bind(tag=TAG).debug("已发送开始请求,等待服务器准备...") async def _forward_results(self, conn): """Forward recognition results""" @@ -225,7 +231,7 @@ class ASRProvider(ASRProviderBase): # Receiving transcription started indicates that the server is ready to receive audio data if message_name == "TranscriptionStarted": self.server_ready = True - logger.bind(tag=TAG).info("The server is ready to start sending cached audio...") + logger.bind(tag=TAG).debug("服务器已准备,开始发送缓存音频...") # Send buffered audio if conn.asr_audio: @@ -274,8 +280,8 @@ class ASRProvider(ASRProviderBase): await self._cleanup(conn) async def _cleanup(self, conn): - """Clean up resources""" - logger.bind(tag=TAG).info(f"Start asr session cleanup | Current status: processing={self.is_processing}, server_ready={self.server_ready}") + """清理资源""" + logger.bind(tag=TAG).debug(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}") # Clear connected audio cache if conn and hasattr(conn, 'asr_audio_for_voiceprint'): @@ -292,22 +298,23 @@ class ASRProvider(ASRProviderBase): "namespace": "SpeechTranscriber", "name": "StopTranscription", "status": 20000000, - "message_id": ''.join(random.choices('0123456789abcdef', k=32)), + "message_id": uuid.uuid4().hex, + "task_id": self.task_id, "status_text": "Client:Stop", "appkey": self.appkey } } - logger.bind(tag=TAG).info("Sending asr termination request") + logger.bind(tag=TAG).debug("正在发送ASR终止请求") await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False)) await asyncio.sleep(0.1) - logger.bind(tag=TAG).info("Asr termination request sent") + logger.bind(tag=TAG).debug("ASR终止请求已发送") except Exception as e: logger.bind(tag=TAG).error(f"Asr termination request failed to send: {e}") # Status reset (after termination request sent) self.is_processing = False self.server_ready = False - logger.bind(tag=TAG).info("Asr status has been reset") + logger.bind(tag=TAG).debug("ASR状态已重置") # Cleanup tasks if self.forward_task and not self.forward_task.done(): @@ -330,7 +337,7 @@ class ASRProvider(ASRProviderBase): finally: self.asr_ws = None - logger.bind(tag=TAG).info("Asr session cleanup completed") + logger.bind(tag=TAG).debug("ASR会话清理完成") async def speech_to_text(self, opus_data, session_id, audio_format): """Get recognition results""" diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 250a25f2c..05600b3a9 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -68,7 +68,7 @@ class ASRProviderBase(ABC): conn.asr_audio.clear() conn.reset_vad_states() - if len(asr_audio_task) > 15: + if len(asr_audio_task) > 15 or conn.client_listen_mode == "manual": await self.handle_voice_stop(conn, asr_audio_task) # 处理语音停止 @@ -101,7 +101,7 @@ class ASRProviderBase(ABC): self.speech_to_text(asr_audio_task, conn.session_id, conn.audio_format) ) end_time = time.monotonic() - logger.bind(tag=TAG).info(f"ASR耗时: {end_time - start_time:.3f}s") + logger.bind(tag=TAG).debug(f"ASR耗时: {end_time - start_time:.3f}s") return result finally: loop.close() @@ -158,7 +158,7 @@ class ASRProviderBase(ABC): # 性能监控 total_time = time.monotonic() - total_start_time - logger.bind(tag=TAG).info(f"总处理耗时: {total_time:.3f}s") + logger.bind(tag=TAG).debug(f"总处理耗时: {total_time:.3f}s") # 检查文本长度 text_len, _ = remove_punctuation_and_length(raw_text) diff --git a/main/xiaozhi-server/core/providers/asr/xunfei_stream.py b/main/xiaozhi-server/core/providers/asr/xunfei_stream.py index 7f6964282..e91c8f098 100644 --- a/main/xiaozhi-server/core/providers/asr/xunfei_stream.py +++ b/main/xiaozhi-server/core/providers/asr/xunfei_stream.py @@ -22,6 +22,7 @@ STATUS_FIRST_FRAME = 0 # 第一帧的标识 STATUS_CONTINUE_FRAME = 1 # 中间帧标识 STATUS_LAST_FRAME = 2 # 最后一帧的标识 + class ASRProvider(ASRProviderBase): def __init__(self, config, delete_audio_file): super().__init__() @@ -35,6 +36,7 @@ class ASRProvider(ASRProviderBase): self.server_ready = False self.last_frame_sent = False # 标记是否已发送最终帧 self.best_text = "" # 保存最佳识别结果 + self.has_final_result = False # 标记是否收到最终识别结果 # 讯飞配置 self.app_id = config.get("app_id") @@ -50,19 +52,15 @@ class ASRProvider(ASRProviderBase): "language": config.get("language", "zh_cn"), "accent": config.get("accent", "mandarin"), "dwa": config.get("dwa", "wpgs"), - "result": { - "encoding": "utf8", - "compress": "raw", - "format": "plain" - } + "result": {"encoding": "utf8", "compress": "raw", "format": "plain"}, } self.output_dir = config.get("output_dir", "tmp/") self.delete_audio_file = delete_audio_file - + def create_url(self) -> str: """生成认证URL""" - url = 'ws://iat.cn-huabei-1.xf-yun.com/v1' + url = "ws://iat.cn-huabei-1.xf-yun.com/v1" # 生成RFC1123格式的时间戳 now = datetime.now() date = format_date_time(mktime(now.timetuple())) @@ -73,23 +71,30 @@ class ASRProvider(ASRProviderBase): signature_origin += "GET " + "/v1 " + "HTTP/1.1" # 进行hmac-sha256进行加密 - signature_sha = hmac.new(self.api_secret.encode('utf-8'), signature_origin.encode('utf-8'), - digestmod=hashlib.sha256).digest() - signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8') + signature_sha = hmac.new( + self.api_secret.encode("utf-8"), + signature_origin.encode("utf-8"), + digestmod=hashlib.sha256, + ).digest() + signature_sha = base64.b64encode(signature_sha).decode(encoding="utf-8") - authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % ( - self.api_key, "hmac-sha256", "host date request-line", signature_sha) - authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8') + authorization_origin = ( + 'api_key="%s", algorithm="%s", headers="%s", signature="%s"' + % (self.api_key, "hmac-sha256", "host date request-line", signature_sha) + ) + authorization = base64.b64encode(authorization_origin.encode("utf-8")).decode( + encoding="utf-8" + ) # 将请求的鉴权参数组合为字典 v = { "authorization": authorization, "date": date, - "host": "iat.cn-huabei-1.xf-yun.com" + "host": "iat.cn-huabei-1.xf-yun.com", } # 拼接鉴权参数,生成url - url = url + '?' + urlencode(v) + url = url + "?" + urlencode(v) return url async def open_audio_channels(self, conn): @@ -100,7 +105,7 @@ class ASRProvider(ASRProviderBase): await super().receive_audio(conn, audio, audio_have_voice) # 存储音频数据用于声纹识别 - if not hasattr(conn, 'asr_audio_for_voiceprint'): + if not hasattr(conn, "asr_audio_for_voiceprint"): conn.asr_audio_for_voiceprint = [] conn.asr_audio_for_voiceprint.append(audio) @@ -146,8 +151,10 @@ class ASRProvider(ASRProviderBase): # 发送首帧音频 if conn.asr_audio and len(conn.asr_audio) > 0: - first_audio = conn.asr_audio[-1] if conn.asr_audio else b'' - pcm_frame = self.decoder.decode(first_audio, 960) if first_audio else b'' + first_audio = conn.asr_audio[-1] if conn.asr_audio else b"" + pcm_frame = ( + self.decoder.decode(first_audio, 960) if first_audio else b"" + ) await self._send_audio_frame(pcm_frame, STATUS_FIRST_FRAME) self.server_ready = True logger.bind(tag=TAG).info("已发送首帧,开始识别") @@ -176,23 +183,14 @@ class ASRProvider(ASRProviderBase): if not self.asr_ws: return - audio_b64 = base64.b64encode(audio_data).decode('utf-8') + audio_b64 = base64.b64encode(audio_data).decode("utf-8") frame_data = { - "header": { - "status": status, - "app_id": self.app_id - }, - "parameter": { - "iat": self.iat_params - }, + "header": {"status": status, "app_id": self.app_id}, + "parameter": {"iat": self.iat_params}, "payload": { - "audio": { - "audio": audio_b64, - "sample_rate": 16000, - "encoding": "raw" - } - } + "audio": {"audio": audio_b64, "sample_rate": 16000, "encoding": "raw"} + }, } await self.asr_ws.send(json.dumps(frame_data, ensure_ascii=False)) @@ -207,11 +205,13 @@ class ASRProvider(ASRProviderBase): try: while self.asr_ws and not conn.stop_event.is_set(): # 获取当前连接的音频数据 - audio_data = getattr(conn, 'asr_audio_for_voiceprint', []) + audio_data = getattr(conn, "asr_audio_for_voiceprint", []) try: # 如果已发送最终帧,增加超时时间等待完整结果 timeout = 3.0 if self.last_frame_sent else 30.0 - response = await asyncio.wait_for(self.asr_ws.recv(), timeout=timeout) + response = await asyncio.wait_for( + self.asr_ws.recv(), timeout=timeout + ) result = json.loads(response) logger.bind(tag=TAG).debug(f"收到ASR结果: {result}") @@ -221,7 +221,9 @@ class ASRProvider(ASRProviderBase): status = header.get("status", 0) if code != 0: - logger.bind(tag=TAG).error(f"识别错误,错误码: {code}, 消息: {header.get('message', '')}") + logger.bind(tag=TAG).error( + f"识别错误,错误码: {code}, 消息: {header.get('message', '')}" + ) if code in [10114, 10160]: # 连接问题 break continue @@ -231,52 +233,124 @@ class ASRProvider(ASRProviderBase): text_data = payload["result"]["text"] if text_data: # 解码base64文本 - decoded_text = base64.b64decode(text_data).decode('utf-8') + decoded_text = base64.b64decode(text_data).decode("utf-8") text_json = json.loads(decoded_text) # 提取文本内容 - text_ws = text_json.get('ws', []) - result_text = '' + text_ws = text_json.get("ws", []) + result_text = "" for i in text_ws: for j in i.get("cw", []): w = j.get("w", "") result_text += w # 更新识别文本 - 实时更新策略 - if result_text and result_text.strip() not in ['', '。', '.', ',', ',']: + # 只检查是否为空字符串,不再过滤任何标点符号 + # 这样可以确保所有识别到的内容,包括标点符号都能被实时更新 + if result_text and result_text.strip(): # 实时更新:正常情况下都更新,提高响应速度 should_update = True - # 保存最佳文本(最长的有意义文本) - if (len(result_text) > len(self.best_text) and - result_text.strip() not in ['?', '?', '。', '.']): - self.best_text = result_text - logger.bind(tag=TAG).debug(f"保存最佳文本: {self.best_text}") + # 保存最佳文本 + # 1. 如果是识别完成状态或最终帧后收到的结果,优先保存 + # 2. 否则保存最长的有意义文本 + # 取消对标点符号的过滤,只检查是否为空 + # 这样可以保留所有识别到的内容,包括各种标点符号 + is_valid_text = len(result_text.strip()) > 0 - # 如果已发送最终帧,只过滤明显的无效结果 + if ( + self.last_frame_sent or status == 2 + ) and is_valid_text: + self.best_text = result_text + self.has_final_result = True # 标记已收到最终结果 + logger.bind(tag=TAG).debug( + f"保存最终识别结果: {self.best_text}" + ) + elif ( + len(result_text) > len(self.best_text) + and is_valid_text + and not self.has_final_result + ): + self.best_text = result_text + logger.bind(tag=TAG).debug( + f"保存中间最佳文本: {self.best_text}" + ) + + # 如果已发送最终帧,只过滤空文本 if self.last_frame_sent: - # 最终帧后拒绝问号等明显错误的结果 - if result_text.strip() in ['?', '?', '。', '.']: + # 只拒绝完全空的结果 + if not result_text.strip(): should_update = False - logger.bind(tag=TAG).warning(f"最终帧后拒绝无效文本: {result_text}") + logger.bind(tag=TAG).warning( + f"最终帧后拒绝空文本" + ) if should_update: - self.text = result_text - logger.bind(tag=TAG).info(f"实时更新识别文本: {self.text} (最终帧已发送: {self.last_frame_sent})") + # 处理流式识别结果,避免简单替换导致内容丢失 + # 1. 如果是中间状态(非最终帧后),可能需要替换为更完整的识别 + # 2. 如果是最终帧后收到的结果,可能是对前面文本的补充 + if self.last_frame_sent: + # 最终帧后收到的结果可能是标点符号等补充内容 + # 检查是否需要合并文本而不是替换 + # 如果当前文本是纯标点而前面已有内容,应该追加而不是替换 + if len( + self.text + ) > 0 and result_text.strip() in [ + "。", + ".", + "?", + "?", + "!", + "!", + ",", + ",", + ";", + ";", + ]: + # 对于标点符号,追加到现有文本后 + self.text = ( + self.text.rstrip().rstrip("。.") + + result_text + ) + else: + # 其他情况保持替换逻辑 + self.text = result_text + else: + # 中间状态替换为新的识别结果 + self.text = result_text + + logger.bind(tag=TAG).info( + f"实时更新识别文本: {self.text} (最终帧已发送: {self.last_frame_sent})" + ) # 识别完成,但如果还没发送最终帧,继续等待 if status == 2: - logger.bind(tag=TAG).info(f"识别完成状态已到达,当前识别文本: {self.text}") + logger.bind(tag=TAG).info( + f"识别完成状态已到达,当前识别文本: {self.text}" + ) # 如果还没发送最终帧,继续等待 if not self.last_frame_sent: - logger.bind(tag=TAG).info("识别完成但最终帧未发送,继续等待...") + logger.bind(tag=TAG).info( + "识别完成但最终帧未发送,继续等待..." + ) continue - # 已发送最终帧且收到完成状态,使用最佳文本作为最终结果 - if self.best_text and len(self.best_text) > len(self.text): - logger.bind(tag=TAG).info(f"使用最佳文本作为最终结果: {self.text} -> {self.best_text}") - self.text = self.best_text + # 已发送最终帧且收到完成状态,使用最佳策略选择最终结果 + # 优先使用识别完成状态下的最新结果,而不是仅仅基于长度 + if self.best_text: + # 如果当前文本是在最终帧发送后或识别完成状态下收到的,优先使用 + if ( + self.last_frame_sent or status == 2 + ) and self.text.strip(): + logger.bind(tag=TAG).info( + f"使用完成状态下的最新识别结果: {self.text}" + ) + elif len(self.best_text) > len(self.text): + logger.bind(tag=TAG).info( + f"使用更长的最佳文本作为最终结果: {self.text} -> {self.best_text}" + ) + self.text = self.best_text logger.bind(tag=TAG).info(f"获取到最终完整文本: {self.text}") conn.reset_vad_states() @@ -289,9 +363,13 @@ class ASRProvider(ASRProviderBase): if self.last_frame_sent: # 超时时也使用最佳文本 if self.best_text and len(self.best_text) > len(self.text): - logger.bind(tag=TAG).info(f"超时,使用最佳文本: {self.text} -> {self.best_text}") + logger.bind(tag=TAG).info( + f"超时,使用最佳文本: {self.text} -> {self.best_text}" + ) self.text = self.best_text - logger.bind(tag=TAG).info(f"最终帧后超时,使用结果: {self.text}") + logger.bind(tag=TAG).info( + f"最终帧后超时,使用结果: {self.text}" + ) break # 如果还没发送最终帧,继续等待 continue @@ -316,11 +394,11 @@ class ASRProvider(ASRProviderBase): self.asr_ws = None self.is_processing = False if conn: - if hasattr(conn, 'asr_audio_for_voiceprint'): + if hasattr(conn, "asr_audio_for_voiceprint"): conn.asr_audio_for_voiceprint = [] - if hasattr(conn, 'asr_audio'): + if hasattr(conn, "asr_audio"): conn.asr_audio = [] - if hasattr(conn, 'has_valid_voice'): + if hasattr(conn, "has_valid_voice"): conn.has_valid_voice = False async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]): @@ -330,7 +408,7 @@ class ASRProvider(ASRProviderBase): if self.asr_ws and self.is_processing: try: # 取最后一个有效的音频帧作为最后一帧数据 - last_frame = b'' + last_frame = b"" if asr_audio_task: last_audio = asr_audio_task[-1] last_frame = self.decoder.decode(last_audio, 960) @@ -338,8 +416,7 @@ class ASRProvider(ASRProviderBase): logger.bind(tag=TAG).info("已发送最后一帧") # 发送最终帧后,给_forward_results适当时间处理最终结果 - # 减少等待时间,提高响应速度 - await asyncio.sleep(0.1) # 从3秒减少到1秒 + await asyncio.sleep(0.25) logger.bind(tag=TAG).info(f"准备处理最终识别结果: {self.text}") except Exception as e: @@ -350,8 +427,9 @@ class ASRProvider(ASRProviderBase): except Exception as e: logger.bind(tag=TAG).error(f"处理语音停止失败: {e}") import traceback + logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}") - + def stop_ws_connection(self): if self.asr_ws: asyncio.create_task(self.asr_ws.close()) @@ -360,12 +438,14 @@ class ASRProvider(ASRProviderBase): async def _cleanup(self, conn): """清理资源""" - logger.bind(tag=TAG).info(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}") + logger.bind(tag=TAG).info( + f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}" + ) # 发送最后一帧 if self.asr_ws and self.is_processing: try: - await self._send_audio_frame(b'', STATUS_LAST_FRAME) + await self._send_audio_frame(b"", STATUS_LAST_FRAME) await asyncio.sleep(0.1) logger.bind(tag=TAG).info("已发送最后一帧") except Exception as e: @@ -376,6 +456,7 @@ class ASRProvider(ASRProviderBase): self.server_ready = False self.last_frame_sent = False self.best_text = "" + self.has_final_result = False logger.bind(tag=TAG).info("ASR状态已重置") # 清理任务 @@ -403,11 +484,11 @@ class ASRProvider(ASRProviderBase): # 清理连接的音频缓存 if conn: - if hasattr(conn, 'asr_audio_for_voiceprint'): + if hasattr(conn, "asr_audio_for_voiceprint"): conn.asr_audio_for_voiceprint = [] - if hasattr(conn, 'asr_audio'): + if hasattr(conn, "asr_audio"): conn.asr_audio = [] - if hasattr(conn, 'has_valid_voice'): + if hasattr(conn, "has_valid_voice"): conn.has_valid_voice = False logger.bind(tag=TAG).info("ASR会话清理完成") @@ -432,11 +513,11 @@ class ASRProvider(ASRProviderBase): self.forward_task = None self.is_processing = False # 清理所有连接的音频缓冲区 - if hasattr(self, '_connections'): + if hasattr(self, "_connections"): for conn in self._connections.values(): - if hasattr(conn, 'asr_audio_for_voiceprint'): + if hasattr(conn, "asr_audio_for_voiceprint"): conn.asr_audio_for_voiceprint = [] - if hasattr(conn, 'asr_audio'): + if hasattr(conn, "asr_audio"): conn.asr_audio = [] - if hasattr(conn, 'has_valid_voice'): - conn.has_valid_voice = False \ No newline at end of file + if hasattr(conn, "has_valid_voice"): + conn.has_valid_voice = False diff --git a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py index 8d426d085..73ab843ac 100644 --- a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py +++ b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py @@ -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}") diff --git a/main/xiaozhi-server/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py index 5c85c6478..2863c4204 100644 --- a/main/xiaozhi-server/core/providers/llm/openai/openai.py +++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py @@ -17,27 +17,26 @@ class LLMProvider(LLMProviderBase): self.base_url = config.get("base_url") else: self.base_url = config.get("url") - # 增加timeout的配置项,单位为秒 timeout = config.get("timeout", 300) 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}" @@ -48,34 +47,46 @@ class LLMProvider(LLMProviderBase): logger.bind(tag=TAG).error(model_key_msg) self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url, timeout=httpx.Timeout(self.timeout)) + @staticmethod + def normalize_dialogue(dialogue): + """自动修复 dialogue 中缺失 content 的消息""" + for msg in dialogue: + if "role" in msg and "content" not in msg: + msg["content"] = "" + return dialogue + def response(self, session_id, dialogue, **kwargs): try: - 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 - ), - ) + dialogue = self.normalize_dialogue(dialogue) + + 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: try: - # 检查是否存在有效的choice且content不为空 - delta = ( - chunk.choices[0].delta - if getattr(chunk, "choices", None) - else None - ) - content = delta.content if hasattr(delta, "content") else "" + delta = chunk.choices[0].delta if getattr(chunk, "choices", None) else None + content = getattr(delta, "content", "") if delta else "" except IndexError: content = "" if content: - # 处理标签跨多个chunk的情况 if "" in content: is_active = False content = content.split("")[0] @@ -88,19 +99,36 @@ 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: - stream = self.client.chat.completions.create( - model=self.model_name, messages=dialogue, stream=True, tools=functions - ) + dialogue = self.normalize_dialogue(dialogue) + + 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: - # 检查是否存在有效的choice且content不为空 if getattr(chunk, "choices", None): - yield chunk.choices[0].delta.content, chunk.choices[ - 0 - ].delta.tool_calls - # 存在 CompletionUsage 消息时,生成 Token 消耗 log + delta = chunk.choices[0].delta + content = getattr(delta, "content", "") + tool_calls = getattr(delta, "tool_calls", None) + yield content, tool_calls elif isinstance(getattr(chunk, "usage", None), CompletionUsage): usage_info = getattr(chunk, "usage", None) logger.bind(tag=TAG).info( diff --git a/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py b/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py index d61d73f3e..530aa3171 100644 --- a/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py +++ b/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py @@ -42,7 +42,7 @@ class MemoryProvider(MemoryProviderBase): if message.role != "system" ] result = self.client.add( - messages, user_id=self.role_id, output_format=self.api_version + messages, user_id=self.role_id ) logger.bind(tag=TAG).debug(f"Save memory result: {result}") except Exception as e: @@ -53,9 +53,12 @@ class MemoryProvider(MemoryProviderBase): if not self.use_mem0: return "" try: - results = self.client.search( - query, user_id=self.role_id, output_format=self.api_version - ) + if not getattr(self, "role_id", None): + return "" + + filters = {"user_id": self.role_id} + + results = self.client.search(query, filters=filters) if not results or "results" not in results: return "" diff --git a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py index c1b4d6c85..457b22fc8 100644 --- a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py +++ b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py @@ -106,14 +106,14 @@ async def send_mcp_message(conn, payload: dict): try: await conn.websocket.send(message) - logger.bind(tag=TAG).info(f"成功发送MCP消息: {message}") + logger.bind(tag=TAG).debug(f"成功发送MCP消息: {message}") except Exception as e: logger.bind(tag=TAG).error(f"发送MCP消息失败: {e}") async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict): """处理MCP消息,包括初始化、工具列表和工具调用响应等""" - logger.bind(tag=TAG).info(f"处理MCP消息: {str(payload)[:100]}") + logger.bind(tag=TAG).debug(f"处理MCP消息: {str(payload)[:100]}") if not isinstance(payload, dict): logger.bind(tag=TAG).error("MCP消息缺少payload字段或格式错误") @@ -138,7 +138,7 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict): if isinstance(server_info, dict): name = server_info.get("name") version = server_info.get("version") - logger.bind(tag=TAG).info( + logger.bind(tag=TAG).debug( f"客户端MCP服务器信息: name={name}, version={version}" ) return @@ -195,11 +195,11 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict): next_cursor = result.get("nextCursor", "") if next_cursor: - logger.bind(tag=TAG).info(f"有更多工具,nextCursor: {next_cursor}") + logger.bind(tag=TAG).debug(f"有更多工具,nextCursor: {next_cursor}") await send_mcp_tools_list_continue_request(conn, next_cursor) else: await mcp_client.set_ready(True) - logger.bind(tag=TAG).info("所有工具已获取,MCP客户端准备就绪") + logger.bind(tag=TAG).debug("所有工具已获取,MCP客户端准备就绪") # 刷新工具缓存,确保MCP工具被包含在函数列表中 if hasattr(conn, "func_handler") and conn.func_handler: @@ -255,7 +255,7 @@ async def send_mcp_initialize_message(conn): }, }, } - logger.bind(tag=TAG).info("发送MCP初始化消息") + logger.bind(tag=TAG).debug("发送MCP初始化消息") await send_mcp_message(conn, payload) diff --git a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_handler.py b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_handler.py index c6afb07ba..8d9921cda 100644 --- a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_handler.py +++ b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_handler.py @@ -358,7 +358,9 @@ async def call_mcp_endpoint_tool( } message = json.dumps(payload) - logger.bind(tag=TAG).info(f"发送MCP接入点工具调用请求: {actual_name},参数: {args}") + logger.bind(tag=TAG).info( + f"发送MCP接入点工具调用请求: {actual_name},参数: {json.dumps(arguments, ensure_ascii=False)}" + ) await mcp_client.send_message(message) try: diff --git a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py index 6dd141959..c1126a646 100644 --- a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py +++ b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py @@ -13,6 +13,7 @@ from typing import Optional, List, Dict, Any from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from mcp.client.sse import sse_client +from mcp.client.streamable_http import streamablehttp_client from config.logger import setup_logging from core.utils.util import sanitize_tool_name @@ -172,10 +173,33 @@ class ServerMCPClient: if "API_ACCESS_TOKEN" in self.config: headers["Authorization"] = f"Bearer {self.config['API_ACCESS_TOKEN']}" self.logger.bind(tag=TAG).warning(f"你正在使用旧过时的配置 API_ACCESS_TOKEN ,请在.mcp_server_settings.json中将API_ACCESS_TOKEN直接设置在headers中,例如 'Authorization': 'Bearer API_ACCESS_TOKEN'") - sse_r, sse_w = await stack.enter_async_context( - sse_client(self.config["url"], headers=headers, timeout=self.config.get("timeout", 5), sse_read_timeout=self.config.get("sse_read_timeout", 60 * 5)) - ) - read_stream, write_stream = sse_r, sse_w + + # 根据transport类型选择不同的客户端,默认为SSE + transport_type = self.config.get("transport", "sse") + + if transport_type == "streamable-http" or transport_type == "http": + # 使用 Streamable HTTP 传输 + http_r, http_w, get_session_id = await stack.enter_async_context( + streamablehttp_client( + url=self.config["url"], + headers=headers, + timeout=self.config.get("timeout", 30), + sse_read_timeout=self.config.get("sse_read_timeout", 60 * 5), + terminate_on_close=self.config.get("terminate_on_close", True) + ) + ) + read_stream, write_stream = http_r, http_w + else: + # 使用传统的 SSE 传输 + sse_r, sse_w = await stack.enter_async_context( + sse_client( + url=self.config["url"], + headers=headers, + timeout=self.config.get("timeout", 5), + sse_read_timeout=self.config.get("sse_read_timeout", 60 * 5) + ) + ) + read_stream, write_stream = sse_r, sse_w else: raise ValueError("MCP客户端配置必须包含'command'或'url'") diff --git a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py index 17d3b564b..6c61eacd1 100644 --- a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py +++ b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py @@ -71,6 +71,19 @@ class ServerPluginExecutor(ToolExecutor): for func_name in all_required_functions: func_item = all_function_registry.get(func_name) if func_item: + # 从函数注册中获取描述 + fun_description = ( + self.config.get("plugins", {}) + .get(func_name, {}) + .get("description", "") + ) + if fun_description is not None and len(fun_description) > 0: + if "function" in func_item.description and isinstance( + func_item.description["function"], dict + ): + func_item.description["function"][ + "description" + ] = fun_description tools[func_name] = ToolDefinition( name=func_name, description=func_item.description, diff --git a/main/xiaozhi-server/core/providers/tools/unified_tool_handler.py b/main/xiaozhi-server/core/providers/tools/unified_tool_handler.py index b81029aca..6f2896325 100644 --- a/main/xiaozhi-server/core/providers/tools/unified_tool_handler.py +++ b/main/xiaozhi-server/core/providers/tools/unified_tool_handler.py @@ -69,7 +69,7 @@ class UnifiedToolHandler: self._initialize_home_assistant() self.finish_init = True - self.logger.info("统一工具处理器初始化完成") + self.logger.debug("统一工具处理器初始化完成") # 输出当前支持的所有工具列表 self.current_support_functions() diff --git a/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py b/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py index e2a918693..f69a6dc39 100644 --- a/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py +++ b/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py @@ -20,7 +20,7 @@ class ToolManager: """注册工具执行器""" self.executors[tool_type] = executor self._invalidate_cache() - self.logger.info(f"注册工具执行器: {tool_type.value}") + self.logger.debug(f"注册工具执行器: {tool_type.value}") def _invalidate_cache(self): """使缓存失效""" @@ -109,7 +109,7 @@ class ToolManager: def refresh_tools(self): """刷新工具缓存""" self._invalidate_cache() - self.logger.info("工具缓存已刷新") + self.logger.debug("工具缓存已刷新") def get_tool_statistics(self) -> Dict[str, int]: """获取工具统计信息""" diff --git a/main/xiaozhi-server/core/providers/tts/aliyun_stream.py b/main/xiaozhi-server/core/providers/tts/aliyun_stream.py index 9178e2d30..bcbf2b401 100644 --- a/main/xiaozhi-server/core/providers/tts/aliyun_stream.py +++ b/main/xiaozhi-server/core/providers/tts/aliyun_stream.py @@ -1,3 +1,4 @@ +import random import uuid import json import hmac @@ -131,7 +132,7 @@ class TTSProvider(TTSProviderBase): self.last_active_time = None # 专属tts设置 - self.message_id = "" + self.task_id = uuid.uuid4().hex # 创建Opus编码器 self.opus_encoder = opus_encoder_utils.OpusEncoderUtils( @@ -185,9 +186,10 @@ class TTSProvider(TTSProviderBase): current_time = time.time() if self.ws and current_time - self.last_active_time < 10: # 10秒内才可以复用链接进行连续对话 - logger.bind(tag=TAG).info(f"使用已有链接...") + self.task_id = uuid.uuid4().hex + logger.bind(tag=TAG).info(f"使用已有链接..., task_id: {self.task_id}") return self.ws - logger.bind(tag=TAG).info("开始建立新连接...") + logger.bind(tag=TAG).debug("开始建立新连接...") self.ws = await websockets.connect( self.ws_url, @@ -196,7 +198,8 @@ class TTSProvider(TTSProviderBase): ping_timeout=10, close_timeout=10, ) - logger.bind(tag=TAG).info("WebSocket连接建立成功") + self.task_id = uuid.uuid4().hex + logger.bind(tag=TAG).debug(f"WebSocket连接建立成功, task_id: {self.task_id}") self.last_active_time = time.time() return self.ws except Exception as e: @@ -224,23 +227,14 @@ class TTSProvider(TTSProviderBase): if message.sentence_type == SentenceType.FIRST: # 初始化参数 try: - if not getattr(self.conn, "sentence_id", None): - self.conn.sentence_id = uuid.uuid4().hex - logger.bind(tag=TAG).info( - f"自动生成新的 会话ID: {self.conn.sentence_id}" - ) - - # aliyunStream独有的参数生成 - self.message_id = str(uuid.uuid4().hex) - - logger.bind(tag=TAG).info("开始启动TTS会话...") + logger.bind(tag=TAG).debug("开始启动TTS会话...") future = asyncio.run_coroutine_threadsafe( - self.start_session(self.conn.sentence_id), + self.start_session(self.task_id), loop=self.conn.loop, ) future.result() self.before_stop_play_files.clear() - logger.bind(tag=TAG).info("TTS会话启动成功") + logger.bind(tag=TAG).debug("TTS会话启动成功") except Exception as e: logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}") @@ -271,9 +265,9 @@ class TTSProvider(TTSProviderBase): self._process_audio_file_stream(message.content_file, callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail)) if message.sentence_type == SentenceType.LAST: try: - logger.bind(tag=TAG).info("开始结束TTS会话...") + logger.bind(tag=TAG).debug("开始结束TTS会话...") future = asyncio.run_coroutine_threadsafe( - self.finish_session(self.conn.sentence_id), + self.finish_session(self.task_id), loop=self.conn.loop, ) future.result() @@ -296,8 +290,8 @@ class TTSProvider(TTSProviderBase): filtered_text = MarkdownCleaner.clean_markdown(text) run_request = { "header": { - "message_id": self.message_id, - "task_id": self.conn.sentence_id, + "message_id": uuid.uuid4().hex, + "task_id": self.task_id, "namespace": "FlowingSpeechSynthesizer", "name": "RunSynthesis", "appkey": self.appkey, @@ -318,8 +312,8 @@ class TTSProvider(TTSProviderBase): self.ws = None raise - async def start_session(self, session_id): - logger.bind(tag=TAG).info(f"开始会话~~{session_id}") + async def start_session(self, task_id): + logger.bind(tag=TAG).debug("开始会话~~") try: # 会话开始时检测上个会话的监听状态 if ( @@ -340,8 +334,8 @@ class TTSProvider(TTSProviderBase): start_request = { "header": { - "message_id": self.message_id, - "task_id": self.conn.sentence_id, + "message_id": uuid.uuid4().hex, + "task_id": self.task_id, "namespace": "FlowingSpeechSynthesizer", "name": "StartSynthesis", "appkey": self.appkey, @@ -358,28 +352,28 @@ class TTSProvider(TTSProviderBase): } await self.ws.send(json.dumps(start_request)) self.last_active_time = time.time() - logger.bind(tag=TAG).info("会话启动请求已发送") + logger.bind(tag=TAG).debug("会话启动请求已发送") except Exception as e: logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}") # 确保清理资源 await self.close() raise - async def finish_session(self, session_id): - logger.bind(tag=TAG).info(f"关闭会话~~{session_id}") + async def finish_session(self, task_id): + logger.bind(tag=TAG).debug(f"关闭会话~~{task_id}") try: if self.ws: stop_request = { "header": { - "message_id": self.message_id, - "task_id": self.conn.sentence_id, + "message_id": uuid.uuid4().hex, + "task_id": self.task_id, "namespace": "FlowingSpeechSynthesizer", "name": "StopSynthesis", "appkey": self.appkey, } } await self.ws.send(json.dumps(stop_request)) - logger.bind(tag=TAG).info("会话结束请求已发送") + logger.bind(tag=TAG).debug("会话结束请求已发送") self.last_active_time = time.time() if self._monitor_task: try: @@ -484,8 +478,6 @@ class TTSProvider(TTSProviderBase): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) - # 生成会话ID - session_id = uuid.uuid4().hex # 存储音频数据 audio_data = [] @@ -504,11 +496,10 @@ class TTSProvider(TTSProviderBase): ) try: # 发送StartSynthesis请求 - start_message_id = str(uuid.uuid4().hex) start_request = { "header": { - "message_id": start_message_id, - "task_id": session_id, + "message_id": uuid.uuid4().hex, + "task_id": self.task_id, "namespace": "FlowingSpeechSynthesizer", "name": "StartSynthesis", "appkey": self.appkey, @@ -549,11 +540,10 @@ class TTSProvider(TTSProviderBase): # 发送文本合成请求 filtered_text = MarkdownCleaner.clean_markdown(text) - run_message_id = str(uuid.uuid4().hex) run_request = { "header": { - "message_id": run_message_id, - "task_id": session_id, + "message_id": uuid.uuid4().hex, + "task_id": self.task_id, "namespace": "FlowingSpeechSynthesizer", "name": "RunSynthesis", "appkey": self.appkey, @@ -563,11 +553,10 @@ class TTSProvider(TTSProviderBase): await ws.send(json.dumps(run_request)) # 发送停止合成请求 - stop_message_id = str(uuid.uuid4().hex) stop_request = { "header": { - "message_id": stop_message_id, - "task_id": session_id, + "message_id": uuid.uuid4().hex, + "task_id": self.task_id, "namespace": "FlowingSpeechSynthesizer", "name": "StopSynthesis", "appkey": self.appkey, diff --git a/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py b/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py index 45cc59679..4c761ac2e 100644 --- a/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py +++ b/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py @@ -149,6 +149,7 @@ class TTSProvider(TTSProviderBase): self.access_token = config.get("access_token") self.cluster = config.get("cluster") self.resource_id = config.get("resource_id") + self.activate_session = False if config.get("private_voice"): self.voice = config.get("private_voice") else: @@ -180,12 +181,12 @@ class TTSProvider(TTSProviderBase): raise async def _ensure_connection(self): - """建立新的WebSocket连接""" + """建立新的WebSocket连接,并启动监听任务(仅第一次)""" try: if self.ws: logger.bind(tag=TAG).info(f"使用已有链接...") return self.ws - logger.bind(tag=TAG).info("开始建立新连接...") + logger.bind(tag=TAG).debug("开始建立新连接...") ws_header = { "X-Api-App-Key": self.appId, "X-Api-Access-Key": self.access_token, @@ -195,7 +196,13 @@ class TTSProvider(TTSProviderBase): self.ws = await websockets.connect( self.ws_url, additional_headers=ws_header, max_size=1000000000 ) - logger.bind(tag=TAG).info("WebSocket连接建立成功") + logger.bind(tag=TAG).debug("WebSocket连接建立成功") + + # 连接建立成功后,启动监听任务 + if self._monitor_task is None or self._monitor_task.done(): + logger.bind(tag=TAG).debug("启动监听任务...") + self._monitor_task = asyncio.create_task(self._start_monitor_tts_response()) + return self.ws except Exception as e: logger.bind(tag=TAG).error(f"建立连接失败: {str(e)}") @@ -231,16 +238,16 @@ class TTSProvider(TTSProviderBase): try: if not getattr(self.conn, "sentence_id", None): self.conn.sentence_id = uuid.uuid4().hex - logger.bind(tag=TAG).info(f"自动生成新的 会话ID: {self.conn.sentence_id}") + logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}") - logger.bind(tag=TAG).info("开始启动TTS会话...") + logger.bind(tag=TAG).debug("开始启动TTS会话...") future = asyncio.run_coroutine_threadsafe( self.start_session(self.conn.sentence_id), loop=self.conn.loop, ) future.result() self.before_stop_play_files.clear() - logger.bind(tag=TAG).info("TTS会话启动成功") + logger.bind(tag=TAG).debug("TTS会话启动成功") except Exception as e: logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}") continue @@ -270,7 +277,7 @@ class TTSProvider(TTSProviderBase): self._process_audio_file_stream(message.content_file, callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail)) if message.sentence_type == SentenceType.LAST: try: - logger.bind(tag=TAG).info("开始结束TTS会话...") + logger.bind(tag=TAG).debug("开始结束TTS会话...") future = asyncio.run_coroutine_threadsafe( self.finish_session(self.conn.sentence_id), loop=self.conn.loop, @@ -313,23 +320,25 @@ class TTSProvider(TTSProviderBase): raise async def start_session(self, session_id): - logger.bind(tag=TAG).info(f"开始会话~~{session_id}") - try: - # 会话开始时检测上个会话的监听状态 - if ( - self._monitor_task is not None - and isinstance(self._monitor_task, Task) - and not self._monitor_task.done() - ): - logger.bind(tag=TAG).info("检测到未完成的上个会话,关闭监听任务和连接...") + logger.bind(tag=TAG).debug(f"开始会话~~{session_id}") + try: + # 等待上一个会话结束,最多等待3次 + for _ in range(3): + if not self.activate_session: + break + logger.bind(tag=TAG).debug(f"等待上一个会话结束...") + await asyncio.sleep(0.1) + else: + # 等待超时,强制清除连接状态 + logger.bind(tag=TAG).debug("等待上一个会话超时,清除连接状态...") await self.close() - - # 建立新连接 + + # 设置会话激活标志 + self.activate_session = True + + # 确保连接建立 await self._ensure_connection() - # 启动监听任务 - self._monitor_task = asyncio.create_task(self._start_monitor_tts_response()) - header = Header( message_type=FULL_CLIENT_REQUEST, message_type_specific_flags=MsgTypeFlagWithEvent, @@ -342,7 +351,7 @@ class TTSProvider(TTSProviderBase): event=EVENT_StartSession, speaker=self.voice ) await self.send_event(self.ws, header, optional, payload) - logger.bind(tag=TAG).info("会话启动请求已发送") + logger.bind(tag=TAG).debug("会话启动请求已发送") except Exception as e: logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}") # 确保清理资源 @@ -350,7 +359,7 @@ class TTSProvider(TTSProviderBase): raise async def finish_session(self, session_id): - logger.bind(tag=TAG).info(f"关闭会话~~{session_id}") + logger.bind(tag=TAG).debug(f"关闭会话~~{session_id}") try: if self.ws: header = Header( @@ -363,18 +372,7 @@ class TTSProvider(TTSProviderBase): ).as_bytes() payload = str.encode("{}") await self.send_event(self.ws, header, optional, payload) - logger.bind(tag=TAG).info("会话结束请求已发送") - - # 等待监听任务完成 - if self._monitor_task: - try: - await self._monitor_task - except Exception as e: - logger.bind(tag=TAG).error( - f"等待监听任务完成时发生错误: {str(e)}" - ) - finally: - self._monitor_task = None + logger.bind(tag=TAG).debug("会话结束请求已发送") except Exception as e: logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}") @@ -383,7 +381,7 @@ class TTSProvider(TTSProviderBase): raise async def cancel_session(self,session_id): - logger.bind(tag=TAG).info(f"取消会话,释放服务端资源~~{session_id}") + logger.bind(tag=TAG).debug(f"取消会话,释放服务端资源~~{session_id}") try: if self.ws: header = Header( @@ -396,7 +394,7 @@ class TTSProvider(TTSProviderBase): ).as_bytes() payload = str.encode("{}") await self.send_event(self.ws, header, optional, payload) - logger.bind(tag=TAG).info("会话取消请求已发送") + logger.bind(tag=TAG).debug("会话取消请求已发送") except Exception as e: logger.bind(tag=TAG).error(f"取消会话失败: {str(e)}") # 确保清理资源 @@ -405,6 +403,7 @@ class TTSProvider(TTSProviderBase): async def close(self): """资源清理方法""" + self.activate_session = False # 取消监听任务 if self._monitor_task: try: @@ -424,9 +423,8 @@ class TTSProvider(TTSProviderBase): self.ws = None async def _start_monitor_tts_response(self): - """监听TTS响应""" + """监听TTS响应 - 长期运行""" try: - session_finished = False # 标记会话是否正常结束 while not self.conn.stop_event.is_set(): try: # 确保 `recv()` 运行在同一个 event loop @@ -434,10 +432,17 @@ class TTSProvider(TTSProviderBase): res = self.parser_response(msg) self.print_response(res, "send_text res:") + # 只处理当前活跃会话的响应 + if res.optional.sessionId and self.conn.sentence_id != res.optional.sessionId: + # 如果是会话结束相关事件,即使会话ID不匹配也要重置状态 + if res.optional.event in [EVENT_SessionCanceled, EVENT_SessionFailed, EVENT_SessionFinished]: + logger.bind(tag=TAG).debug(f"收到残余下行结束响应重置会话状态~~") + self.activate_session = False + continue + if res.optional.event == EVENT_SessionCanceled: logger.bind(tag=TAG).debug(f"释放服务端资源成功~~") - session_finished = True - break + self.activate_session = False elif res.optional.event == EVENT_TTSSentenceStart: json_data = json.loads(res.payload.decode("utf-8")) self.tts_text = json_data.get("text", "") @@ -454,9 +459,8 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).info(f"句子语音生成成功:{self.tts_text}") elif res.optional.event == EVENT_SessionFinished: logger.bind(tag=TAG).debug(f"会话结束~~") + self.activate_session = False self._process_before_stop_play_files() - session_finished = True - break except websockets.ConnectionClosed: logger.bind(tag=TAG).warning("WebSocket连接已关闭") break @@ -466,8 +470,8 @@ class TTSProvider(TTSProviderBase): ) traceback.print_exc() break - # 仅在连接异常时才关闭 - if not session_finished and self.ws: + # 连接异常时关闭WebSocket + if self.ws: try: await self.ws.close() except: @@ -513,7 +517,7 @@ class TTSProvider(TTSProviderBase): def read_res_content(self, res: bytes, offset: int): content_size = int.from_bytes(res[offset : offset + 4], "big", signed=True) offset += 4 - content = str(res[offset : offset + content_size]) + content = res[offset : offset + content_size].decode('utf-8') offset += content_size return content, offset diff --git a/main/xiaozhi-server/core/providers/vad/silero.py b/main/xiaozhi-server/core/providers/vad/silero.py index b516d8fbd..2263fcb73 100644 --- a/main/xiaozhi-server/core/providers/vad/silero.py +++ b/main/xiaozhi-server/core/providers/vad/silero.py @@ -70,7 +70,9 @@ class VADProvider(VADProviderBase): # 更新滑动窗口 conn.client_voice_window.append(is_voice) - client_have_voice = (conn.client_voice_window.count(True) >= self.frame_window_threshold) + client_have_voice = ( + conn.client_voice_window.count(True) >= self.frame_window_threshold + ) # 如果之前有声音,但本次没有声音,且与上次有声音的时间差已经超过了静默阈值,则认为已经说完一句话 if conn.client_have_voice and not client_have_voice: diff --git a/main/xiaozhi-server/core/utils/prompt_manager.py b/main/xiaozhi-server/core/utils/prompt_manager.py index 4cbeefcb9..444b16eec 100644 --- a/main/xiaozhi-server/core/utils/prompt_manager.py +++ b/main/xiaozhi-server/core/utils/prompt_manager.py @@ -66,7 +66,9 @@ class PromptManager: def _load_base_template(self): """加载基础提示词模板""" try: - template_path = "agent-base-prompt.txt" + template_path = self.config.get("prompt_template", None) + if not template_path: + template_path = "agent-base-prompt.txt" cache_key = f"prompt_template:{template_path}" # 先从缓存获取 @@ -88,7 +90,7 @@ class PromptManager: self.base_prompt_template = template_content self.logger.bind(tag=TAG).debug("成功加载基础提示词模板并缓存") else: - self.logger.bind(tag=TAG).warning("未找到agent-base-prompt.txt文件") + self.logger.bind(tag=TAG).warning(f"未找到{template_path}文件") except Exception as e: self.logger.bind(tag=TAG).error(f"加载提示词模板失败: {e}") @@ -117,8 +119,12 @@ class PromptManager: def _get_current_time_info(self) -> tuple: """获取当前时间信息""" - from .current_time import get_current_date, get_current_weekday, get_current_lunar_date - + from .current_time import ( + get_current_date, + get_current_weekday, + get_current_lunar_date, + ) + today_date = get_current_date() today_weekday = get_current_weekday() lunar_date = get_current_lunar_date() + "\n" @@ -178,7 +184,7 @@ class PromptManager: local_address = self._get_location_info(client_ip) # 获取天气信息(使用全局缓存) self._get_weather_info(conn, local_address) - self.logger.bind(tag=TAG).info(f"上下文信息更新完成") + self.logger.bind(tag=TAG).debug(f"上下文信息更新完成") except Exception as e: self.logger.bind(tag=TAG).error(f"更新上下文信息失败: {e}") @@ -192,9 +198,7 @@ class PromptManager: try: # 获取最新的时间信息(不缓存) - today_date, today_weekday, lunar_date = ( - self._get_current_time_info() - ) + today_date, today_weekday, lunar_date = self._get_current_time_info() # 获取缓存的上下文信息 local_address = "" @@ -225,7 +229,9 @@ class PromptManager: weather_info=weather_info, emojiList=EMOJI_List, device_id=device_id, - *args, **kwargs + client_ip=client_ip, + *args, + **kwargs, ) device_cache_key = f"device_prompt:{device_id}" self.cache_manager.set( diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py index 27471e581..f10cc3699 100644 --- a/main/xiaozhi-server/core/utils/util.py +++ b/main/xiaozhi-server/core/utils/util.py @@ -176,31 +176,67 @@ def parse_string_to_list(value, separator=";"): return [] -def check_ffmpeg_installed(): - ffmpeg_installed = False +def check_ffmpeg_installed() -> bool: + """ + 检查当前环境中是否已正确安装并可执行 ffmpeg。 + + Returns: + bool: 如果 ffmpeg 正常可用,返回 True;否则抛出 ValueError 异常。 + + Raises: + ValueError: 当检测到 ffmpeg 未安装或依赖缺失时,抛出详细的提示信息。 + """ try: - # 执行ffmpeg -version命令,并捕获输出 + # 尝试执行 ffmpeg 命令 result = subprocess.run( ["ffmpeg", "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, - check=True, # 如果返回码非零则抛出异常 + check=True, # 非零退出码会触发 CalledProcessError ) - # 检查输出中是否包含版本信息(可选) - output = result.stdout + result.stderr - if "ffmpeg version" in output.lower(): - ffmpeg_installed = True - return False - except (subprocess.CalledProcessError, FileNotFoundError): - # 命令执行失败或未找到 - ffmpeg_installed = False - if not ffmpeg_installed: - error_msg = "您的电脑还没正确安装ffmpeg\n" - error_msg += "\n建议您:\n" - error_msg += "1、按照项目的安装文档,正确进入conda环境\n" - error_msg += "2、查阅安装文档,如何在conda环境中安装ffmpeg\n" - raise ValueError(error_msg) + + output = (result.stdout + result.stderr).lower() + if "ffmpeg version" in output: + return True + + # 如果未检测到版本信息,也视为异常情况 + raise ValueError("未检测到有效的 ffmpeg 版本输出。") + + except (subprocess.CalledProcessError, FileNotFoundError) as e: + # 提取错误输出 + stderr_output = "" + if isinstance(e, subprocess.CalledProcessError): + stderr_output = (e.stderr or "").strip() + else: + stderr_output = str(e).strip() + + # 构建基础错误提示 + error_msg = [ + "❌ 检测到 ffmpeg 无法正常运行。\n", + "建议您:", + "1. 确认已正确激活 conda 环境;", + "2. 查阅项目安装文档,了解如何在 conda 环境中安装 ffmpeg。\n", + ] + + # 🎯 针对具体错误信息提供额外提示 + if "libiconv.so.2" in stderr_output: + 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() + ): + error_msg.append("⚠️ 系统未找到 ffmpeg 可执行文件。") + error_msg.append("解决方法:在当前 conda 环境中执行:") + error_msg.append(" conda install -c conda-forge ffmpeg\n") + else: + error_msg.append("错误详情:") + error_msg.append(stderr_output or "未知错误。") + + # 抛出详细异常信息 + raise ValueError("\n".join(error_msg)) from e def extract_json_from_string(input_string): @@ -212,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: @@ -229,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编码的帧列表 @@ -280,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数据,支持wav、mp3、p3 """ @@ -324,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字节流 @@ -350,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 @@ -423,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 diff --git a/main/xiaozhi-server/docker-compose_all.yml b/main/xiaozhi-server/docker-compose_all.yml index b3602d45a..327676e18 100644 --- a/main/xiaozhi-server/docker-compose_all.yml +++ b/main/xiaozhi-server/docker-compose_all.yml @@ -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 diff --git a/main/xiaozhi-server/mcp_server_settings.json b/main/xiaozhi-server/mcp_server_settings.json index 70607a2c1..966741b4f 100644 --- a/main/xiaozhi-server/mcp_server_settings.json +++ b/main/xiaozhi-server/mcp_server_settings.json @@ -4,7 +4,7 @@ "后面不断测试补充好用的mcp服务,欢迎大家一起补充。", "记得删除注释行,des属性仅为说明,不会被解析。", "des和link属性,仅为说明安装方式,方便大家查看原始链接,不是必须项。", - "当前支持stdio/sse两种模式。" + "当前支持三种传输模式:stdio(标准输入输出), sse(Server-Sent Events), streamable-http(流式HTTP)。" ], "mcpServers": { "Home Assistant": { @@ -41,7 +41,16 @@ "url": "http://localhost:8080/sse", "headers": { "Authorization": "Bearer YOUR TOKEN" - } + }, + "des": "使用SSE传输模式(默认)" + }, + "streamable-http-mcp-server": { + "url": "http://localhost:8000/mcp", + "transport": "streamable-http", + "headers": { + "Authorization": "Bearer YOUR TOKEN" + }, + "des": "使用Streamable HTTP传输模式,适用于生产环境的Web部署" } } } diff --git a/main/xiaozhi-server/performance_tester/performance_tester_llm.py b/main/xiaozhi-server/performance_tester/performance_tester_llm.py index 33430637b..769cad6b8 100644 --- a/main/xiaozhi-server/performance_tester/performance_tester_llm.py +++ b/main/xiaozhi-server/performance_tester/performance_tester_llm.py @@ -38,7 +38,7 @@ class LLMPerformanceTester: """加载系统提示词""" try: prompt_file = os.path.join( - os.path.dirname(os.path.dirname(__file__)), "agent-base-prompt.txt" + os.path.dirname(os.path.dirname(__file__)), self.config.get("prompt_template", "agent-base-prompt.txt") ) with open(prompt_file, "r", encoding="utf-8") as f: content = f.read() diff --git a/main/xiaozhi-server/plugins_func/functions/search_from_ragflow.py b/main/xiaozhi-server/plugins_func/functions/search_from_ragflow.py new file mode 100644 index 000000000..d585a7624 --- /dev/null +++ b/main/xiaozhi-server/plugins_func/functions/search_from_ragflow.py @@ -0,0 +1,99 @@ +import requests +import sys +from config.logger import setup_logging +from plugins_func.register import register_function, ToolType, ActionResponse, Action + +TAG = __name__ +logger = setup_logging() + +# 定义基础的函数描述模板 +SEARCH_FROM_RAGFLOW_FUNCTION_DESC = { + "type": "function", + "function": { + "name": "search_from_ragflow", + "description": "从知识库中查询信息", + "parameters": { + "type": "object", + "properties": {"question": {"type": "string", "description": "查询的问题"}}, + "required": ["question"], + }, + }, +} + + +@register_function( + "search_from_ragflow", SEARCH_FROM_RAGFLOW_FUNCTION_DESC, ToolType.SYSTEM_CTL +) +def search_from_ragflow(conn, question=None): + # 确保字符串参数正确处理编码 + if question and isinstance(question, str): + # 确保问题参数是UTF-8编码的字符串 + pass + else: + question = str(question) if question is not None else "" + + base_url = conn.config["plugins"]["search_from_ragflow"].get("base_url", "") + api_key = conn.config["plugins"]["search_from_ragflow"].get("api_key", "") + dataset_ids = conn.config["plugins"]["search_from_ragflow"].get("dataset_ids", []) + + url = base_url + "/api/v1/retrieval" + headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"} + + # 确保payload中的字符串都是UTF-8编码 + payload = {"question": question, "dataset_ids": dataset_ids} + + try: + # 使用ensure_ascii=False确保JSON序列化时正确处理中文 + response = requests.post( + url, + json=payload, + headers=headers, + timeout=5, + verify=False, + ) + + # 显式设置响应的编码为utf-8 + response.encoding = "utf-8" + + response.raise_for_status() + + # 先获取文本内容,然后手动处理JSON解码 + response_text = response.text + import json + + result = json.loads(response_text) + + if result.get("code") != 0: + error_detail = response.get("error", {}).get("detail", "") + # 安全地记录错误信息 + logger.bind(tag=TAG).error( + "从RAGflow获取信息失败,原因:%s", str(error_detail) + ) + return ActionResponse(Action.RESPONSE, None, "RAG接口返回异常") + + chunks = result.get("data", {}).get("chunks", []) + contents = [] + for chunk in chunks: + content = chunk.get("content", "") + if content: + # 安全地处理内容字符串 + if isinstance(content, str): + contents.append(content) + elif isinstance(content, bytes): + contents.append(content.decode("utf-8", errors="replace")) + else: + contents.append(str(content)) + + 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) + + except Exception as e: + # 使用安全的方式记录异常,避免编码问题 + logger.bind(tag=TAG).error("从RAGflow获取信息失败,原因:%s", str(e)) + return ActionResponse(Action.RESPONSE, None, "RAG接口返回异常") diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt old mode 100755 new mode 100644 index 75964ec93..a5b791ff8 --- a/main/xiaozhi-server/requirements.txt +++ b/main/xiaozhi-server/requirements.txt @@ -1,38 +1,41 @@ -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==1.107.0 +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.0.0 -httpx==0.27.2 -aiohttp==3.12.15 -aiohttp_cors==0.7.0 -ormsgpack==1.7.0 -ruamel.yaml==0.18.15 +edge_tts==7.2.3 +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 -mem0ai==0.1.62 +cozepy==0.20.0 +mem0ai==1.0.0 bs4==0.0.2 modelscope==1.23.2 -sherpa_onnx==1.12.11 -mcp==1.13.1 +sherpa_onnx==1.12.15 +mcp==1.20.0 cnlunar==0.2.0 PySocks==1.7.1 -dashscope==1.23.1 +dashscope==1.24.6 baidu-aip==4.16.13 chardet==5.2.0 -aioconsole==0.8.1 +aioconsole==0.8.2 markitdown==0.1.3 -mcp-proxy==0.8.2 -PyJWT==2.8.0 +mcp-proxy==0.10.0 +PyJWT==2.10.1 psutil==7.0.0 portalocker==3.2.0 Jinja2==3.1.6 -vosk==0.3.45 +vosk==0.3.44 \ No newline at end of file diff --git a/main/xiaozhi-server/test/default-mcp-tools.json b/main/xiaozhi-server/test/default-mcp-tools.json new file mode 100644 index 000000000..2d44f2dc7 --- /dev/null +++ b/main/xiaozhi-server/test/default-mcp-tools.json @@ -0,0 +1,72 @@ +[ + { + "name": "self.get_device_status", + "description": "Provides the real-time information of the device, including the current status of the audio speaker, screen, battery, network, etc.\nUse this tool for: \n1. Answering questions about current condition (e.g. what is the current volume of the audio speaker?)\n2. As the first step to control the device (e.g. turn up / down the volume of the audio speaker, etc.)", + "inputSchema": { + "type": "object", + "properties": {} + }, + "mockResponse": { + "audio_speaker": { + "volume": 50, + "muted": false + }, + "screen": { + "brightness": 80, + "theme": "light" + }, + "battery": { + "level": 85, + "charging": false + }, + "network": { + "connected": true, + "type": "wifi" + } + } + }, + { + "name": "self.audio_speaker.set_volume", + "description": "Set the volume of the audio speaker. If the current volume is unknown, you must call `self.get_device_status` tool first and then call this tool.", + "inputSchema": { + "type": "object", + "properties": { + "volume": { + "type": "integer", + "minimum": 0, + "maximum": 100 + } + }, + "required": [ + "volume" + ] + }, + "mockResponse": { + "success": true, + "volume": "${volume}", + "message": "音量已设置为 ${volume}" + } + }, + { + "name": "self.screen.set_brightness", + "description": "Set the brightness of the screen.", + "inputSchema": { + "type": "object", + "properties": { + "brightness": { + "type": "integer", + "minimum": 0, + "maximum": 100 + } + }, + "required": [ + "brightness" + ] + }, + "mockResponse": { + "success": true, + "brightness": "${brightness}", + "message": "亮度已设置为 ${brightness}" + } + } +] \ No newline at end of file diff --git a/main/xiaozhi-server/test/js/xiaoZhiConnect.js b/main/xiaozhi-server/test/js/xiaoZhiConnect.js index 606d615b4..d8fbe7a3b 100644 --- a/main/xiaozhi-server/test/js/xiaoZhiConnect.js +++ b/main/xiaozhi-server/test/js/xiaoZhiConnect.js @@ -1,24 +1,50 @@ +import { otaStatusStyle } from './document.js'; import { log } from './utils/logger.js'; -import { otaStatusStyle } from './document.js' // WebSocket 连接 -export async function webSocketConnect(otaUrl,wsUrl,config){ - if (!validateWsUrl(wsUrl)) { - return; // 直接返回,不再往下执行 - } +export async function webSocketConnect(otaUrl, config) { if (!validateConfig(config)) { return; } - const ok = await sendOTA(otaUrl, config); - if (!ok) return; - // 使用自定义WebSocket实现以添加认证头信息 - let connUrl = new URL(wsUrl); - // 添加认证参数 + // 发送OTA请求并获取返回的websocket信息 + const otaResult = await sendOTA(otaUrl, config); + if (!otaResult) { + log('无法从OTA服务器获取信息', 'error'); + return; + } + + // 从OTA响应中提取websocket信息 + const { websocket } = otaResult; + if (!websocket || !websocket.url) { + log('OTA响应中缺少websocket信息', 'error'); + return; + } + + // 使用OTA返回的websocket URL + let connUrl = new URL(websocket.url); + + // 添加token参数(从OTA响应中获取) + if (websocket.token) { + if (websocket.token.startsWith("Bearer ")) { + connUrl.searchParams.append('authorization', websocket.token); + } else { + connUrl.searchParams.append('authorization', 'Bearer ' + websocket.token); + } + } + + // 添加认证参数(保持原有逻辑) connUrl.searchParams.append('device-id', config.deviceId); connUrl.searchParams.append('client-id', config.clientId); - log(`正在连接: ${connUrl.toString()}`, 'info'); + + const wsurl = connUrl.toString() + + log(`正在连接: ${wsurl}`, 'info'); + + if (wsurl) { + document.getElementById('serverUrl').value = wsurl; + } return new WebSocket(connUrl.toString()); } @@ -37,7 +63,7 @@ function validateConfig(config) { } // 判断wsUrl路径是否存在错误 -function validateWsUrl(wsUrl){ +function validateWsUrl(wsUrl) { if (wsUrl === '') return false; // 检查URL格式 if (!wsUrl.startsWith('ws://') && !wsUrl.startsWith('wss://')) { @@ -48,7 +74,7 @@ function validateWsUrl(wsUrl){ } -// OTA发送请求,验证状态 +// OTA发送请求,验证状态,并返回响应数据 async function sendOTA(otaUrl, config) { try { const res = await fetch(otaUrl, { @@ -90,14 +116,9 @@ async function sendOTA(otaUrl, config) { const result = await res.json(); otaStatusStyle(true) - return true; // 成功 + return result; // 返回完整的响应数据 } catch (err) { otaStatusStyle(false) - return false; // 失败 + return null; // 失败返回null } -} - - - - - +} \ No newline at end of file diff --git a/main/xiaozhi-server/test/test_page.css b/main/xiaozhi-server/test/test_page.css index c70c97069..bea049947 100644 --- a/main/xiaozhi-server/test/test_page.css +++ b/main/xiaozhi-server/test/test_page.css @@ -21,9 +21,9 @@ h1 { } .section { - margin-bottom: 20px; - padding: 15px; - border-radius: 8px; + margin-bottom: 5px; + padding: 10px; + border-radius: 10px; background-color: #f9f9f9; } diff --git a/main/xiaozhi-server/test/test_page.html b/main/xiaozhi-server/test/test_page.html index 547f2b31b..b9fc5c85d 100644 --- a/main/xiaozhi-server/test/test_page.html +++ b/main/xiaozhi-server/test/test_page.html @@ -56,6 +56,163 @@ #fileProtocolWarning button:hover { background-color: #45a049; } + + /* 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-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; + }