feat: add T1D assistant integrations and server customizations

This commit is contained in:
atangbc 2026-09-02 15:09:39 -04:00
parent a8c13d740b
commit 5c818bda1e
244 changed files with 42657 additions and 5372 deletions

View file

@ -1,374 +0,0 @@
[![Banners](docs/images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server)
<h1 align="center">Xiaozhi Backend-Service xiaozhi-esp32-server</h1>
<p align="center">
Dieses Projekt basiert auf der Theorie und Technologie der Mensch-Maschine-symbiotischen Intelligenz zur Entwicklung intelligenter Terminal-Hardware- und Software-Systeme<br/>und bietet Backend-Dienste für das Open-Source-Hardware-Projekt
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
Implementiert mit Python, Java und Vue gemäß dem <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">Xiaozhi-Kommunikationsprotokoll</a><br/>
Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Endpunkte und Stimmabdruckerkennung
</p>
<p align="center">
<a href="./docs/FAQ.md">Häufige Fragen</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">Probleme melden</a>
· <a href="./README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3">Deployment-Dokumentation</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">Release-Hinweise</a>
</p>
<p align="center">
<a href="./README.md"><img alt="简体中文版自述文件" src="https://img.shields.io/badge/简体中文-DFE0E5"></a>
<a href="./README_en.md"><img alt="README in English" src="https://img.shields.io/badge/English-DFE0E5"></a>
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DBEDFA"></a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/LICENSE">
<img alt="GitHub pull requests" src="https://img.shields.io/badge/license-MIT-white?labelColor=black" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server">
<img alt="stars" src="https://img.shields.io/github/stars/xinnan-tech/xiaozhi-esp32-server?color=ffcb47&labelColor=black" />
</a>
</p>
<p align="center">
Geleitet vom Team von Professor Siyuan Liu (South China University of Technology)
</br>
刘思源教授团队主导研发(华南理工大学)
</br>
<img src="./docs/images/hnlg.jpg" alt="South China University of Technology" width="50%">
</p>
---
## Zielgruppe 👥
Dieses Projekt erfordert ESP32-Hardware-Geräte zum Betrieb. Wenn Sie ESP32-bezogene Hardware erworben haben, erfolgreich eine Verbindung zu Brother Xias bereitgestelltem Backend-Service hergestellt haben und Ihren eigenen `xiaozhi-esp32`-Backend-Service unabhängig aufbauen möchten, dann ist dieses Projekt perfekt für Sie.
Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
<table>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture>
<img alt="响应速度感受" src="docs/images/demo9.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
<picture>
<img alt="速度优化秘诀" src="docs/images/demo6.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture>
<img alt="复杂医疗场景" src="docs/images/demo1.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
<picture>
<img alt="MQTT指令下发" src="docs/images/demo4.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture>
<img alt="声纹识别" src="docs/images/demo14.png" />
</picture>
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture>
<img alt="控制家电开关" src="docs/images/demo5.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture>
<img alt="MCP接入点" src="docs/images/demo13.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture>
<img alt="多指令任务" src="docs/images/demo11.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture>
<img alt="播放音乐" src="docs/images/demo7.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Z8XuYZEAS" target="_blank">
<picture>
<img alt="天气插件" src="docs/images/demo8.png" />
</picture>
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture>
<img alt="实时打断" src="docs/images/demo10.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
<picture>
<img alt="拍照识物品" src="docs/images/demo12.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture>
<img alt="自定义音色" src="docs/images/demo2.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
<picture>
<img alt="使用粤语交流" src="docs/images/demo3.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV17LXWYvENb" target="_blank">
<picture>
<img alt="播报新闻" src="docs/images/demo0.png" />
</picture>
</a>
</td>
</tr>
</table>
---
## Warnungen ⚠️
1. Dieses Projekt ist Open-Source-Software. Diese Software hat keine kommerzielle Partnerschaft mit Drittanbieter-API-Dienstleistern (einschließlich, aber nicht beschränkt auf Spracherkennung, große Modelle, Sprachsynthese und andere Plattformen), mit denen sie sich verbindet, und bietet keine Garantie für deren Servicequalität oder finanzielle Sicherheit. Es wird empfohlen, dass Benutzer Dienstleister mit entsprechenden Geschäftslizenzen bevorzugen und deren Servicevereinbarungen und Datenschutzrichtlinien sorgfältig lesen. Diese Software hostet keine Kontoschlüssel, nimmt nicht an Geldströmen teil und trägt nicht das Risiko von Verlusten bei Guthaben-Aufladungen.
2. Die Funktionalität dieses Projekts ist nicht vollständig und hat keine Netzwerksicherheitsbewertung bestanden. Bitte verwenden Sie es nicht in Produktionsumgebungen. Wenn Sie dieses Projekt zu Lernzwecken in einer öffentlichen Netzwerkumgebung bereitstellen, stellen Sie bitte sicher, dass notwendige Schutzmaßnahmen vorhanden sind.
---
## Deployment-Dokumentation
![Banners](docs/images/banner2.png)
Dieses Projekt bietet zwei Bereitstellungsmethoden. Bitte wählen Sie basierend auf Ihren spezifischen Anforderungen:
#### 🚀 Auswahl der Bereitstellungsmethode
| Bereitstellungsmethode | Funktionen | Anwendungsszenarien | Deployment-Dokumente | Konfigurationsanforderungen | Video-Tutorials |
|---------|------|---------|---------|---------|---------|
| **Vereinfachte Installation** | Intelligenter Dialog, Einzel-Agenten-Verwaltung | 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, Mehrbenutzerverwaltung, Mehr-Agenten-Verwaltung, Intelligente Steuerkonsole-Bedienung | 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) | 👍XunfeiStreamASR (Xunfei-Streaming) |
| LLM (Großes Modell) | glm-4-flash (Zhipu) | 👍qwen-flash (Alibaba Bailian) |
| VLLM (Vision Large Model) | glm-4v-flash (Zhipu) | 👍qwen2.5-vl-3b-instructh (Alibaba Bailian) |
| TTS (Sprachsynthese) | ✅LinkeraiTTS (Lingxi-Streaming) | 👍HuoshanDoubleStreamTTS (Volcano-Streaming) |
| 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#related-open-source-projects) in diesem Ökosystem ansehen
---
## Liste der von diesem Projekt unterstützten Plattformen/Komponenten 📋
### LLM-Sprachmodelle
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:|
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Volcano Engine Doubao, DeepSeek, Zhipu ChatGLM, Gemini | Zhipu ChatGLM, Gemini |
| Ollama-Schnittstellenaufrufe | Ollama | - |
| Dify-Schnittstellenaufrufe | Dify | - |
| FastGPT-Schnittstellenaufrufe | FastGPT | - |
| Coze-Schnittstellenaufrufe | Coze | - |
| Xinference-Schnittstellenaufrufe | Xinference | - |
| HomeAssistant-Schnittstellenaufrufe | HomeAssistant | - |
Tatsächlich kann jedes LLM, das OpenAI-Schnittstellenaufrufe unterstützt, integriert und verwendet werden.
---
### VLLM-Vision-Modelle
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:|
| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, integriert und verwendet werden.
---
### TTS-Sprachsynthese
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:|
| Schnittstellenaufrufe | EdgeTTS, Volcano Engine Doubao TTS, Tencent Cloud, Alibaba Cloud TTS, AliYun Stream TTS, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS, Volcano Dual-Stream TTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow (teilweise) |
| Lokale Dienste | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
---
### VAD-Sprachaktivitätserkennung
| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
|:---:|:---------:|:----:|:----:|:--:|
| VAD | SileroVAD | Lokale Verwendung | Kostenlos | |
---
### ASR-Spracherkennung
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:|
| Lokale Verwendung | FunASR, SherpaASR | FunASR, SherpaASR |
| Schnittstellenaufrufe | DoubaoASR, Doubao Streaming ASR, FunASRServer, TencentASR, AliyunASR, Aliyun Streaming ASR, Baidu ASR, OpenAI ASR | FunASRServer |
---
### Voiceprint-Stimmabdruckerkennung
| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
|:---:|:---:|:---:|
| Lokale Verwendung | 3D-Speaker | 3D-Speaker |
---
### Memory-Gedächtnisspeicher
| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
|:------:|:---------------:|:----:|:---------:|:--:|
| Memory | mem0ai | Schnittstellenaufrufe | 1000 Mal/Monat Kontingent | |
| Memory | mem_local_short | Lokale Zusammenfassung | Kostenlos | |
| Memory | nomem | Kein Gedächtnismodus | Kostenlos | |
---
### Intent-Absichtserkennung
| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
|:------:|:-------------:|:----:|:-------:|:---------------------:|
| Intent | intent_llm | Schnittstellenaufrufe | Basierend auf LLM-Preisen | Erkennt Absicht durch große Modelle, starke Allgemeingültigkeit |
| Intent | function_call | Schnittstellenaufrufe | Basierend auf LLM-Preisen | Vervollständigt Absicht durch Funktionsaufruf großer Modelle, schnelle Geschwindigkeit, guter Effekt |
| Intent | nointent | Kein Absichtsmodus | Kostenlos | Führt keine Absichtserkennung durch, gibt direkt Dialogergebnis zurück |
---
### Rag Retrieval Augmented Generation
| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
|:------:|:-------------:|:----:|:-------:|:---------------------:|
| Rag | ragflow | Schnittstellenaufrufe | Gebühren basierend auf Token-Verbrauch für Segmentierung und Tokenisierung | Nutzt RAGFlow's Retrieval-Augmented-Generation-Funktion für präzisere Dialogantworten |
---
## Danksagungen 🙏
| Logo | Projekt/Unternehmen | Beschreibung |
|:---:|:---:|:---|
| <img src="./docs/images/logo_bailing.png" width="160"> | [Bailing Voice Dialogue Robot](https://github.com/wwbin2017/bailing) | Dieses Projekt wurde von [Bailing Voice Dialogue Robot](https://github.com/wwbin2017/bailing) inspiriert und auf dessen Basis implementiert |
| <img src="./docs/images/logo_tenclass.png" width="160"> | [Tenclass](https://www.tenclass.com/) | Dank an [Tenclass](https://www.tenclass.com/) für die Formulierung von Standardkommunikationsprotokollen, Multi-Geräte-Kompatibilitätslösungen und High-Concurrency-Szenario-Praxisdemonstrationen für das Xiaozhi-Ökosystem; für die Bereitstellung vollständiger technischer Dokumentationsunterstützung für dieses Projekt |
| <img src="./docs/images/logo_xuanfeng.png" width="160"> | [Xuanfeng Technology](https://github.com/Eric0308) | Dank an [Xuanfeng Technology](https://github.com/Eric0308) für den Beitrag des Funktionsaufruf-Frameworks, des MCP-Kommunikationsprotokolls und der plugin-basierten Aufrufmechanismus-Implementierungscode. Durch standardisiertes Befehlsplanungssystem und dynamische Erweiterungsfähigkeiten wird die Interaktionseffizienz und funktionale Erweiterbarkeit von Frontend-Geräten (IoT) erheblich verbessert |
| <img src="./docs/images/logo_junsen.png" width="160"> | [huangjunsen](https://github.com/huangjunsen0406) | Dank an [huangjunsen](https://github.com/huangjunsen0406) für den Beitrag des `Smart Control Console Mobile`-Moduls, das eine effiziente Steuerung und Echtzeit-Interaktion über mobile Geräte ermöglicht und die Betriebsbequemlichkeit und Verwaltungseffizienz des Systems in mobilen Szenarien erheblich verbessert |
| <img src="./docs/images/logo_huiyuan.png" width="160"> | [Huiyuan Design](http://ui.kwd988.net/) | Dank an [Huiyuan Design](http://ui.kwd988.net/) für die Bereitstellung professioneller visueller Lösungen für dieses Projekt, unter Verwendung ihrer Design-Praxiserfahrung im Dienst von über tausend Unternehmen, um die Produktbenutzererfahrung dieses Projekts zu stärken |
| <img src="./docs/images/logo_qinren.png" width="160"> | [Xi'an Qinren Information Technology](https://www.029app.com/) | Dank an [Xi'an Qinren Information Technology](https://www.029app.com/) für die Vertiefung des visuellen Systems dieses Projekts und die Sicherstellung der Konsistenz und Erweiterbarkeit des Gesamtdesignstils in Multi-Szenario-Anwendungen |
| <img src="./docs/images/logo_contributors.png" width="160"> | [Code-Mitwirkende](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Dank an [alle Code-Mitwirkenden](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), Ihre Bemühungen haben das Projekt robuster und leistungsfähiger gemacht. |
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
</picture>
</a>

View file

@ -1,375 +0,0 @@
[![Banners](docs/images/banner1.png)](https://github.com/xinnan-tech/xiaozhi-esp32-server)
<h1 align="center">Dịch vụ Backend Xiaozhi xiaozhi-esp32-server</h1>
<p align="center">
Dự án này dựa trên lý thuyết và công nghệ trí tuệ cộng sinh người-máy để phát triển hệ thống phần mềm và phần cứng thiết bị đầu cuối thông minh<br/>Cung cấp dịch vụ backend cho dự án phần cứng thông minh mã nguồn mở
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
Được triển khai bằng Python, Java, Vue theo <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">giao thức truyền thông Xiaozhi</a><br/>
Hỗ trợ giao thức MQTT+UDP, giao thức Websocket, điểm truy cập MCP, nhận dạng giọng nói và kho tri thức
</p>
<p align="center">
<a href="./docs/FAQ.md">Câu hỏi thường gặp</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">Báo cáo vấn đề</a>
· <a href="./README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3">Tài liệu triển khai</a>
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">Nhật ký cập nhật</a>
</p>
<p align="center">
<a href="./README.md"><img alt="简体中文版自述文件" src="https://img.shields.io/badge/简体中文-DFE0E5"></a>
<a href="./README_en.md"><img alt="README in English" src="https://img.shields.io/badge/English-DFE0E5"></a>
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DBEDFA"></a>
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/LICENSE">
<img alt="GitHub pull requests" src="https://img.shields.io/badge/license-MIT-white?labelColor=black" />
</a>
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server">
<img alt="stars" src="https://img.shields.io/github/stars/xinnan-tech/xiaozhi-esp32-server?color=ffcb47&labelColor=black" />
</a>
</p>
<p align="center">
Spearheaded by Professor Siyuan Liu's Team (South China University of Technology)
</br>
Được dẫn dắt bởi nhóm Giáo sư Lưu Tư Nguyên (Đại học Bách khoa Nam Trung Quốc)
</br>
<img src="./docs/images/hnlg.jpg" alt="华南理工大学" width="50%">
</p>
---
## Người dùng phù hợp 👥
Dự án này cần được sử dụng cùng với thiết bị phần cứng ESP32. Nếu bạn đã mua phần cứng liên quan đến ESP32, đã thành công kết nối với dịch vụ backend do anh Xia triển khai, và muốn xây dựng dịch vụ backend `xiaozhi-esp32` riêng của mình, thì dự án này rất phù hợp với bạn.
Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
<table>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
<picture>
<img alt="响应速度感受" src="docs/images/demo9.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
<picture>
<img alt="速度优化秘诀" src="docs/images/demo6.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
<picture>
<img alt="复杂医疗场景" src="docs/images/demo1.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
<picture>
<img alt="MQTT指令下发" src="docs/images/demo4.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
<picture>
<img alt="声纹识别" src="docs/images/demo14.png" />
</picture>
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
<picture>
<img alt="控制家电开关" src="docs/images/demo5.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
<picture>
<img alt="MCP接入点" src="docs/images/demo13.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
<picture>
<img alt="多指令任务" src="docs/images/demo11.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
<picture>
<img alt="播放音乐" src="docs/images/demo7.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Z8XuYZEAS" target="_blank">
<picture>
<img alt="天气插件" src="docs/images/demo8.png" />
</picture>
</a>
</td>
</tr>
<tr>
<td>
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
<picture>
<img alt="实时打断" src="docs/images/demo10.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
<picture>
<img alt="拍照识物品" src="docs/images/demo12.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
<picture>
<img alt="自定义音色" src="docs/images/demo2.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
<picture>
<img alt="使用粤语交流" src="docs/images/demo3.png" />
</picture>
</a>
</td>
<td>
<a href="https://www.bilibili.com/video/BV17LXWYvENb" target="_blank">
<picture>
<img alt="播报新闻" src="docs/images/demo0.png" />
</picture>
</a>
</td>
</tr>
</table>
---
## Cảnh báo ⚠️
1. Dự án này là phần mềm mã nguồn mở, phần mềm này không có quan hệ hợp tác thương mại với bất kỳ nhà cung cấp dịch vụ API bên thứ ba nào (bao gồm nhưng không giới hạn ở các nền tảng nhận dạng giọng nói, mô hình lớn, tổng hợp giọng nói, v.v.), và không đảm bảo chất lượng dịch vụ cũng như an toàn tài chính của họ.
Khuyến nghị người dùng ưu tiên lựa chọn nhà cung cấp dịch vụ có giấy phép kinh doanh liên quan và đọc kỹ thỏa thuận dịch vụ và chính sách bảo mật của họ. Phần mềm này không lưu trữ bất kỳ khóa tài khoản nào, không tham gia vào luồng tiền và không chịu rủi ro mất tiền nạp.
2. Chức năng của dự án này chưa hoàn thiện và chưa qua đánh giá bảo mật mạng, vui lòng không sử dụng trong môi trường sản xuất. Nếu bạn triển khai dự án này trong môi trường mạng công cộng để học tập, vui lòng thực hiện các biện pháp bảo vệ cần thiết.
---
## Tài liệu triển khai
![Banners](docs/images/banner2.png)
Dự án này cung cấp hai phương pháp triển khai, vui lòng chọn theo nhu cầu cụ thể của bạn:
#### 🚀 Lựa chọn phương pháp triển khai
| Phương pháp triển khai | Đặc điểm | Tình huống áp dụng | Tài liệu triển khai | Yêu cầu cấu hình | Video hướng dẫn |
|---------|------|---------|---------|---------|---------|
| **Cài đặt tối giản** | Đối thoại thông minh, quản lý đơn tác nhân | Môi trường cấu hình thấp, dữ liệu lưu trong tệp cấu hình, không cần cơ sở dữ liệu | [①Phiên bản Docker](./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, quản lý đa người dùng, quản lý đa tác nhân, bảng điều khiển thông minh | Trải nghiệm đầy đủ tính năng, dữ liệu lưu trong cơ sở dữ liệu |[①Phiên bản Docker](./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) | 👍XunfeiStreamASR(Xunfei Streaming) |
| LLM(Mô hình lớn) | glm-4-flash(Zhipu) | 👍qwen-flash(Alibaba Bailian) |
| VLLM(Mô hình lớn thị giác) | glm-4v-flash(Zhipu) | 👍qwen2.5-vl-3b-instructh(Alibaba Bailian) |
| TTS(Tổng hợp giọng nói) | ✅LinkeraiTTS(Lingxi streaming) | 👍HuoshanDoubleStreamTTS(Volcano Streaming) |
| 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#related-open-source-projects) khác trong hệ sinh thái này
---
## Danh sách nền tảng/thành phần được dự án này hỗ trợ 📋
### LLM Mô hình ngôn ngữ
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|:---:|:---:|:---:|
| Gọi giao diện openai | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFlytek | Zhipu, Gemini |
| Gọi giao diện ollama | Ollama | - |
| Gọi giao diện dify | Dify | - |
| Gọi giao diện fastgpt | Fastgpt | - |
| Gọi giao diện coze | Coze | - |
| Gọi giao diện xinference | Xinference | - |
| Gọi giao diện homeassistant | HomeAssistant | - |
Trên thực tế, bất kỳ LLM nào hỗ trợ gọi giao diện openai đều có thể truy cập sử dụng.
---
### VLLM Mô hình thị giác
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|:---:|:---:|:---:|
| Gọi giao diện openai | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đều có thể truy cập sử dụng.
---
### TTS Tổng hợp giọng nói
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|:---:|:---:|:---:|
| Gọi giao diện | EdgeTTS, iFlytek, Volcano Engine, Tencent Cloud, Alibaba Cloud và Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi streaming TTS, MinimaxTTS | Lingxi streaming TTS, EdgeTTS, CosyVoiceSiliconflow(một phần) |
| Dịch vụ cục bộ | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
---
### VAD Phát hiện hoạt động giọng nói
| Loại | Tên nền tảng | Phương pháp sử dụng | Mô hình thu phí | Ghi chú |
|:---:|:---------:|:----:|:----:|:--:|
| VAD | SileroVAD | Sử dụng cục bộ | Miễn phí | |
---
### ASR Nhận dạng giọng nói
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|:---:|:---:|:---:|
| Sử dụng cục bộ | FunASR, SherpaASR | FunASR, SherpaASR |
| Gọi giao diện | FunASRServer, Volcano Engine, iFlytek, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
---
### Voiceprint Nhận dạng vân giọng
| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
|:---:|:---:|:---:|
| Sử dụng cục bộ | 3D-Speaker | 3D-Speaker |
---
### Memory Lưu trữ bộ nhớ
| Loại | Tên nền tảng | Phương pháp sử dụng | Mô hình thu phí | Ghi chú |
|:------:|:---------------:|:----:|:---------:|:--:|
| Memory | mem0ai | Gọi giao diện | Hạn mức 1000 lần/tháng | |
| Memory | mem_local_short | Tóm tắt cục bộ | Miễn phí | |
| Memory | nomem | Chế độ không có bộ nhớ | Miễn phí | |
---
### Intent Nhận dạng ý định
| Loại | Tên nền tảng | Phương pháp sử dụng | Mô hình thu phí | Ghi chú |
|:------:|:-------------:|:----:|:-------:|:---------------------:|
| Intent | intent_llm | Gọi giao diện | Thu phí theo LLM | Nhận dạng ý định qua mô hình lớn, tính tổng quát mạnh |
| Intent | function_call | Gọi giao diện | Thu phí theo LLM | Hoàn thành ý định qua gọi hàm mô hình lớn, tốc độ nhanh, hiệu quả tốt |
| Intent | nointent | Chế độ không có ý định | Miễn phí | Không thực hiện nhận dạng ý định, trả về trực tiếp kết quả đối thoại |
---
### Rag Tăng cường truy xuất thông tin
| Loại | Tên nền tảng | Phương pháp sử dụng | Mô hình thu phí | Ghi chú |
|:------:|:-------------:|:----:|:-------:|:---------------------:|
| Rag | ragflow | Gọi giao diện | Thu phí theo token tiêu tốn của phân đoạn, phân từ | Sử dụng chức năng tăng cường truy xuất của RagFlow, cung cấp phản hồi đối thoại chính xác hơn |
---
## Lời cảm ơn 🙏
| Logo | Dự án/Công ty | Mô tả |
|:---:|:---:|:---|
| <img src="./docs/images/logo_bailing.png" width="160"> | [Robot đối thoại giọng nói Bailing](https://github.com/wwbin2017/bailing) | Dự án này được lấy cảm hứng từ [Robot đối thoại giọng nói Bailing](https://github.com/wwbin2017/bailing) và được triển khai trên cơ sở đó |
| <img src="./docs/images/logo_tenclass.png" width="160"> | [Shifang Ronghai](https://www.tenclass.com/) | Cảm ơn [Shifang Ronghai](https://www.tenclass.com/) đã xây dựng giao thức truyền thông tiêu chuẩn, phương án tương thích đa thiết bị và mô phạm thực hành tình huống đồng thời cao cho hệ sinh thái Xiaozhi; cung cấp tài liệu hỗ trợ kỹ thuật toàn diện cho dự án này |
| <img src="./docs/images/logo_xuanfeng.png" width="160"> | [Xuanfeng Technology](https://github.com/Eric0308) | Cảm ơn [Xuanfeng Technology](https://github.com/Eric0308) đã đóng góp khung gọi hàm, giao thức truyền thông MCP và mã triển khai cơ chế gọi dạng plugin, thông qua hệ thống điều phối lệnh tiêu chuẩn hóa và khả năng mở rộng động, đã cải thiện đáng kể hiệu suất tương tác và khả năng mở rộng chức năng của thiết bị front-end(IoT) |
| <img src="./docs/images/logo_junsen.png" width="160"> | [huangjunsen](https://github.com/huangjunsen0406) | Cảm ơn [huangjunsen](https://github.com/huangjunsen0406) đã đóng góp module `Bảng điều khiển thông minh di động`, thực hiện điều khiển hiệu quả và tương tác thời gian thực trên thiết bị di động đa nền tảng, cải thiện đáng kể sự tiện lợi vận hành và hiệu quả quản lý của hệ thống trong tình huống di động |
| <img src="./docs/images/logo_huiyuan.png" width="160"> | [Huiyuan Design](http://ui.kwd988.net/) | Cảm ơn [Huiyuan Design](http://ui.kwd988.net/) đã cung cấp giải pháp thị giác chuyên nghiệp cho dự án này, sử dụng kinh nghiệm thực tế thiết kế phục vụ hơn nghìn doanh nghiệp, trao quyền cho trải nghiệm người dùng sản phẩm của dự án này |
| <img src="./docs/images/logo_qinren.png" width="160"> | [Xi'an Qinren Information Technology](https://www.029app.com/) | Cảm ơn [Xi'an Qinren Information Technology](https://www.029app.com/) đã làm sâu sắc hệ thống thị giác của dự án này, đảm bảo tính nhất quán và khả năng mở rộng của phong cách thiết kế tổng thể trong ứng dụng đa tình huống |
| <img src="./docs/images/logo_contributors.png" width="160"> | [Người đóng góp mã](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Cảm ơn [tất cả người đóng góp mã](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), sự cống hiến của bạn khiến dự án mạnh mẽ và vững chắc hơn. |
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xinnan-tech/xiaozhi-esp32-server&type=Date" />
</picture>
</a>

View file

@ -4,8 +4,8 @@ import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
/**
* 国际化
* Copyright (c) 人人开源 All rights reserved.
* Internationalization
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class MessageUtils {
@ -17,7 +17,7 @@ public class MessageUtils {
public static String getMessage(int code, String... params) {
if (messageSource == null) {
// 延迟初始化,确保Spring上下文已完全初始化
// Lazy initialization, ensuring Spring context is fully initialized
messageSource = (MessageSource) SpringContextUtils.getBean("messageSource");
}
return messageSource.getMessage(code + "", params, LocaleContextHolder.getLocale());

View file

@ -7,8 +7,8 @@ import lombok.Data;
import xiaozhi.common.exception.ErrorCode;
/**
* 响应数据
* Copyright (c) 人人开源 All rights reserved.
* Response Data
* Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Data
@ -16,19 +16,19 @@ import xiaozhi.common.exception.ErrorCode;
public class Result<T> implements Serializable {
/**
* 编码:0表示成功,其他值表示失败
* Code: 0 indicates success, other values indicate failure
*/
@Schema(description = "编码:0表示成功,其他值表示失败")
@Schema(description = "Code: 0 indicates success, other values indicate failure")
private int code = 0;
/**
* 消息内容
* Message content
*/
@Schema(description = "消息内容")
@Schema(description = "Message content")
private String msg = "success";
/**
* 响应数据
* Response data
*/
@Schema(description = "响应数据")
@Schema(description = "Response data")
private T data;
public Result<T> ok(T data) {

View file

@ -29,7 +29,7 @@ import xiaozhi.modules.sys.service.SysUserService;
import xiaozhi.modules.sys.vo.AdminPageUserVO;
/**
* 管理员控制层
* Admin Controller
*
* @author zjy
* @since 2025-3-25
@ -37,19 +37,19 @@ import xiaozhi.modules.sys.vo.AdminPageUserVO;
@AllArgsConstructor
@RestController
@RequestMapping("/admin")
@Tag(name = "管理员管理")
@Tag(name = "Admin Management")
public class AdminController {
private final SysUserService sysUserService;
private final DeviceService deviceService;
@GetMapping("/users")
@Operation(summary = "分页查找用户")
@Operation(summary = "Page Search User")
@RequiresPermissions("sys:role:superAdmin")
@Parameters({
@Parameter(name = "mobile", description = "用户手机号码", required = false),
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true),
@Parameter(name = "mobile", description = "User Mobile", required = false),
@Parameter(name = Constant.PAGE, description = "Current Page, starting from 1", required = true),
@Parameter(name = Constant.LIMIT, description = "Records per page", required = true),
})
public Result<PageData<AdminPageUserVO>> pageUser(
@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
@ -63,7 +63,7 @@ public class AdminController {
}
@PutMapping("/users/{id}")
@Operation(summary = "重置密码")
@Operation(summary = "Reset Password")
@RequiresPermissions("sys:role:superAdmin")
public Result<String> update(
@PathVariable Long id) {
@ -72,7 +72,7 @@ public class AdminController {
}
@DeleteMapping("/users/{id}")
@Operation(summary = "用户删除")
@Operation(summary = "Delete User")
@RequiresPermissions("sys:role:superAdmin")
public Result<Void> delete(@PathVariable Long id) {
sysUserService.deleteById(id);
@ -80,21 +80,21 @@ public class AdminController {
}
@PutMapping("/users/changeStatus/{status}")
@Operation(summary = "批量修改用户状态")
@Operation(summary = "Batch Change User Status")
@RequiresPermissions("sys:role:superAdmin")
@Parameter(name = "status", description = "用户状态", required = true)
@Parameter(name = "status", description = "User Status", required = true)
public Result<Void> changeStatus(@PathVariable Integer status, @RequestBody String[] userIds) {
sysUserService.changeStatus(status, userIds);
return new Result<Void>();
}
@GetMapping("/device/all")
@Operation(summary = "分页查找设备")
@Operation(summary = "Page Search Device")
@RequiresPermissions("sys:role:superAdmin")
@Parameters({
@Parameter(name = "keywords", description = "设备关键词", required = false),
@Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
@Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true),
@Parameter(name = "keywords", description = "Device Keywords", required = false),
@Parameter(name = Constant.PAGE, description = "Current Page, starting from 1", required = true),
@Parameter(name = Constant.LIMIT, description = "Records per page", required = true),
})
public Result<PageData<UserShowDeviceListVO>> pageDevice(
@Parameter(hidden = true) @RequestParam Map<String, Object> params) {

View file

@ -35,11 +35,11 @@ import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.common.redis.RedisUtils;
/**
* 服务端管理控制器
* Server-side Management Controller
*/
@RestController
@RequestMapping("/admin/server")
@Tag(name = "服务端管理")
@Tag(name = "Server-side Management")
@AllArgsConstructor
public class ServerSideManageController {
private final SysParamsService sysParamsService;
@ -48,11 +48,11 @@ public class ServerSideManageController {
private static final ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
// 忽略json字符串中存在,但pojo中不存在对应字段的情况
// Ignore fields present in JSON but missing in POJO
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Operation(summary = "获取Ws服务端列表")
@Operation(summary = "Get Ws Server List")
@GetMapping("/server-list")
@RequiresPermissions("sys:role:superAdmin")
public Result<List<String>> getWsServerList() {
@ -63,9 +63,9 @@ public class ServerSideManageController {
return new Result<List<String>>().ok(Arrays.asList(wsText.split(";")));
}
@Operation(summary = "通知python服务端更新配置")
@Operation(summary = "Notify Python Server to Update Config")
@PostMapping("/emit-action")
@LogOperation("通知python服务端更新配置")
@LogOperation("Notify Python server to update config")
@RequiresPermissions("sys:role:superAdmin")
public Result<Boolean> emitServerAction(@RequestBody @Valid EmitSeverActionDTO emitSeverActionDTO) {
if (emitSeverActionDTO.getAction() == null) {
@ -77,7 +77,7 @@ public class ServerSideManageController {
}
String targetWs = emitSeverActionDTO.getTargetWs();
String[] wsList = wsText.split(";");
// 找到需要发起的
// Find target
if (StringUtils.isBlank(targetWs) || !Arrays.asList(wsList).contains(targetWs)) {
throw new RenException(ErrorCode.TARGET_WEBSOCKET_NOT_EXIST);
}
@ -94,7 +94,7 @@ public class ServerSideManageController {
String clientId = UUID.randomUUID().toString();
String redisKey = xiaozhi.common.redis.RedisKeys.getTmpRegisterMacKey(deviceId);
redisUtils.set(redisKey, "true", 300); // 5分钟有效期
redisUtils.set(redisKey, "true", 300); // 5 minutes validity
WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
headers.add("device-id", deviceId);
@ -112,12 +112,12 @@ public class ServerSideManageController {
.uri(targetWsUri)
.headers(headers)
.build()) {
// 如果连接成功则发送一个json数据包并等待服务端响应
// If connection successful, send JSON packet and wait for server response
client.sendJson(
ServerActionPayloadDTO.build(
actionEnum,
Map.of("secret", serverSK)));
// 等待服务端响应并持续监听信息
// Wait for server response and continue listening
client.listener((jsonText) -> {
if (StringUtils.isBlank(jsonText)) {
return false;
@ -131,7 +131,7 @@ public class ServerSideManageController {
}
});
} catch (Exception e) {
// 捕获全部错误,由全局异常处理器返回
// Catch all errors, returned by global exception handler
throw new RenException(ErrorCode.WEB_SOCKET_CONNECT_FAILED);
}
return true;

View file

@ -4,7 +4,7 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* 服务端动作枚举
* Server Action Enum
*/
public enum ServerActionEnum {
RESTART("restart"),

View file

@ -14,61 +14,61 @@ const langStore = useLangStore()
onLaunch(() => {
console.log('App Launch')
// 获取公共配置
// Get public config
configStore.fetchPublicConfig().catch((error) => {
console.error('获取公共配置失败:', error)
console.error('Failed to get public config:', error)
})
})
onShow(() => {
console.log('App Show')
// 使用setTimeout延迟执行,确保tabBar已经初始化
// Use setTimeout to delay execution, ensure tabBar initialized
setTimeout(() => {
updateTabBarText()
}, 100)
})
// 动态更新tabBar文本
// Dynamically update tabBar text
function updateTabBarText() {
try {
// 设置首页tabBar文本
// Set home tabBar text
uni.setTabBarItem({
index: 0,
text: t('tabBar.home'),
success: () => {},
fail: (err) => {
console.log('设置首页tabBar文本失败:', err)
console.log('Failed to set home tabBar text:', err)
}
})
// 设置配网tabBar文本
// Set config network tabBar text
uni.setTabBarItem({
index: 1,
text: t('tabBar.deviceConfig'),
success: () => {},
fail: (err) => {
console.log('设置配网tabBar文本失败:', err)
console.log('Failed to set config network tabBar text:', err)
}
})
// 设置系统tabBar文本
// Set system tabBar text
uni.setTabBarItem({
index: 2,
text: t('tabBar.settings'),
success: () => {},
fail: (err) => {
console.log('设置系统tabBar文本失败:', err)
console.log('Failed to set system tabBar text:', err)
}
})
} catch (error) {
console.log('更新tabBar文本时出错:', error)
console.log('Error updating tabBar text:', error)
}
}
// 监听语言切换事件
// Listen for language switch event
onMounted(() => {
// 监听语言变化,当语言改变时自动更新tabBar文本
// Listen for language change, automatically update tabBar text
watch(() => langStore.currentLang, () => {
console.log('语言已切换,更新tabBar文本')
// 语言切换后立即更新tabBar文本
console.log('Language switched, updating tabBar text')
// Update tabBar text immediately after language switch
updateTabBarText()
})
})

View file

@ -7,7 +7,7 @@ import store from './store'
import '@/style/index.scss'
import 'virtual:uno.css'
// 导入国际化相关功能
// Import i18n related functions
import { initI18n } from './i18n'
import { useLangStore } from './store/lang'
@ -17,7 +17,7 @@ export function createApp() {
app.use(routeInterceptor)
app.use(VueQueryPlugin)
// 初始化国际化
// Initialize i18n
initI18n()
return {

View file

@ -61,32 +61,32 @@ export default {
};
},
mounted() {
// 检测是否为移动设备且VUE_APP_H5_URL不为空,如果两个条件都满足则跳转到H5页面
// Check if mobile device and VUE_APP_H5_URL is set, if both met redirect to H5 page
if (this.isMobileDevice() && process.env.VUE_APP_H5_URL) {
window.location.href = process.env.VUE_APP_H5_URL;
return;
}
// 只有在启用CDN时才添加相关事件和功能
// Only add events and functions when CDN is enabled
if (this.isCDNEnabled) {
// 添加全局快捷键Alt+C用于显示缓存查看器
// Add global shortcut Alt+C to show cache viewer
document.addEventListener('keydown', this.handleKeyDown);
// 在全局对象上添加缓存检查方法,便于调试
// Add cache check method to global object for debugging
window.checkCDNCacheStatus = () => {
this.showCacheViewer = true;
};
// 在控制台输出提示信息
// Output hints in console
console.info(
'%c[' + this.$t('system.name') + '] ' + this.$t('cache.cdnEnabled'),
'color: #409EFF; font-weight: bold;'
);
console.info(
'按下 Alt+C 组合键或在控制台运行 checkCDNCacheStatus() 可以查看CDN缓存状态'
'Press Alt+C or run checkCDNCacheStatus() in console to view CDN cache status'
);
// 检查Service Worker状态
// Check Service Worker status
this.checkServiceWorkerStatus();
} else {
console.info(
@ -96,25 +96,25 @@ export default {
}
},
beforeDestroy() {
// 只有在启用CDN时才需要移除事件监听
// Only remove event listener when CDN is enabled
if (this.isCDNEnabled) {
document.removeEventListener('keydown', this.handleKeyDown);
}
},
methods: {
handleKeyDown(e) {
// Alt+C 快捷键
// Alt+C Shortcut
if (e.altKey && e.key === 'c') {
this.showCacheViewer = true;
}
},
isMobileDevice() {
// 检测是否为移动设备的函数
// Function to check if mobile device
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
},
async checkServiceWorkerStatus() {
// 检查Service Worker是否已注册
// Check if Service Worker is registered
if ('serviceWorker' in navigator) {
try {
const registrations = await navigator.serviceWorker.getRegistrations();
@ -124,7 +124,7 @@ export default {
'color: #67C23A; font-weight: bold;'
);
// 输出缓存状态到控制台
// Output cache status to console
setTimeout(async () => {
const hasCaches = await logCacheStatus();
if (!hasCaches) {
@ -133,7 +133,7 @@ export default {
'color: #E6A23C; font-weight: bold;'
);
// 开发环境下提供额外提示
// Provide extra hints in dev environment
if (process.env.NODE_ENV === 'development') {
console.info(
'%c[' + this.$t('system.name') + '] ' + this.$t('cache.swDevEnvWarning'),
@ -164,7 +164,7 @@ export default {
}
}
} catch (error) {
console.error('检查Service Worker状态失败:', error);
console.error('Failed to check Service Worker status:', error);
}
} else {
console.warn(this.$t('cache.swNotSupported'));

View file

@ -10,17 +10,17 @@ import './styles/global.scss';
import { register as registerServiceWorker } from './registerServiceWorker';
import featureManager from './utils/featureManager';
// 创建事件总线,用于组件间通信
// Create event bus for component communication
Vue.prototype.$eventBus = new Vue();
Vue.use(ElementUI);
Vue.config.productionTip = false
// 注册Service Worker
// Register Service Worker
registerServiceWorker();
// 创建Vue实例
// Create Vue Instance
new Vue({
router,
store,

9
main/xiaozhi-server/.gitignore vendored Normal file
View file

@ -0,0 +1,9 @@
models/iic/SenseVoiceSmall/model.pt
data/
tmp/
*.mp3
*.wav
*.log
__pycache__/
*.pyc
.DS_Store

View file

@ -0,0 +1,43 @@
# Joe AI - Future Features TODO
## Ready for Testing
- [x] Multilingual support (responds in user's language)
- [x] CGM status always in context
- [x] CGM trends injection when asked
- [x] News RAG injection when asked
- [x] History RAG (past conversations)
- [x] Concise, casual persona
## Planned Features
- [ ] Schedule/Calendar awareness
- Integrate with Google Calendar or iCloud
- Detect queries like "what do I have tomorrow?"
- Add `needs_schedule` to classifier
- [ ] Class notes RAG
- Index notes/documents for specific classes
- Useful for study help, assignment reminders
- Add `needs_class_notes` to classifier
- [ ] Activity tracking (LOCAL on device, exposed via MCP)
- Use gyroscope + accelerometer for step counting
- Detect activity level (walking, stationary, sleeping)
- Expose as MCP tool: `get_activity_stats`
- Similar to existing `get_battery_level` pattern
- Server can query when relevant to conversation
- [ ] Reduce classifier latency
- Currently 4-7 seconds per call
- Consider smaller model for intent detection
- Or run classifier in parallel with other processing
## Architecture Notes
- Context classifier: `core/utils/cgm_intent.py`
- Context injection: `core/connection.py` (lines ~930-1000)
- Client configs: `data/<client-id>/config.json`
- Persona prompts: `data/<client-id>/prompt.txt`
To add a new context type:
1. Update classifier prompt in `cgm_intent.py`
2. Add injection logic in `connection.py`
3. (Optional) Add config flag in client's `config.json`

View file

@ -77,5 +77,13 @@
{{ dynamic_context }}
</context>
<intent_triggers>
If the user asks about the following topics, output the corresponding trigger ONLY, do not answer yourself:
- Weather: [[WEATHER]]
- Battery level / Device status: [[BATTERY]]
- News / Current events: [[NEWS: <search_query>]]
</intent_triggers>
<memory>
</memory>

View file

@ -10,6 +10,9 @@ from core.http_server import SimpleHttpServer
from core.websocket_server import WebSocketServer
from core.utils.util import check_ffmpeg_installed
from core.utils.gc_manager import get_gc_manager
from core.utils.npr_scraper import news_scraper_task
from core.utils.cgm_manager import cgm_background_task
from core.utils.pump_manager import create_pump_background_task
TAG = __name__
logger = setup_logging()
@ -17,9 +20,9 @@ logger = setup_logging()
async def wait_for_exit() -> None:
"""
阻塞直到收到 Ctrl‑C / SIGTERM。
- Unix: 使用 add_signal_handler
- Windows: 依赖 KeyboardInterrupt
Block until Ctrl-C / SIGTERM is received.
- Unix: Use add_signal_handler
- Windows: Rely on KeyboardInterrupt
"""
loop = asyncio.get_running_loop()
stop_event = asyncio.Event()
@ -29,8 +32,8 @@ async def wait_for_exit() -> None:
loop.add_signal_handler(sig, stop_event.set)
await stop_event.wait()
else:
# Windows:await一个永远pending的fut,
# 让 KeyboardInterrupt 冒泡到 asyncio.run,以此消除遗留普通线程导致进程退出阻塞的问题
# Windows: await a forever pending fut,
# Let KeyboardInterrupt bubble up to asyncio.run, resolving the issue of lingering threads blocking process exit
try:
await asyncio.Future()
except KeyboardInterrupt: # Ctrl‑C
@ -38,40 +41,46 @@ async def wait_for_exit() -> None:
async def monitor_stdin():
"""监控标准输入,消费回车键"""
"""Monitor standard input, consume enter key"""
while True:
await ainput() # 异步等待输入,消费回车
await ainput() # Asynchronously wait for input, consume enter key
async def main():
check_ffmpeg_installed()
config = load_config()
# auth_key优先级:配置文件server.auth_key > manager-api.secret > 自动生成
# auth_key用于jwt认证,比如视觉分析接口的jwt认证、ota接口的token生成与websocket认证
# 获取配置文件中的auth_key
# auth_key priority: config file server.auth_key > manager-api.secret > automatically generated
# auth_key is used for jwt authentication, such as jwt authentication for vision analysis interface, ota interface token generation and websocket authentication
# Get auth_key from config file
auth_key = config["server"].get("auth_key", "")
# 验证auth_key,无效则尝试使用manager-api.secret
# Verify auth_key, if invalid try to use manager-api.secret
if not auth_key or len(auth_key) == 0 or "你" in auth_key:
auth_key = config.get("manager-api", {}).get("secret", "")
# 验证secret,无效则生成随机密钥
# Verify secret, if invalid generate random key
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 监控任务
# Add stdin monitoring task
stdin_task = asyncio.create_task(monitor_stdin())
# 启动全局GC管理器(5分钟清理一次)
# Start global GC manager (clean up every 5 minutes)
gc_manager = get_gc_manager(interval_seconds=300)
await gc_manager.start()
# 启动 WebSocket 服务器
# Start NPR news scraper
scraper_task = asyncio.create_task(news_scraper_task())
# Start CGM scraper
cgm_task = asyncio.create_task(cgm_background_task())
# Start Pump scraper
pump_task = asyncio.create_task(create_pump_background_task())
# Start WebSocket server
ws_server = WebSocketServer(config)
ws_task = asyncio.create_task(ws_server.start())
# 启动 Simple http 服务器
# Start Simple http server
ota_server = SimpleHttpServer(config)
ota_task = asyncio.create_task(ota_server.start())
@ -79,74 +88,89 @@ async def main():
port = int(config["server"].get("http_port", 8003))
if not read_config_from_api:
logger.bind(tag=TAG).info(
"OTA接口是\t\thttp://{}:{}/xiaozhi/ota/",
"OTA interface is\t\thttp://{}:{}/xiaozhi/ota/",
get_local_ip(),
port,
)
logger.bind(tag=TAG).info(
"视觉分析接口是\thttp://{}:{}/mcp/vision/explain",
"Vision analysis interface is\thttp://{}:{}/mcp/vision/explain",
get_local_ip(),
port,
)
mcp_endpoint = config.get("mcp_endpoint", None)
if mcp_endpoint is not None and "你" not in mcp_endpoint:
# 校验MCP接入点格式
# Validate MCP endpoint format
if validate_mcp_endpoint(mcp_endpoint):
logger.bind(tag=TAG).info("mcp接入点是\t{}", mcp_endpoint)
# 将mcp计入点地址转成调用点
logger.bind(tag=TAG).info("MCP endpoint is\t{}", mcp_endpoint)
# Convert mcp endpoint address to call point
mcp_endpoint = mcp_endpoint.replace("/mcp/", "/call/")
config["mcp_endpoint"] = mcp_endpoint
else:
logger.bind(tag=TAG).error("mcp接入点不符合规范")
config["mcp_endpoint"] = "你的接入点 websocket地址"
logger.bind(tag=TAG).error("MCP endpoint is invalid")
config["mcp_endpoint"] = "Your endpoint websocket address"
# 获取WebSocket配置,使用安全的默认值
# Get WebSocket config, use safe defaults
websocket_port = 8000
server_config = config.get("server", {})
if isinstance(server_config, dict):
websocket_port = int(server_config.get("port", 8000))
# Determine final websocket address for logging
final_ws_url = f"ws://{get_local_ip()}:{websocket_port}/xiaozhi/v1/"
websocket_config = server_config.get("websocket")
# Check if config is valid (using the same logic as http_server.py)
if websocket_config:
final_ws_url = websocket_config
logger.bind(tag=TAG).info(
"Websocket地址是\tws://{}:{}/xiaozhi/v1/",
get_local_ip(),
websocket_port,
"Websocket address is\t{}",
final_ws_url,
)
logger.bind(tag=TAG).info(
"=======上面的地址是websocket协议地址,请勿用浏览器访问======="
"======= The address above is a websocket protocol address, please do not access it with a browser ======="
)
logger.bind(tag=TAG).info(
"如想测试websocket请用谷歌浏览器打开test目录下的test_page.html"
"If you want to test websocket, please open test_page.html in the test directory with Google Chrome"
)
logger.bind(tag=TAG).info(
"=============================================================\n"
)
try:
await wait_for_exit() # 阻塞直到收到退出信号
await wait_for_exit() # Block until exit signal is received
except asyncio.CancelledError:
print("任务被取消,清理资源中...")
print("Task cancelled, cleaning up resources...")
finally:
# 停止全局GC管理器
# Stop global GC manager
await gc_manager.stop()
# 取消所有任务(关键修复点)
# Cancel all tasks (critical repair point)
stdin_task.cancel()
ws_task.cancel()
if ota_task:
ota_task.cancel()
# 等待任务终止(必须加超时)
scraper_task.cancel()
cgm_task.cancel()
pump_task.cancel()
# Wait for task termination (must add timeout)
tasks_to_wait = [stdin_task, ws_task, scraper_task, cgm_task, pump_task]
if ota_task:
tasks_to_wait.append(ota_task)
await asyncio.wait(
[stdin_task, ws_task, ota_task] if ota_task else [stdin_task, ws_task],
tasks_to_wait,
timeout=3.0,
return_when=asyncio.ALL_COMPLETED,
)
print("服务器已关闭,程序退出。")
print("Server closed, program exited.")
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("手动中断,程序终止。")
print("Manual interruption, program terminated.")

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1 @@
/Users/mcmillan/src/xiaozhi-esp32-server/main/xiaozhi-server/config.yaml

View file

@ -5,7 +5,7 @@ from config.manage_api_client import init_service, get_server_config, get_agent_
def get_project_dir():
"""获取项目根目录"""
"""Get project root directory"""
return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/"
@ -16,10 +16,10 @@ def read_config(config_path):
def load_config():
"""加载配置文件"""
"""Load configuration file"""
from core.utils.cache.manager import cache_manager, CacheType
# 检查缓存
# Check cache
cached_config = cache_manager.get(CacheType.CONFIG, "main_config")
if cached_config is not None:
return cached_config
@ -27,7 +27,7 @@ def load_config():
default_config_path = get_project_dir() + "config.yaml"
custom_config_path = get_project_dir() + "data/.config.yaml"
# 加载默认配置
# Load default config
default_config = read_config(default_config_path)
custom_config = read_config(custom_config_path)
@ -35,30 +35,30 @@ def load_config():
import asyncio
try:
loop = asyncio.get_running_loop()
# 如果已经在事件循环中,使用异步版本
# If already in event loop, use async version
config = asyncio.run_coroutine_threadsafe(
get_config_from_api_async(custom_config), loop
).result()
except RuntimeError:
# 如果不在事件循环中(启动时),创建新的事件循环
# If not in event loop (startup), create new event loop
config = asyncio.run(get_config_from_api_async(custom_config))
else:
# 合并配置
# Merge config
config = merge_configs(default_config, custom_config)
# 初始化目录
# Initialize directories
ensure_directories(config)
# 缓存配置
# Cache config
cache_manager.set(CacheType.CONFIG, "main_config", config)
return config
async def get_config_from_api_async(config):
"""从Java API获取配置(异步版本)"""
# 初始化API客户端
"""Get config from Java API (async version)"""
# Initialize API client
init_service(config)
# 获取服务器配置
# Get server config
config_data = await get_server_config()
if config_data is None:
raise Exception("Failed to fetch server config from API")
@ -69,7 +69,7 @@ async def get_config_from_api_async(config):
"secret": config["manager-api"].get("secret", ""),
}
auth_enabled = config_data.get("server", {}).get("auth", {}).get("enabled", False)
# server的配置以本地为准
# server config takes precedence from local
if config.get("server"):
config_data["server"] = {
"ip": config["server"].get("ip", ""),
@ -79,26 +79,26 @@ async def get_config_from_api_async(config):
"auth_key": config["server"].get("auth_key", ""),
}
config_data["server"]["auth"] = {"enabled": auth_enabled}
# 如果服务器没有prompt_template,则从本地配置读取
# If server does not have prompt_template, read from local config
if not config_data.get("prompt_template"):
config_data["prompt_template"] = config.get("prompt_template")
return config_data
async def get_private_config_from_api(config, device_id, client_id):
"""从Java API获取私有配置"""
"""Get private config from Java API"""
return await get_agent_models(device_id, client_id, config["selected_module"])
def ensure_directories(config):
"""确保所有配置路径存在"""
"""Ensure all config, paths exist"""
dirs_to_create = set()
project_dir = get_project_dir() # 获取项目根目录
# 日志文件目录
project_dir = get_project_dir() # Get project root directory
# Log file directory
log_dir = config.get("log", {}).get("log_dir", "tmp")
dirs_to_create.add(os.path.join(project_dir, log_dir))
# ASR/TTS模块输出目录
# ASR/TTS module output directory
for module in ["ASR", "TTS"]:
if config.get(module) is None:
continue
@ -107,7 +107,7 @@ def ensure_directories(config):
if output_dir:
dirs_to_create.add(output_dir)
# 根据selected_module创建模型目录
# Create model directories according to selected_module
selected_modules = config.get("selected_module", {})
for module_type in ["ASR", "LLM", "TTS"]:
selected_provider = selected_modules.get(module_type)
@ -123,24 +123,24 @@ def ensure_directories(config):
full_model_dir = os.path.join(project_dir, output_dir)
dirs_to_create.add(full_model_dir)
# 统一创建目录(保留原data目录创建)
# Create directories uniformly (preserve original data directory creation)
for dir_path in dirs_to_create:
try:
os.makedirs(dir_path, exist_ok=True)
except PermissionError:
print(f"警告:无法创建目录 {dir_path},请检查写入权限")
print(f"Warning: Unable to create directory {dir_path}, please check write permissions")
def merge_configs(default_config, custom_config):
"""
递归合并配置,custom_config优先级更高
Recursively merge configurations, custom_config has higher priority
Args:
default_config: 默认配置
custom_config: 用户自定义配置
default_config: Default configuration
custom_config: User custom configuration
Returns:
合并后的配置
Merged configuration
"""
if not isinstance(default_config, Mapping) or not isinstance(
custom_config, Mapping

View file

@ -10,8 +10,8 @@ _logger_initialized = False
def get_module_abbreviation(module_name, module_dict):
"""获取模块名称的缩写,如果为空则返回00
如果名称中包含下划线,则返回下划线后面的前两个字符
"""Get the abbreviation of the module name, return 00 if empty
If the name contains an underscore, return the first two characters after the underscore
"""
module_value = module_dict.get(module_name, "")
if not module_value:
@ -23,7 +23,7 @@ def get_module_abbreviation(module_name, module_dict):
def build_module_string(selected_module):
"""构建模块字符串"""
"""Build module string"""
return (
get_module_abbreviation("VAD", selected_module)
+ get_module_abbreviation("ASR", selected_module)
@ -36,25 +36,25 @@ def build_module_string(selected_module):
def formatter(record):
"""为没有 tag 的日志添加默认值,并处理动态模块字符串"""
"""Add default value for logs without tag, and handle dynamic module string"""
record["extra"].setdefault("tag", record["name"])
# 如果没有设置 selected_module,使用默认值
# If selected_module is not set, use default value
record["extra"].setdefault("selected_module", "00000000000000")
# 将 selected_module 从 extra 提取到顶级,以支持 {selected_module} 格式
# Extract selected_module from extra to top level to support {selected_module} format
record["selected_module"] = record["extra"]["selected_module"]
return record["message"]
def setup_logging():
check_config_file()
"""从配置文件中读取日志配置,并设置日志输出格式和级别"""
"""Read log configuration from config file, and set log output format and level"""
config = load_config()
log_config = config["log"]
global _logger_initialized
# 第一次初始化时配置日志
# Configure logging on first initialization
if not _logger_initialized:
# 使用默认的模块字符串进行初始化
# Initialize with default module string
logger.configure(
extra={
"selected_module": log_config.get("selected_module", "00000000000000"),
@ -80,35 +80,35 @@ def setup_logging():
os.makedirs(log_dir, exist_ok=True)
os.makedirs(data_dir, exist_ok=True)
# 配置日志输出
# Configure log output
logger.remove()
# 输出到控制台
logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter)
# Output to console
logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter, enqueue=True)
# 输出到文件 - 统一目录,按大小轮转
# 日志文件完整路径
# Output to file - unified directory, rotate by size
# Log file full path
log_file_path = os.path.join(log_dir, log_file)
# 添加日志处理器
# Add log handler
logger.add(
log_file_path,
format=log_format_file,
level=log_level,
filter=formatter,
rotation="10 MB", # 每个文件最大10MB
retention="30 days", # 保留30天
rotation="10 MB", # Max 10MB per file
retention="30 days", # Keep for 30 days
compression=None,
encoding="utf-8",
enqueue=True, # 异步安全
enqueue=True, # Async safe
backtrace=True,
diagnose=True,
)
_logger_initialized = True # 标记为已初始化
_logger_initialized = True # Mark as initialized
return logger
def create_connection_logger(selected_module_str):
"""为连接创建独立的日志器,绑定特定的模块字符串"""
"""Create independent logger for connection, bind specific module string"""
return logger.bind(selected_module=selected_module_str)

View file

@ -14,16 +14,16 @@ class DeviceNotFoundException(Exception):
class DeviceBindException(Exception):
def __init__(self, bind_code):
self.bind_code = bind_code
super().__init__(f"设备绑定异常,绑定码: {bind_code}")
super().__init__(f"Device binding exception, bind code: {bind_code}")
class ManageApiClient:
_instance = None
_async_clients = {} # 为每个事件循环存储独立的客户端
_async_clients = {} # Store independent clients for each event loop
_secret = None
def __new__(cls, config):
"""单例模式确保全局唯一实例,并支持传入配置参数"""
"""Singleton pattern ensures globally unique instance, and supports passing configuration parameters"""
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._init_client(config)
@ -31,38 +31,38 @@ class ManageApiClient:
@classmethod
def _init_client(cls, config):
"""初始化配置(延迟创建客户端)"""
"""Initialize configuration (delay creating client)"""
cls.config = config.get("manager-api")
if not cls.config:
raise Exception("manager-api配置错误")
raise Exception("manager-api config error")
if not cls.config.get("url") or not cls.config.get("secret"):
raise Exception("manager-api的url或secret配置错误")
raise Exception("manager-api url or secret config error")
if "你" in cls.config.get("secret"):
raise Exception("请先配置manager-api的secret")
raise Exception("Please configure manager-api secret first")
cls._secret = cls.config.get("secret")
cls.max_retries = cls.config.get("max_retries", 6) # 最大重试次数
cls.retry_delay = cls.config.get("retry_delay", 10) # 初始重试延迟(秒)
# 不在这里创建 AsyncClient,延迟到实际使用时创建
cls.max_retries = cls.config.get("max_retries", 6) # Max retries
cls.retry_delay = cls.config.get("retry_delay", 10) # Initial retry delay (seconds)
# Do not create AsyncClient here, delay until actual use
cls._async_clients = {}
@classmethod
async def _ensure_async_client(cls):
"""确保异步客户端已创建(为每个事件循环创建独立的客户端)"""
"""Ensure async client is created (create independent client for each event loop)"""
import asyncio
try:
loop = asyncio.get_running_loop()
loop_id = id(loop)
# 为每个事件循环创建独立的客户端
# Create independent client for each event loop
if loop_id not in cls._async_clients:
# 服务端可能主动关闭连接,httpx 连接池无法正确检测和清理
# Server may actively close connection, httpx connection pool cannot detect and clean up correctly
limits = httpx.Limits(
max_keepalive_connections=0, # 禁用 keep-alive,每次都新建连接
max_keepalive_connections=0, # Disable keep-alive, create new connection every time
)
cls._async_clients[loop_id] = httpx.AsyncClient(
base_url=cls.config.get("url"),
@ -72,17 +72,17 @@ class ManageApiClient:
"Authorization": "Bearer " + cls._secret,
},
timeout=cls.config.get("timeout", 30),
limits=limits, # 使用限制
limits=limits, # Use limits
)
return cls._async_clients[loop_id]
except RuntimeError:
# 如果没有运行中的事件循环,创建一个临时的
raise Exception("必须在异步上下文中调用")
# If there is no running event loop, create a temporary one
raise Exception("Must be called in async context")
@classmethod
async def _async_request(cls, method: str, endpoint: str, **kwargs) -> Dict:
"""发送单次异步HTTP请求并处理响应"""
# 确保客户端已创建
"""Send single async HTTP request and handle response"""
# Ensure client is created
client = await cls._ensure_async_client()
endpoint = endpoint.lstrip("/")
response = None
@ -92,31 +92,31 @@ class ManageApiClient:
result = response.json()
# 处理API返回的业务错误
# Handle business errors returned by API
if result.get("code") == 10041:
raise DeviceNotFoundException(result.get("msg"))
elif result.get("code") == 10042:
raise DeviceBindException(result.get("msg"))
elif result.get("code") != 0:
raise Exception(f"API返回错误: {result.get('msg', '未知错误')}")
raise Exception(f"API returned error: {result.get('msg', 'Unknown error')}")
# 返回成功数据
# Return success data
return result.get("data") if result.get("code") == 0 else None
finally:
# 确保响应被关闭(即使异常也会执行)
# Ensure response is closed (executed even if exception occurs)
if response is not None:
await response.aclose()
@classmethod
def _should_retry(cls, exception: Exception) -> bool:
"""判断异常是否应该重试"""
# 网络连接相关错误
"""Determine if exception should be retried"""
# Network connection related errors
if isinstance(
exception, (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError)
):
return True
# HTTP状态码错误
# HTTP status code errors
if isinstance(exception, httpx.HTTPStatusError):
status_code = exception.response.status_code
return status_code in [408, 429, 500, 502, 503, 504]
@ -125,31 +125,31 @@ class ManageApiClient:
@classmethod
async def _execute_async_request(cls, method: str, endpoint: str, **kwargs) -> Dict:
"""带重试机制的异步请求执行器"""
"""Async request executor with retry mechanism"""
import asyncio
retry_count = 0
while retry_count <= cls.max_retries:
try:
# 执行异步请求
# Execute async request
return await cls._async_request(method, endpoint, **kwargs)
except Exception as e:
# 判断是否应该重试
# Determine if retry is needed
if retry_count < cls.max_retries and cls._should_retry(e):
retry_count += 1
print(
f"{method} {endpoint} 异步请求失败,将在 {cls.retry_delay:.1f} 秒后进行第 {retry_count} 次重试"
f"{method} {endpoint} async request failed, will retry for the {retry_count} time in {cls.retry_delay:.1f} seconds"
)
await asyncio.sleep(cls.retry_delay)
continue
else:
# 不重试,直接抛出异常
# Do not retry, raise exception directly
raise
@classmethod
def safe_close(cls):
"""安全关闭所有异步连接池"""
"""Safely close all async connection pools"""
import asyncio
for client in list(cls._async_clients.values()):
@ -162,7 +162,7 @@ class ManageApiClient:
async def get_server_config() -> Optional[Dict]:
"""获取服务器基础配置"""
"""Get server base configuration"""
return await ManageApiClient._instance._execute_async_request(
"POST", "/config/server-base"
)
@ -171,7 +171,7 @@ async def get_server_config() -> Optional[Dict]:
async def get_agent_models(
mac_address: str, client_id: str, selected_module: Dict
) -> Optional[Dict]:
"""获取代理模型配置"""
"""Get agent model configuration"""
return await ManageApiClient._instance._execute_async_request(
"POST",
"/config/agent-models",
@ -184,21 +184,21 @@ async def get_agent_models(
async def generate_and_save_chat_summary(session_id: str) -> Optional[Dict]:
"""生成并保存聊天记录总结"""
"""Generate and save chat summary"""
try:
return await ManageApiClient._instance._execute_async_request(
"POST",
f"/agent/chat-summary/{session_id}/save",
)
except Exception as e:
print(f"生成并保存聊天记录总结失败: {e}")
print(f"Failed to generate and save chat summary: {e}")
return None
async def report(
mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time
) -> Optional[Dict]:
"""异步聊天记录上报"""
"""Async chat history report"""
if not content or not ManageApiClient._instance:
return None
try:
@ -217,7 +217,7 @@ async def report(
},
)
except Exception as e:
print(f"TTS上报失败: {e}")
print(f"TTS report failed: {e}")
return None

View file

@ -11,23 +11,23 @@ def check_config_file():
if config_file_valid:
return
"""
简化的配置检查,仅提示用户配置文件的使用情况
Simplified configuration check, only prompts the user for configuration file usage
"""
custom_config_file = get_project_dir() + "data/." + default_config_file
if not os.path.exists(custom_config_file):
raise FileNotFoundError(
"找不到data/.config.yaml文件,请按教程确认该配置文件是否存在"
"File data/.config.yaml not found, please check the tutorial to confirm if the configuration file exists"
)
# 检查是否从API读取配置
# Check if reading config from API
config = load_config()
if config.get("read_config_from_api", False):
print("从API读取配置")
print("Reading config from API")
old_config_origin = read_config(custom_config_file)
if old_config_origin.get("selected_module") is not None:
error_msg = "您的配置文件好像既包含智控台的配置又包含本地配置:\n"
error_msg += "\n建议您:\n"
error_msg += "1、将根目录的config_from_api.yaml文件复制到data下,重命名为.config.yaml\n"
error_msg += "2、按教程配置好接口地址和密钥\n"
error_msg = "Your configuration file seems to contain both console configuration and local configuration:\n"
error_msg += "\nSuggestion:\n"
error_msg += "1. Copy the config_from_api.yaml file in the root directory to data and rename it to .config.yaml\n"
error_msg += "2. Configure the interface address and key according to the tutorial\n"
raise ValueError(error_msg)
config_file_valid = True

View file

@ -1,27 +1,27 @@
# 如果你只想轻量化安装xiaozhi-server,只使用本地的配置文件,不需要理会这个文件,不需要改动本文件任何东西
# 如果你想从manager-api获取配置,请往下看:
# 请将本文件复制到xiaozhi-server/data目录下,没有data目录,请创建一个,并将复制过去的文件命名为.config.yaml
# 注意如果data目录有.config.yaml文件,请先删除它
# 先启动manager-api和manager-web,注册一个账号,第一个注册的账号为管理员
# 使用管理员,进入【参数管理】页面,找到【server.secret】,复制它到参数值,注意每次从零部署,server.secret都会变化
# 打开本data目录下的.config.yaml文件,修改manager-api.secret为刚才复制出来的server.secret
# If you only want a lightweight installation of xiaozhi-server using local config file, ignore this file and do not modify it.
# If you want to get config from manager-api, read below:
# Copy this file to xiaozhi-server/data directory. If data directory does not exist, create it. Name the copied file .config.yaml
# Note: If .config.yaml already exists in data directory, please delete it first
# First start manager-api and manager-web, register an account. The first registered account is admin
# Login as admin, go to [Parameter Management] page, find [server.secret], copy it to parameter value. Note that server.secret changes every time you deploy from scratch
# Open .config.yaml in data directory, modify manager-api.secret to the server.secret you just copied
server:
ip: 0.0.0.0
port: 8000
# http服务的端口,用于视觉分析接口
# HTTP service port, used for vision analysis interface
http_port: 8003
# 视觉分析接口地址
# 向设备发送的视觉分析的接口地址
# 如果按下面默认的写法,系统会自动生成视觉识别地址,并输出在启动日志里,这个地址你可以直接用浏览器访问确认一下
# 当你使用docker部署或使用公网部署(使用ssl、域名)时,不一定准确
# 所以如果你使用docker部署时,将vision_explain设置成局域网地址
# 如果你使用公网部署时,将vision_explain设置成公网地址
vision_explain: http://你的ip或者域名:端口号/mcp/vision/explain
# Vision analysis interface address
# Vision analysis interface address sent to device
# If you use the default setting below, the system will automatically generate the vision recognition address and output it in the startup log. You can verify this address by accessing it in a browser directly
# When deploying with docker or public network (using ssl, domain), it might not be accurate
# So if deploying with docker, set vision_explain to LAN address
# If deploying with public network, set vision_explain to public address
vision_explain: http://YOUR_IP_OR_DOMAIN:PORT/mcp/vision/explain
manager-api:
# 你的manager-api的地址,最好使用局域网ip
# 如果使用docker部署,请使用填写成 http://xiaozhi-esp32-server-web:8002/xiaozhi
# Your manager-api address, preferably use LAN IP
# If deploying with docker, please fill in http://xiaozhi-esp32-server-web:8002/xiaozhi
url: http://127.0.0.1:8002/xiaozhi
# 你的manager-api的token,就是刚才复制出来的server.secret
secret: 你的server.secret值
# 默认系统提示词模板文件
prompt_template: agent-base-prompt.txt
# Your manager-api token, which is the server.secret you copied earlier
secret: YOUR_SERVER_SECRET_VALUE
# Default system prompt template file
prompt_template: data/agent-base-prompt.txt

View file

@ -8,7 +8,7 @@ class BaseHandler:
self.logger = setup_logging()
def _add_cors_headers(self, response):
"""添加CORS头信息"""
"""Add CORS headers"""
response.headers["Access-Control-Allow-Headers"] = (
"client-id, content-type, device-id, authorization"
)
@ -16,9 +16,9 @@ class BaseHandler:
response.headers["Access-Control-Allow-Origin"] = "*"
async def handle_options(self, request):
"""处理OPTIONS请求,添加CORS头信息"""
"""Handle OPTIONS request, add CORS headers"""
response = web.Response(body=b"", content_type="text/plain")
self._add_cors_headers(response)
# 添加允许的方法
# Add allowed methods
response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
return response

View file

@ -48,7 +48,7 @@ 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")
@ -99,18 +99,18 @@ class OTAHandler(BaseHandler):
f"Firmware cache refreshed: {len(files_by_model)} models"
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"刷新固件缓存失败: {e}")
self.logger.bind(tag=TAG).error(f"Failed to refresh firmware cache: {e}")
# keep previous cache if any
def generate_password_signature(self, content: str, secret_key: str) -> str:
"""生成MQTT密码签名
"""Generate MQTT password signature
Args:
content: 签名内容 (clientId + '|' + username)
secret_key: 密钥
content: Signature content (clientId + '|' + username)
secret_key: Secret key
Returns:
str: Base64编码的HMAC-SHA256签名
str: Base64 encoded HMAC-SHA256 signature
"""
try:
hmac_obj = hmac.new(
@ -123,25 +123,25 @@ class OTAHandler(BaseHandler):
return ""
def _get_websocket_url(self, local_ip: str, port: int) -> str:
"""获取websocket地址
"""Get websocket address
Args:
local_ip: 本地IP地址
port: 端口号
local_ip: Local IP address
port: Port number
Returns:
str: websocket地址
str: websocket address
"""
server_config = self.config["server"]
websocket_config = server_config.get("websocket", "")
if "你的" not in websocket_config:
if "YOUR_" not in websocket_config and "你的" not in websocket_config:
return websocket_config
else:
return f"ws://{local_ip}:{port}/xiaozhi/v1/"
async def handle_post(self, request):
"""处理 OTA POST 请求
"""Handle OTA POST request
This handler will:
- read device id/client id (as before)
@ -151,21 +151,28 @@ class OTAHandler(BaseHandler):
"""
try:
data = await request.text()
self.logger.bind(tag=TAG).debug(f"OTA请求方法: {request.method}")
self.logger.bind(tag=TAG).debug(f"OTA请求头: {request.headers}")
self.logger.bind(tag=TAG).debug(f"OTA请求数据: {data}")
self.logger.bind(tag=TAG).debug(f"OTA request method: {request.method}")
self.logger.bind(tag=TAG).debug(f"OTA request headers: {request.headers}")
self.logger.bind(tag=TAG).debug(f"OTA request data: {data}")
device_id = request.headers.get("device-id", "")
if device_id:
self.logger.bind(tag=TAG).info(f"OTA请求设备ID: {device_id}")
self.logger.bind(tag=TAG).info(f"OTA request DeviceID: {device_id}")
else:
raise Exception("OTA请求设备ID为空")
raise Exception("OTA request DeviceID is empty")
client_id = request.headers.get("client-id", "")
if client_id:
self.logger.bind(tag=TAG).info(f"OTA请求ClientID: {client_id}")
self.logger.bind(tag=TAG).info(f"OTA request ClientID: {client_id}")
else:
raise Exception("OTA请求ClientID为空")
raise Exception("OTA request ClientID is empty")
if device_id == "b0:a6:04:5b:d7:98":
old_client_id = client_id
client_id = "26ea0ba9-2d55-4368-a56d-19c4a27c0772"
self.logger.bind(tag=TAG).info(
f"[FORCE MAP OTA] device {device_id}: {old_client_id} -> {client_id}"
)
data_json = {}
try:
@ -234,18 +241,18 @@ class OTAHandler(BaseHandler):
# existing mqtt/websocket logic (unchanged)
mqtt_gateway_endpoint = server_config.get("mqtt_gateway")
if mqtt_gateway_endpoint: # 如果配置了非空字符串
# 尝试从请求数据中获取设备型号(已解析 above)
if mqtt_gateway_endpoint: # If non-empty string is configured
# Try to get device model from request data (parsed above)
try:
group_id = f"GID_{device_model}".replace(":", "_").replace(" ", "_")
except Exception as e:
self.logger.bind(tag=TAG).error(f"获取设备型号失败: {e}")
self.logger.bind(tag=TAG).error(f"Failed to get device model: {e}")
group_id = "GID_default"
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)
@ -253,10 +260,10 @@ class OTAHandler(BaseHandler):
"utf-8"
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"生成用户名失败: {e}")
self.logger.bind(tag=TAG).error(f"Failed to generate username: {e}")
username = ""
# 生成密码
# Generate password
password = ""
signature_key = server_config.get("mqtt_signature_key", "")
if signature_key:
@ -264,11 +271,11 @@ class OTAHandler(BaseHandler):
mqtt_client_id + "|" + username, signature_key
)
if not password:
password = "" # 签名失败则留空,由设备决定是否允许无密码
password = "" # Leave empty if signature fails, let device decide whether to allow no password
else:
self.logger.bind(tag=TAG).warning("缺少MQTT签名密钥,密码留空")
self.logger.bind(tag=TAG).warning("Missing MQTT signature key, password left empty")
# 构建MQTT配置(直接使用 mqtt_gateway 字符串)
# Build MQTT config (use mqtt_gateway string directly)
return_json["mqtt"] = {
"endpoint": mqtt_gateway_endpoint,
"client_id": mqtt_client_id,
@ -277,10 +284,10 @@ class OTAHandler(BaseHandler):
"publish_topic": "device-server",
"subscribe_topic": f"devices/p2p/{mac_address_safe}",
}
self.logger.bind(tag=TAG).info(f"为设备 {device_id} 下发MQTT网关配置")
self.logger.bind(tag=TAG).info(f"Sending MQTT gateway config for device {device_id}")
else: # 未配置 mqtt_gateway,下发 WebSocket
# 如果开启了认证,则进行认证校验
else: # No mqtt_gateway configured, send WebSocket
# If auth is enabled, perform auth verification
token = ""
if self.auth_enable:
if self.allowed_devices:
@ -294,7 +301,7 @@ class OTAHandler(BaseHandler):
"token": token,
}
self.logger.bind(tag=TAG).info(
f"未配置MQTT网关,为设备 {device_id} 下发WebSocket配置"
f"No MQTT gateway configured, sending WebSocket config for device {device_id}"
)
# Now check firmware files for updates
@ -304,7 +311,7 @@ class OTAHandler(BaseHandler):
candidates = files_by_model.get(device_model, [])
self.logger.bind(tag=TAG).info(
f"查找型号 {device_model} 的固件,找到 {len(candidates)} 个候选"
f"Searching firmware for model {device_model}, found {len(candidates)} candidates"
)
chosen_url = ""
@ -327,22 +334,22 @@ class OTAHandler(BaseHandler):
return_json["firmware"]["version"] = chosen_version
return_json["firmware"]["url"] = chosen_url
self.logger.bind(tag=TAG).info(
f"为设备 {device_id} 下发固件 {chosen_version} [如果地址前缀有误,请检查配置文件中的server.vision_explain]-> {chosen_url} "
f"Sending firmware {chosen_version} for device {device_id} [Check server.vision_explain if prefix error]-> {chosen_url} "
)
else:
self.logger.bind(tag=TAG).info(
f"设备 {device_id} 固件已是最新: {device_version}"
f"Device {device_id} firmware is up to date: {device_version}"
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"检查固件版本时出错: {e}")
self.logger.bind(tag=TAG).error(f"Error checking firmware version: {e}")
response = web.Response(
text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json",
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"OTA POST处理异常: {e}")
self.logger.bind(tag=TAG).error(f"OTA POST handling error: {e}")
return_json = {"success": False, "message": "request error."}
response = web.Response(
text=json.dumps(return_json, separators=(",", ":")),
@ -353,28 +360,28 @@ class OTAHandler(BaseHandler):
return response
async def handle_get(self, request):
"""处理 OTA GET 请求"""
"""Handle OTA GET request"""
try:
server_config = self.config["server"]
local_ip = get_local_ip()
# use websocket port for websocket URL
websocket_port = int(server_config.get("port", 8000))
websocket_url = self._get_websocket_url(local_ip, websocket_port)
message = f"OTA接口运行正常,向设备发送的websocket地址是:{websocket_url}"
message = f"OTA interface running normally, websocket address sent to device is: {websocket_url}"
response = web.Response(text=message, content_type="text/plain")
except Exception as e:
self.logger.bind(tag=TAG).error(f"OTA GET请求异常: {e}")
response = web.Response(text="OTA接口异常", content_type="text/plain")
self.logger.bind(tag=TAG).error(f"OTA GET request exception: {e}")
response = web.Response(text="OTA interface exception", content_type="text/plain")
finally:
self._add_cors_headers(response)
return response
async def handle_download(self, request):
"""
下载固件接口
Firmware download interface
URL: /xiaozhi/ota/download/{filename}
- 只允许下载 data/bin 目录下的 .bin 文件
- filename 必须是 basename 且匹配安全的模式
- Only allow downloading .bin files in data/bin directory
- filename must be basename and match safe pattern
"""
try:
fname = request.match_info.get("filename", "")
@ -405,7 +412,7 @@ class OTAHandler(BaseHandler):
except web.HTTPError as e:
resp = e
except Exception as e:
self.logger.bind(tag=TAG).error(f"固件下载异常: {e}")
self.logger.bind(tag=TAG).error(f"Firmware download exception: {e}")
resp = web.Response(text="download error", status=500)
finally:
try:

View file

@ -13,86 +13,86 @@ from plugins_func.register import Action
TAG = __name__
# 设置最大文件大小为5MB
# Set max file size to 5MB
MAX_FILE_SIZE = 5 * 1024 * 1024
class VisionHandler(BaseHandler):
def __init__(self, config: dict):
super().__init__(config)
# 初始化认证工具
# Initialize auth tool
self.auth = AuthToken(config["server"]["auth_key"])
def _create_error_response(self, message: str) -> dict:
"""创建统一的错误响应格式"""
"""Create unified error response format"""
return {"success": False, "message": message}
def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]:
"""验证认证token"""
"""Verify auth token"""
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer "):
return False, None
token = auth_header[7:] # 移除"Bearer "前缀
token = auth_header[7:] # Remove "Bearer " prefix
return self.auth.verify_token(token)
async def handle_post(self, request):
"""处理 MCP Vision POST 请求"""
response = None # 初始化response变量
"""Handle MCP Vision POST request"""
response = None # Initialize response variable
try:
# 验证token
# Verify token
is_valid, token_device_id = self._verify_auth_token(request)
if not is_valid:
response = web.Response(
text=json.dumps(
self._create_error_response("无效的认证token或token已过期")
self._create_error_response("Invalid auth token or token expired")
),
content_type="application/json",
status=401,
)
return response
# 获取请求头信息
# Get request headers
device_id = request.headers.get("Device-Id", "")
client_id = request.headers.get("Client-Id", "")
if device_id != token_device_id:
raise ValueError("设备ID与token不匹配")
# 解析multipart/form-data请求
raise ValueError("Device ID does not match token")
# Parse multipart/form-data request
reader = await request.multipart()
# 读取question字段
# Read question field
question_field = await reader.next()
if question_field is None:
raise ValueError("缺少问题字段")
raise ValueError("Missing question field")
question = await question_field.text()
self.logger.bind(tag=TAG).debug(f"Question: {question}")
# 读取图片文件
# Read image file
image_field = await reader.next()
if image_field is None:
raise ValueError("缺少图片文件")
raise ValueError("Missing image file")
# 读取图片数据
# Read image data
image_data = await image_field.read()
if not image_data:
raise ValueError("图片数据为空")
raise ValueError("Image data is empty")
# 检查文件大小
# Check file size
if len(image_data) > MAX_FILE_SIZE:
raise ValueError(
f"图片大小超过限制,最大允许{MAX_FILE_SIZE/1024/1024}MB"
f"Image size exceeds limit, max allowed {MAX_FILE_SIZE/1024/1024}MB"
)
# 检查文件格式
# Check file format
if not is_valid_image_file(image_data):
raise ValueError(
"不支持的文件格式,请上传有效的图片文件(支持JPEG、PNG、GIF、BMP、TIFF、WEBP格式)"
"Unsupported file format, please upload a valid image file (supports JPEG, PNG, GIF, BMP, TIFF, WEBP)"
)
# 将图片转换为base64编码
# Convert image to base64 encoding
image_base64 = base64.b64encode(image_data).decode("utf-8")
# 如果开启了智控台,则从智控台获取模型配置
# If control panel is enabled, get model config from it
current_config = copy.deepcopy(self.config)
read_config_from_api = current_config.get("read_config_from_api", False)
if read_config_from_api:
@ -104,7 +104,7 @@ class VisionHandler(BaseHandler):
select_vllm_module = current_config["selected_module"].get("VLLM")
if not select_vllm_module:
raise ValueError("您还未设置默认的视觉分析模块")
raise ValueError("You have not set the default vision analysis module")
vllm_type = (
select_vllm_module
@ -113,7 +113,7 @@ class VisionHandler(BaseHandler):
)
if not vllm_type:
raise ValueError(f"无法找到VLLM模块对应的供应器{vllm_type}")
raise ValueError(f"Cannot find provider {vllm_type} for VLLM module")
vllm = create_instance(
vllm_type, current_config["VLLM"][select_vllm_module]
@ -132,15 +132,15 @@ class VisionHandler(BaseHandler):
content_type="application/json",
)
except ValueError as e:
self.logger.bind(tag=TAG).error(f"MCP Vision POST请求异常: {e}")
self.logger.bind(tag=TAG).error(f"MCP Vision POST request exception: {e}")
return_json = self._create_error_response(str(e))
response = web.Response(
text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json",
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"MCP Vision POST请求异常: {e}")
return_json = self._create_error_response("处理请求时发生错误")
self.logger.bind(tag=TAG).error(f"MCP Vision POST request exception: {e}")
return_json = self._create_error_response("Error occurred while processing request")
response = web.Response(
text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json",
@ -151,20 +151,20 @@ class VisionHandler(BaseHandler):
return response
async def handle_get(self, request):
"""处理 MCP Vision GET 请求"""
"""Handle MCP Vision GET request"""
try:
vision_explain = get_vision_url(self.config)
if vision_explain and len(vision_explain) > 0 and "null" != vision_explain:
message = (
f"MCP Vision 接口运行正常,视觉解释接口地址是:{vision_explain}"
f"MCP Vision interface running normally, vision explain interface address is: {vision_explain}"
)
else:
message = "MCP Vision 接口运行不正常,请打开data目录下的.config.yaml文件,找到【server.vision_explain】,设置好地址"
message = "MCP Vision interface not running normally, please open .config.yaml in data directory, find [server.vision_explain] and set the address"
response = web.Response(text=message, content_type="text/plain")
except Exception as e:
self.logger.bind(tag=TAG).error(f"MCP Vision GET请求异常: {e}")
return_json = self._create_error_response("服务器内部错误")
self.logger.bind(tag=TAG).error(f"MCP Vision GET request exception: {e}")
return_json = self._create_error_response("Internal server error")
response = web.Response(
text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json",

View file

@ -5,18 +5,18 @@ import time
class AuthenticationError(Exception):
"""认证异常"""
"""Authentication Exception"""
pass
class AuthManager:
"""
统一授权认证管理器
生成与验证 client_id device_id token(HMAC-SHA256)认证三元组
token 中不含明文 client_id/device_id,只携带签名 + 时间戳; client_id/device_id在连接时传递
在 MQTT 中 client_id: client_id, username: device_id, password: token
在 Websocket 中,header:{Device-ID: device_id, Client-ID: client_id, Authorization: Bearer token, ......}
Unified authorization authentication manager
Generate and verify client_id device_id token (HMAC-SHA256) authentication triplet
Token does not contain plaintext client_id/device_id, only carries signature + timestamp; client_id/device_id is passed during connection
In MQTT: client_id: client_id, username: device_id, password: token
In Websocket: header:{Device-ID: device_id, Client-ID: client_id, Authorization: Bearer token, ......}
"""
def __init__(self, secret_key: str, expire_seconds: int = 60 * 60 * 24 * 30):
@ -27,7 +27,7 @@ class AuthManager:
self.secret_key = secret_key
def _sign(self, content: str) -> str:
"""HMAC-SHA256签名并Base64编码"""
"""HMAC-SHA256 signature and Base64 encoding"""
sig = hmac.new(
self.secret_key.encode("utf-8"), content.encode("utf-8"), hashlib.sha256
).digest()
@ -35,33 +35,33 @@ class AuthManager:
def generate_token(self, client_id: str, username: str) -> str:
"""
生成 token
Generate token
Args:
client_id: 设备连接ID
username: 设备用户名(通常为deviceId)
client_id: Device connection ID
username: Device username (usually deviceId)
Returns:
str: token字符串
str: token string
"""
ts = int(time.time())
content = f"{client_id}|{username}|{ts}"
signature = self._sign(content)
# token仅包含签名与时间戳,不包含明文信息
# token only contains signature and timestamp, no plaintext info
token = f"{signature}.{ts}"
return token
def verify_token(self, token: str, client_id: str, username: str) -> bool:
"""
验证token有效性
Verify token validity
Args:
token: 客户端传入的token
client_id: 连接使用的client_id
username: 连接使用的username
token: token passed by client
client_id: client_id used for connection
username: username used for connection
"""
try:
sig_part, ts_str = token.split(".")
ts = int(ts_str)
if int(time.time()) - ts > self.expire_seconds:
return False # 过期
return False # Expired
expected_sig = self._sign(f"{client_id}|{username}|{ts}")
if not hmac.compare_digest(sig_part, expected_sig):

File diff suppressed because it is too large Load diff

View file

@ -9,65 +9,82 @@ from core.providers.tts.dto.dto import SentenceType
from core.utils.wakeup_word import WakeupWordsConfig
from core.handle.sendAudioHandle import sendAudioMessage, send_tts_message
from core.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes
from core.providers.tools.device_mcp import (
MCPClient,
send_mcp_initialize_message,
send_mcp_tools_list_request,
)
TAG = __name__
WAKEUP_CONFIG = {
"refresh_time": 10,
"responses": [
"我一直都在呢,您请说。",
"在的呢,请随时吩咐我。",
"来啦来啦,请告诉我吧。",
"您请说,我正听着。",
"请您讲话,我准备好了。",
"请您说出指令吧。",
"我认真听着呢,请讲。",
"请问您需要什么帮助?",
"我在这里,等候您的指令。",
"I'm here, go ahead.",
"I'm listening, how can I help?",
"Ready for your command.",
"I'm right here.",
"Yes? I'm listening.",
"Tell me what you need.",
"Ready when you are.",
"How can I assist you?",
"Awaiting your instructions.",
],
}
# 创建全局的唤醒词配置管理器
# Global wakeup words config manager
wakeup_words_config = WakeupWordsConfig()
# 用于防止并发调用wakeupWordsResponse的锁
# Lock to prevent concurrent calls to wakeupWordsResponse
_wakeup_response_lock = asyncio.Lock()
async def handleHelloMessage(conn, msg_json):
"""处理hello消息"""
"""Protocol-compliant handshake for XiaoZhi firmware"""
# 1. Update session-specific audio params
audio_params = msg_json.get("audio_params")
if audio_params:
format = audio_params.get("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).debug(f"客户端特性: {features}")
conn.features = features
if features.get("mcp"):
conn.logger.bind(tag=TAG).debug("客户端支持MCP")
conn.mcp_client = MCPClient()
# 发送初始化
asyncio.create_task(send_mcp_initialize_message(conn))
# 发送mcp消息,获取tools列表
asyncio.create_task(send_mcp_tools_list_request(conn))
conn.audio_format = audio_params.get("format")
# 2. Assign features (Setting mcp to False in the response tells the
# firmware not to wait for further MCP packets during the handshake)
features = msg_json.get("features", {})
conn.features = features
await conn.websocket.send(json.dumps(conn.welcome_msg))
# 3. Generate a Session ID
session_id = str(uuid.uuid4().hex)
conn.session_id = session_id
# 4. Construct protocol response
response = {
"type": "hello",
"version": msg_json.get("version", 1),
"transport": msg_json.get("transport", "websocket"),
"auth_key": conn.config["xiaozhi"]["auth_key"],
"session_id": session_id,
"message": "success",
# Force MCP enabled to ensure client listeners are active
"features": {**features, "mcp": True},
"audio_params": {
"format": "opus",
"sample_rate": 16000,
"channels": 1,
"frame_duration": 60
}
}
# 5. Brief pause to ensure network buffers are ready
await asyncio.sleep(0.1)
# 6. Send and Log exactly what was sent
resp_json = json.dumps(response)
await conn.websocket.send(resp_json)
conn.logger.bind(tag=TAG).info(f"Handshake mirrored: {resp_json}")
async def checkWakeupWords(conn, text):
enable_wakeup_words_response_cache = conn.config[
"enable_wakeup_words_response_cache"
]
"""Check if the transcribed text matches any wakeup words"""
enable_wakeup_words_response_cache = conn.config.get(
"enable_wakeup_words_response_cache", False
)
# 等待tts初始化,最多等待3秒
# Wait for TTS initialization (max 3 seconds)
start_time = time.time()
while time.time() - start_time < 3:
if conn.tts:
@ -80,43 +97,38 @@ async def checkWakeupWords(conn, text):
return False
_, filtered_text = remove_punctuation_and_length(text)
if filtered_text not in conn.config.get("wakeup_words"):
if filtered_text not in conn.config.get("wakeup_words", []):
return False
conn.just_woken_up = True
await send_tts_message(conn, "start")
# 获取当前音色
voice = getattr(conn.tts, "voice", "default")
if not voice:
voice = "default"
voice = getattr(conn.tts, "voice", "default") or "default"
# 获取唤醒词回复配置
response = wakeup_words_config.get_wakeup_response(voice)
if not response or not response.get("file_path"):
response = {
"voice": "default",
"file_path": "config/assets/wakeup_words_short.wav",
"time": 0,
"text": "我在这里哦!",
"text": "I'm here!",
}
# 获取音频数据
# Get audio data
opus_packets = await audio_to_data(response.get("file_path"), use_cache=False)
# 播放唤醒词回复
conn.client_abort = False
# 将唤醒词回复视为新会话,生成新的 sentence_id,确保流控器重置
# Treat wakeup as a new session
conn.sentence_id = str(uuid.uuid4().hex)
conn.logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}")
conn.logger.bind(tag=TAG).info(f"Playing wakeup response: {response.get('text')}")
await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
await sendAudioMessage(conn, SentenceType.LAST, [], None)
# 补充对话
# Append to dialogue
conn.dialogue.put(Message(role="assistant", content=response.get("text")))
# 检查是否需要更新唤醒词回复
# Check if we need to refresh the cached response
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
if not _wakeup_response_lock.locked():
asyncio.create_task(wakeupWordsResponse(conn))
@ -124,34 +136,32 @@ async def checkWakeupWords(conn, text):
async def wakeupWordsResponse(conn):
"""Generate and cache a new random wakeup response"""
if not conn.tts:
return
try:
# 尝试获取锁,如果获取不到就返回
if not await _wakeup_response_lock.acquire():
return
# 从预定义回复列表中随机选择一个回复
result = random.choice(WAKEUP_CONFIG["responses"])
if not result or len(result) == 0:
if not result:
return
# 生成TTS音频
# Generate TTS audio in thread
tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
if not tts_result:
return
# 获取当前音色
voice = getattr(conn.tts, "voice", "default")
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000)
file_path = wakeup_words_config.generate_file_path(voice)
with open(file_path, "wb") as f:
f.write(wav_bytes)
# 更新配置
wakeup_words_config.update_wakeup_response(voice, file_path, result)
finally:
# 确保在任何情况下都释放锁
if _wakeup_response_lock.locked():
_wakeup_response_lock.release()

View file

@ -7,85 +7,84 @@ from core.handle.helloHandle import checkWakeupWords
from plugins_func.register import Action, ActionResponse
from core.handle.sendAudioHandle import send_stt_message
from core.utils.util import remove_punctuation_and_length
from core.utils.exit_handler import is_exit_command, handle_exit
from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType
TAG = __name__
async def handle_user_intent(conn, text):
# 预处理输入文本,处理可能的JSON格式
# Preprocess input text, handle potential JSON format
try:
if text.strip().startswith('{') and text.strip().endswith('}'):
parsed_data = json.loads(text)
if isinstance(parsed_data, dict) and "content" in parsed_data:
text = parsed_data["content"] # 提取content用于意图分析
conn.current_speaker = parsed_data.get("speaker") # 保留说话人信息
text = parsed_data["content"] # Extract content for intent analysis
conn.current_speaker = parsed_data.get("speaker") # Keep speaker info
except (json.JSONDecodeError, TypeError):
pass
# 检查是否有明确的退出命令
# Check for direct exit command
_, filtered_text = remove_punctuation_and_length(text)
if await check_direct_exit(conn, filtered_text):
return True
# 检查是否是唤醒词
# Check for wake word
if await checkWakeupWords(conn, filtered_text):
return True
if conn.intent_type == "function_call":
# 使用支持function calling的聊天方法,不再进行意图分析
# Use chat method supporting function calling, skip intent analysis
return False
# 使用LLM进行意图分析
# Use LLM for intent analysis
intent_result = await analyze_intent_with_llm(conn, text)
if not intent_result:
return False
# 会话开始时生成sentence_id
# Generate sentence_id at session start
conn.sentence_id = str(uuid.uuid4().hex)
# 处理各种意图
# Handle various intents
return await process_intent_result(conn, intent_result, text)
async def check_direct_exit(conn, text):
"""检查是否有明确的退出命令"""
"""Check for explicit exit command"""
_, text = remove_punctuation_and_length(text)
cmd_exit = conn.cmd_exit
for cmd in cmd_exit:
if text == cmd:
conn.logger.bind(tag=TAG).info(f"识别到明确的退出命令: {text}")
await send_stt_message(conn, text)
await conn.close()
return True
if is_exit_command(text, conn.cmd_exit):
conn.logger.bind(tag=TAG).info(f"Detected explicit exit command: {text}")
await send_stt_message(conn, text)
handle_exit(conn)
return True
return False
async def analyze_intent_with_llm(conn, text):
"""使用LLM分析用户意图"""
"""Analyze user intent with LLM"""
if not hasattr(conn, "intent") or not conn.intent:
conn.logger.bind(tag=TAG).warning("意图识别服务未初始化")
conn.logger.bind(tag=TAG).warning("Intent service not initialized")
return None
# 对话历史记录
# Dialogue history
dialogue = conn.dialogue
try:
intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
return intent_result
except Exception as e:
conn.logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}")
conn.logger.bind(tag=TAG).error(f"Intent recognition failed: {str(e)}")
return None
async def process_intent_result(conn, intent_result, original_text):
"""处理意图识别结果"""
"""Process intent recognition result"""
try:
# 尝试将结果解析为JSON
# Try to parse result as JSON
intent_data = json.loads(intent_result)
# 检查是否有function_call
# Check for function_call
if "function_call" in intent_data:
# 直接从意图识别获取了function_call
# Got function_call directly from intent
conn.logger.bind(tag=TAG).debug(
f"检测到function_call格式的意图结果: {intent_data['function_call']['name']}"
f"Detected function_call intent format: {intent_data['function_call']['name']}"
)
function_name = intent_data["function_call"]["name"]
if function_name == "continue_chat":
@ -102,12 +101,16 @@ async def process_intent_result(conn, intent_result, original_text):
current_time, today_date, today_weekday, lunar_date = get_current_time_info()
# 构建带上下文的基础提示
context_prompt = f"""当前时间:{current_time}
今天日期:{today_date} ({today_weekday})
今天农历:{lunar_date}
# Build base prompt with context
# Prepend current system prompt (persona) if available
base_system = conn.prompt if hasattr(conn, "prompt") and conn.prompt else ""
context_prompt = f"""{base_system}
Current Time: {current_time}
Date: {today_date} ({today_weekday})
Lunar Date: {lunar_date}
请根据以上信息回答用户的问题:{original_text}"""
Please answer the user's question based on the above information: {original_text}"""
response = conn.intent.replyResult(context_prompt, original_text)
speak_txt(conn, response)
@ -120,7 +123,7 @@ async def process_intent_result(conn, intent_result, original_text):
function_args = intent_data["function_call"]["arguments"]
if function_args is None:
function_args = {}
# 确保参数是字符串格式的JSON
# Ensure args are JSON string
if isinstance(function_args, dict):
function_args = json.dumps(function_args)
@ -133,11 +136,11 @@ async def process_intent_result(conn, intent_result, original_text):
await send_stt_message(conn, original_text)
conn.client_abort = False
# 使用executor执行函数调用和结果处理
# Use executor to handle tool call and result processing
def process_function_call():
conn.dialogue.put(Message(role="user", content=original_text))
# 使用统一工具处理器处理所有工具调用
# Use unified tool handler
try:
result = asyncio.run_coroutine_threadsafe(
conn.func_handler.handle_llm_function_call(
@ -158,6 +161,7 @@ async def process_intent_result(conn, intent_result, original_text):
speak_txt(conn, text)
elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复
text = result.result
conn.logger.bind(tag=TAG).info(f"Tool output for LLM generation: {text}")
conn.dialogue.put(Message(role="tool", content=text))
llm_result = conn.intent.replyResult(text, original_text)
if llm_result is None:
@ -167,7 +171,9 @@ async def process_intent_result(conn, intent_result, original_text):
result.action == Action.NOTFOUND
or result.action == Action.ERROR
):
text = result.result
text = result.response
if not text:
text = result.result
if text is not None:
speak_txt(conn, text)
elif function_name != "play_music":
@ -179,17 +185,17 @@ async def process_intent_result(conn, intent_result, original_text):
if text is not None:
speak_txt(conn, text)
# 将函数执行放在线程池中
# Execute function in thread pool
conn.executor.submit(process_function_call)
return True
return False
except json.JSONDecodeError as e:
conn.logger.bind(tag=TAG).error(f"处理意图结果时出错: {e}")
conn.logger.bind(tag=TAG).error(f"Error processing intent result: {e}")
return False
def speak_txt(conn, text):
# 记录文本
# Log text
conn.tts_MessageText = text
conn.tts.tts_text_queue.put(

View file

@ -37,7 +37,7 @@ async def resume_vad_detection(conn):
conn.just_woken_up = False
async def startToChat(conn, text):
async def startToChat(conn, text, audio_data=None):
# 检查输入是否是JSON格式(包含说话人信息)
speaker_name = None
language_tag = None
@ -94,13 +94,19 @@ async def startToChat(conn, text):
# 意图未被处理,继续常规聊天流程,使用实际文本内容
await send_stt_message(conn, actual_text)
conn.executor.submit(conn.chat, actual_text)
conn.executor.submit(conn.chat, actual_text, audio_data=audio_data)
async def no_voice_close_connect(conn, have_voice):
if have_voice:
conn.last_activity_time = time.time() * 1000
return
# Prevent idle timeout while LLM is actively thinking/speaking
if hasattr(conn, "llm_finish_task") and not conn.llm_finish_task:
conn.last_activity_time = time.time() * 1000
return
# 只有在已经初始化过时间戳的情况下才进行超时检查
if conn.last_activity_time > 0.0:
no_voice_time = time.time() * 1000 - conn.last_activity_time
@ -115,12 +121,12 @@ async def no_voice_close_connect(conn, have_voice):
conn.client_abort = False
end_prompt = conn.config.get("end_prompt", {})
if end_prompt and end_prompt.get("enable", True) is False:
conn.logger.bind(tag=TAG).info("结束对话,无需发送结束提示语")
conn.logger.bind(tag=TAG).info("Closing connection due to inactivity.")
await conn.close()
return
prompt = end_prompt.get("prompt")
if not prompt:
prompt = "请你以```时间过得真快```未来头,用富有感情、依依不舍的话来结束这场对话吧。!"
prompt = "Please provide a very short, polite goodbye in the user's language to end the conversation since it has been idle."
await startToChat(conn, prompt)

View file

@ -7,20 +7,20 @@ from core.providers.tts.dto.dto import SentenceType
from core.utils.audioRateController import AudioRateController
TAG = __name__
# 音频帧时长(毫秒)
# Audio frame duration (ms)
AUDIO_FRAME_DURATION = 60
# 预缓冲包数量,直接发送以减少延迟
# Pre-buffer count, send directly to reduce latency
PRE_BUFFER_COUNT = 5
async def sendAudioMessage(conn, sentenceType, audios, text):
if conn.tts.tts_audio_first_sentence:
conn.logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
conn.logger.bind(tag=TAG).info(f"Sending first audio segment: {text}")
conn.tts.tts_audio_first_sentence = False
await send_tts_message(conn, "start", None)
if sentenceType == SentenceType.FIRST:
# 同一句子的后续消息加入流控队列,其他情况立即发送
# Subsequent messages for the same sentence join the flow control queue, others send immediately
if (
hasattr(conn, "audio_rate_controller")
and conn.audio_rate_controller
@ -31,15 +31,15 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
lambda: send_tts_message(conn, "sentence_start", text)
)
else:
# 新句子或流控器未初始化,立即发送
# New sentence or rate controller not initialized, send immediately
await send_tts_message(conn, "sentence_start", text)
await sendAudio(conn, audios)
# 发送句子开始消息
# Send sentence start message
if sentenceType is not SentenceType.MIDDLE:
conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}")
conn.logger.bind(tag=TAG).info(f"Sending audio message: {sentenceType}, {text}")
# 发送结束消息(如果是最后一个文本)
# Send end message (if it is the last text)
if sentenceType == SentenceType.LAST:
await send_tts_message(conn, "stop", None)
conn.client_is_speaking = False
@ -49,57 +49,57 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
async def _wait_for_audio_completion(conn):
"""
等待音频队列清空并等待预缓冲包播放完成
Wait for audio queue to empty and wait for pre-buffer packets to finish playing
Args:
conn: 连接对象
conn: connection object
"""
if hasattr(conn, "audio_rate_controller") and conn.audio_rate_controller:
rate_controller = conn.audio_rate_controller
conn.logger.bind(tag=TAG).debug(
f"等待音频发送完成,队列中还有 {len(rate_controller.queue)} 个包"
f"Waiting for audio completion, {len(rate_controller.queue)} packets remaining"
)
await rate_controller.queue_empty_event.wait()
# 等待预缓冲包播放完成
# 前N个包直接发送,增加2个网络抖动包,需要额外等待它们在客户端播放完成
# Wait for pre-buffer packets to finish playing
# First N packets sent directly, adding 2 network jitter packets, need extra wait for them to finish playing on client
frame_duration_ms = rate_controller.frame_duration
pre_buffer_playback_time = (PRE_BUFFER_COUNT + 2) * frame_duration_ms / 1000.0
await asyncio.sleep(pre_buffer_playback_time)
conn.logger.bind(tag=TAG).debug("音频发送完成")
conn.logger.bind(tag=TAG).debug("Audio sending completed")
async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence):
"""
发送带16字节头部的opus数据包给mqtt_gateway
Send opus packet with 16-byte header to mqtt_gateway
Args:
conn: 连接对象
opus_packet: opus数据包
timestamp: 时间戳
sequence: 序列号
conn: connection object
opus_packet: opus data packet
timestamp: timestamp
sequence: sequence number
"""
# 为opus数据包添加16字节头部
# Add 16-byte header to opus packet
header = bytearray(16)
header[0] = 1 # type
header[2:4] = len(opus_packet).to_bytes(2, "big") # payload length
header[4:8] = sequence.to_bytes(4, "big") # sequence
header[8:12] = timestamp.to_bytes(4, "big") # 时间戳
header[12:16] = len(opus_packet).to_bytes(4, "big") # opus长度
header[8:12] = timestamp.to_bytes(4, "big") # timestamp
header[12:16] = len(opus_packet).to_bytes(4, "big") # opus length
# 发送包含头部的完整数据包
# Send complete packet containing header
complete_packet = bytes(header) + opus_packet
await conn.websocket.send(complete_packet)
async def sendAudio(conn, audios, frame_duration=AUDIO_FRAME_DURATION):
"""
发送音频包,使用 AudioRateController 进行精确的流量控制
Send audio packets, use AudioRateController for precise flow control
Args:
conn: 连接对象
audios: 单个opus包(bytes) 或 opus包列表
frame_duration: 帧时长(毫秒),默认使用全局常量AUDIO_FRAME_DURATION
conn: connection object
audios: single opus packet (bytes) or list of opus packets
frame_duration: frame duration (ms), default uses global constant AUDIO_FRAME_DURATION
"""
if audios is None or len(audios) == 0:
return
@ -107,15 +107,15 @@ async def sendAudio(conn, audios, frame_duration=AUDIO_FRAME_DURATION):
send_delay = conn.config.get("tts_audio_send_delay", -1) / 1000.0
is_single_packet = isinstance(audios, bytes)
# 初始化或获取 RateController
# Initialize or get RateController
rate_controller, flow_control = _get_or_create_rate_controller(
conn, frame_duration, is_single_packet
)
# 统一转换为列表处理
# Unified conversion to list processing
audio_list = [audios] if is_single_packet else audios
# 发送音频包
# Send audio packets
await _send_audio_with_rate_control(
conn, audio_list, rate_controller, flow_control, send_delay
)
@ -123,32 +123,32 @@ async def sendAudio(conn, audios, frame_duration=AUDIO_FRAME_DURATION):
def _get_or_create_rate_controller(conn, frame_duration, is_single_packet):
"""
获取或创建 RateController 和 flow_control
Get or create RateController and flow_control
Args:
conn: 连接对象
frame_duration: 帧时长
is_single_packet: 是否单包模式(True: TTS流式单包, False: 批量包)
conn: connection object
frame_duration: frame duration
is_single_packet: Whether single packet mode (True: TTS streaming single packet, False: batch packet)
Returns:
(rate_controller, flow_control)
"""
# 检查是否需要重置控制器
# Check if controller needs reset
need_reset = False
if not hasattr(conn, "audio_rate_controller"):
# 控制器不存在,需要创建
# Controller does not exist, need to create
need_reset = True
else:
rate_controller = conn.audio_rate_controller
# 后台发送任务已停止, 则需要重置
# Background send task stopped, need to reset
if (
not rate_controller.pending_send_task
or rate_controller.pending_send_task.done()
):
need_reset = True
# 当sentence_id 变化,需要重置
# When sentence_id changes, need to reset
elif (
getattr(conn, "audio_flow_control", {}).get("sentence_id")
!= conn.sentence_id
@ -156,20 +156,20 @@ def _get_or_create_rate_controller(conn, frame_duration, is_single_packet):
need_reset = True
if need_reset:
# 创建或获取 rate_controller
# Create or get rate_controller
if not hasattr(conn, "audio_rate_controller"):
conn.audio_rate_controller = AudioRateController(frame_duration)
else:
conn.audio_rate_controller.reset()
# 初始化 flow_control
# Initialize flow_control
conn.audio_flow_control = {
"packet_count": 0,
"sequence": 0,
"sentence_id": conn.sentence_id,
}
# 启动后台发送循环
# Start background send loop
_start_background_sender(
conn, conn.audio_rate_controller, conn.audio_flow_control
)
@ -179,24 +179,24 @@ def _get_or_create_rate_controller(conn, frame_duration, is_single_packet):
def _start_background_sender(conn, rate_controller, flow_control):
"""
启动后台发送循环任务
Start background send loop task
Args:
conn: 连接对象
rate_controller: 速率控制器
flow_control: 流控状态
conn: connection object
rate_controller: rate controller
flow_control: flow control status
"""
async def send_callback(packet):
# 检查是否应该中止
# Check if should abort
if conn.client_abort:
raise asyncio.CancelledError("客户端已中止")
raise asyncio.CancelledError("Client aborted")
conn.last_activity_time = time.time() * 1000
await _do_send_audio(conn, packet, flow_control)
conn.client_is_speaking = True
# 使用 start_sending 启动后台循环
# Use start_sending to start background loop
rate_controller.start_sending(send_callback)
@ -204,14 +204,14 @@ async def _send_audio_with_rate_control(
conn, audio_list, rate_controller, flow_control, send_delay
):
"""
使用 rate_controller 发送音频包
Use rate_controller to send audio packets
Args:
conn: 连接对象
audio_list: 音频包列表
rate_controller: 速率控制器
flow_control: 流控状态
send_delay: 固定延迟(秒),-1表示使用动态流控
conn: connection object
audio_list: list of audio packets
rate_controller: rate controller
flow_control: flow control status
send_delay: fixed delay (seconds), -1 means use dynamic flow control
"""
for packet in audio_list:
if conn.client_abort:
@ -219,52 +219,52 @@ async def _send_audio_with_rate_control(
conn.last_activity_time = time.time() * 1000
# 预缓冲:前N个包直接发送
# Pre-buffer: first N packets send directly
if flow_control["packet_count"] < PRE_BUFFER_COUNT:
await _do_send_audio(conn, packet, flow_control)
conn.client_is_speaking = True
elif send_delay > 0:
# 固定延迟模式
# Fixed delay mode
await asyncio.sleep(send_delay)
await _do_send_audio(conn, packet, flow_control)
conn.client_is_speaking = True
else:
# 动态流控模式:仅添加到队列,由后台循环负责发送
# Dynamic flow control mode: only add to queue, background loop responsible for sending
rate_controller.add_audio(packet)
async def _do_send_audio(conn, opus_packet, flow_control):
"""
执行实际的音频发送
Execute actual audio sending
"""
packet_index = flow_control.get("packet_count", 0)
sequence = flow_control.get("sequence", 0)
if conn.conn_from_mqtt_gateway:
# 计算时间戳(基于播放位置)
# Calculate timestamp (based on playback position)
start_time = time.time()
timestamp = int(start_time * 1000) % (2**32)
await _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence)
else:
# 直接发送opus数据包
# Send opus data packet directly
await conn.websocket.send(opus_packet)
# 更新流控状态
# Update flow control status
flow_control["packet_count"] = packet_index + 1
flow_control["sequence"] = sequence + 1
async def send_tts_message(conn, state, text=None):
"""发送 TTS 状态消息"""
"""Send TTS state message"""
if text is None and state == "sentence_start":
return
message = {"type": "tts", "state": state, "session_id": conn.session_id}
if text is not None:
message["text"] = textUtils.check_emoji(text)
# TTS播放结束
# TTS playback finished
if state == "stop":
# 播放提示音
# Play notification sound
tts_notify = conn.config.get("enable_stop_tts_notify", False)
if tts_notify:
stop_tts_notify_voice = conn.config.get(
@ -272,36 +272,36 @@ async def send_tts_message(conn, state, text=None):
)
audios = await audio_to_data(stop_tts_notify_voice, is_opus=True)
await sendAudio(conn, audios)
# 等待所有音频包发送完成
# Wait for all audio packets to finish sending
await _wait_for_audio_completion(conn)
# 清除服务端讲话状态
# Clear server speaking status
conn.clearSpeakStatus()
# 发送消息到客户端
# Send message to client
await conn.websocket.send(json.dumps(message))
async def send_stt_message(conn, text):
"""发送 STT 状态消息"""
"""Send STT state message"""
end_prompt_str = conn.config.get("end_prompt", {}).get("prompt")
if end_prompt_str and end_prompt_str == text:
await send_tts_message(conn, "start")
return
# 解析JSON格式,提取实际的用户说话内容
# Parse JSON format, extract actual user spoken content
display_text = text
try:
# 尝试解析JSON格式
# Try to parse JSON format
if text.strip().startswith("{") and text.strip().endswith("}"):
parsed_data = json.loads(text)
if isinstance(parsed_data, dict) and "content" in parsed_data:
# 如果是包含说话人信息的JSON格式,只显示content部分
# If JSON format containing speaker info, only display content part
display_text = parsed_data["content"]
# 保存说话人信息到conn对象
# Save speaker info to conn object
if "speaker" in parsed_data:
conn.current_speaker = parsed_data["speaker"]
except (json.JSONDecodeError, TypeError):
# 如果不是JSON格式,直接使用原始文本
# If not JSON format, use original text directly
display_text = text
stt_text = textUtils.get_string_no_punctuation_or_emoji(display_text)
await conn.websocket.send(

View file

@ -3,12 +3,12 @@ from core.handle.textMessageProcessor import TextMessageProcessor
TAG = __name__
# 全局处理器注册表
# Global handler registry
message_registry = TextMessageHandlerRegistry()
# 创建全局消息处理器实例
# Create global message processor instance
message_processor = TextMessageProcessor(message_registry)
async def handleTextMessage(conn, message):
"""处理文本消息"""
"""Handle text message"""
await message_processor.process_message(conn, message)

View file

@ -6,7 +6,7 @@ from core.handle.textMessageType import TextMessageType
class AbortTextMessageHandler(TextMessageHandler):
"""Abort消息处理器"""
"""Abort message handler"""
@property
def message_type(self) -> TextMessageType:

View file

@ -9,42 +9,42 @@ from core.providers.tools.device_mcp import handle_mcp_message
TAG = __name__
class ServerTextMessageHandler(TextMessageHandler):
"""MCP消息处理器"""
"""MCP message handler"""
@property
def message_type(self) -> TextMessageType:
return TextMessageType.SERVER
async def handle(self, conn, msg_json: Dict[str, Any]) -> None:
# 如果配置是从API读取的,则需要验证secret
# If config is read from API, need to verify secret
if not conn.read_config_from_api:
return
# 获取post请求的secret
# Get secret from post request
post_secret = msg_json.get("content", {}).get("secret", "")
secret = conn.config["manager-api"].get("secret", "")
# 如果secret不匹配,则返回
# If secret does not match, return
if post_secret != secret:
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
"message": "服务器密钥验证失败",
"message": "Server secret verification failed",
}
)
)
return
# 动态更新配置
# Dynamically update config
if msg_json["action"] == "update_config":
try:
# 更新WebSocketServer的配置
# Update WebSocketServer config
if not conn.server:
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
"message": "无法获取服务器实例",
"message": "Cannot get server instance",
"content": {"action": "update_config"},
}
)
@ -57,36 +57,36 @@ class ServerTextMessageHandler(TextMessageHandler):
{
"type": "server",
"status": "error",
"message": "更新服务器配置失败",
"message": "Failed to update server config",
"content": {"action": "update_config"},
}
)
)
return
# 发送成功响应
# Send success response
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "success",
"message": "配置更新成功",
"message": "Config updated successfully",
"content": {"action": "update_config"},
}
)
)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"更新配置失败: {str(e)}")
conn.logger.bind(tag=TAG).error(f"Failed to update config: {str(e)}")
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
"message": f"更新配置失败: {str(e)}",
"message": f"Failed to update config: {str(e)}",
"content": {"action": "update_config"},
}
)
)
# 重启服务器
# Restart server
elif msg_json["action"] == "restart":
await conn.handle_restart(msg_json)

View file

@ -13,14 +13,14 @@ TAG = __name__
class TextMessageHandlerRegistry:
"""消息处理器注册表"""
"""Message handler registry"""
def __init__(self):
self._handlers: Dict[str, TextMessageHandler] = {}
self._register_default_handlers()
def _register_default_handlers(self) -> None:
"""注册默认的消息处理器"""
"""Register default message handlers"""
handlers = [
HelloTextMessageHandler(),
AbortTextMessageHandler(),
@ -35,13 +35,13 @@ class TextMessageHandlerRegistry:
self.register_handler(handler)
def register_handler(self, handler: TextMessageHandler) -> None:
"""注册消息处理器"""
"""Register message handler"""
self._handlers[handler.message_type.value] = handler
def get_handler(self, message_type: str) -> Optional[TextMessageHandler]:
"""获取消息处理器"""
"""Get message handler"""
return self._handlers.get(message_type)
def get_supported_types(self) -> list:
"""获取支持的消息类型"""
"""Get supported message types"""
return list(self._handlers.keys())

View file

@ -1,41 +1,57 @@
import json
import asyncio
from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry
TAG = __name__
class TextMessageProcessor:
"""消息处理器主类"""
"""Main Message Processor Class"""
def __init__(self, registry: TextMessageHandlerRegistry):
self.registry = registry
async def process_message(self, conn, message: str) -> None:
"""处理消息的主入口"""
"""Main entry point for message processing"""
try:
# 解析JSON消息
# Parse JSON message
msg_json = json.loads(message)
# 处理JSON消息
# Handle JSON message
if isinstance(msg_json, dict):
message_type = msg_json.get("type")
# 记录日志
conn.logger.bind(tag=TAG).info(f"收到{message_type}消息:{message}")
# SAFE LOGGING: Prevent terminal buffer overflow on large MCP payloads
if message_type == "mcp":
conn.logger.bind(tag=TAG).info(f"Received {message_type} message (Payload hidden for performance)")
else:
conn.logger.bind(tag=TAG).info(f"Received {message_type} message: {message}")
# 获取并执行处理器
# TRIGGER: If this is NOT a hello message and MCP is enabled but not ready,
# start discovery now so it doesn't block the handshake.
if message_type != "hello" and conn.features.get("mcp"):
if not hasattr(conn, "mcp_client") or conn.mcp_client is None:
from core.providers.tools.device_mcp.mcp_handler import (
MCPClient, send_mcp_initialize_message, send_mcp_tools_list_request
)
conn.logger.bind(tag=TAG).info("First user interaction detected. Initializing MCP in background...")
conn.mcp_client = MCPClient()
asyncio.create_task(send_mcp_initialize_message(conn))
asyncio.create_task(send_mcp_tools_list_request(conn))
# Get and execute the handler
handler = self.registry.get_handler(message_type)
if handler:
await handler.handle(conn, msg_json)
else:
conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}")
# 处理纯数字消息
conn.logger.bind(tag=TAG).error(f"Received unknown message type: {message}")
# Handle numeric messages
elif isinstance(msg_json, int):
conn.logger.bind(tag=TAG).info(f"收到数字消息:{message}")
conn.logger.bind(tag=TAG).info(f"Received numeric message: {message}")
await conn.websocket.send(message)
except json.JSONDecodeError:
# 非JSON消息直接转发
conn.logger.bind(tag=TAG).error(f"解析到错误的消息:{message}")
# Forward non-JSON messages directly
conn.logger.bind(tag=TAG).error(f"Failed to parse message: {message}")
await conn.websocket.send(message)

View file

@ -15,22 +15,23 @@ class SimpleHttpServer:
self.vision_handler = VisionHandler(config)
def _get_websocket_url(self, local_ip: str, port: int) -> str:
"""获取websocket地址
"""Get websocket address
Args:
local_ip: 本地IP地址
port: 端口号
local_ip: Local IP address
port: Port number
Returns:
str: websocket地址
str: websocket address
"""
server_config = self.config["server"]
websocket_config = server_config.get("websocket")
if websocket_config and "你" not in websocket_config:
# Check if config is valid (not a placeholder "localhost", and not "127.0.0.1")
if websocket_config and websocket_config != "default":
return websocket_config
else:
return f"ws://{local_ip}:{port}/xiaozhi/v1/"
return f"ws://{local_ip}:{port}/xiaozhi/v1"
async def start(self):
try:
@ -43,7 +44,7 @@ class SimpleHttpServer:
app = web.Application()
if not read_config_from_api:
# 如果没有开启智控台,只是单模块运行,就需要再添加简单OTA接口,用于下发websocket接口
# If console is not enabled and running as single module, add simple OTA interface for distributing websocket interface
app.add_routes(
[
web.get("/xiaozhi/ota/", self.ota_handler.handle_get),
@ -51,7 +52,7 @@ class SimpleHttpServer:
web.options(
"/xiaozhi/ota/", self.ota_handler.handle_options
),
# 下载接口,仅提供 data/bin/*.bin 下载
# Download interface, only provides data/bin/*.bin download
web.get(
"/xiaozhi/ota/download/{filename}",
self.ota_handler.handle_download,
@ -62,7 +63,7 @@ class SimpleHttpServer:
),
]
)
# 添加路由
# Add routes
app.add_routes(
[
web.get("/mcp/vision/explain", self.vision_handler.handle_get),
@ -75,18 +76,18 @@ class SimpleHttpServer:
]
)
# 运行服务
# Run service
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, host, port)
await site.start()
# 保持服务运行
# Keep service running
while True:
await asyncio.sleep(3600) # 每隔 1 小时检查一次
await asyncio.sleep(3600) # Check every 1 hour
except Exception as e:
self.logger.bind(tag=TAG).error(f"HTTP服务器启动失败: {e}")
self.logger.bind(tag=TAG).error(f"HTTP server startup failed: {e}")
import traceback
self.logger.bind(tag=TAG).error(f"错误堆栈: {traceback.format_exc()}")
self.logger.bind(tag=TAG).error(f"Error stack: {traceback.format_exc()}")
raise

View file

@ -45,10 +45,10 @@ class AccessToken:
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"Version": "2019-02-28",
}
# 构造规范化的请求字符串
# Construct normalized request string
query_string = AccessToken._encode_dict(parameters)
# print('规范化的请求字符串: %s' % query_string)
# 构造待签名字符串
# print('Normalized request string: %s' % query_string)
# Construct string to sign
string_to_sign = (
"GET"
+ "&"
@ -56,25 +56,25 @@ class AccessToken:
+ "&"
+ AccessToken._encode_text(query_string)
)
# print('待签名的字符串: %s' % string_to_sign)
# 计算签名
# print('String to sign: %s' % string_to_sign)
# Calculate signature
secreted_string = hmac.new(
bytes(access_key_secret + "&", encoding="utf-8"),
bytes(string_to_sign, encoding="utf-8"),
hashlib.sha1,
).digest()
signature = base64.b64encode(secreted_string)
# print('签名: %s' % signature)
# 进行URL编码
# print('Signature: %s' % signature)
# URL encode
signature = AccessToken._encode_text(signature)
# print('URL编码后的签名: %s' % signature)
# 调用服务
# print('URL encoded signature: %s' % signature)
# Call service
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
signature,
query_string,
)
# print('url: %s' % full_url)
# 提交HTTP GET请求
# Submit HTTP GET request
response = requests.get(full_url)
if response.ok:
root_obj = response.json()
@ -91,8 +91,8 @@ class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
self.interface_type = InterfaceType.NON_STREAM
"""阿里云ASR初始化"""
# 新增空值判断逻辑
"""Aliyun ASR initialization"""
# Added null value check logic
self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret")
@ -105,27 +105,27 @@ class ASRProvider(ASRProviderBase):
self.delete_audio_file = delete_audio_file
if self.access_key_id and self.access_key_secret:
# 使用密钥对生成临时token
# Use key pair to generate temporary token
self._refresh_token()
else:
# 直接使用预生成的长期token
# Use pre-generated long-term token directly
self.token = config.get("token")
self.expire_time = None
# 确保输出目录存在
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
def _refresh_token(self):
"""刷新Token并记录过期时间"""
"""Refresh Token and record expiration time"""
if self.access_key_id and self.access_key_secret:
self.token, expire_time_str = AccessToken.create_token(
self.access_key_id, self.access_key_secret
)
if not expire_time_str:
raise ValueError("无法获取有效的Token过期时间")
raise ValueError("Failed to get valid Token expiration time")
try:
# 统一转换为字符串处理
# Convert to string for consistent handling
expire_str = str(expire_time_str).strip()
if expire_str.isdigit():
@ -134,13 +134,13 @@ class ASRProvider(ASRProviderBase):
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
self.expire_time = expire_time.timestamp() - 60
except Exception as e:
raise ValueError(f"无效的过期时间格式: {expire_str}") from e
raise ValueError(f"Invalid expiration time format: {expire_str}") from e
else:
self.expire_time = None
if not self.token:
raise ValueError("无法获取有效的访问Token")
raise ValueError("Failed to get valid access Token")
def _is_token_expired(self):
"""检查Token是否过期"""
@ -148,14 +148,12 @@ class ASRProvider(ASRProviderBase):
return False # 长期Token不过期
# 新增调试日志
# current_time = time.time()
# remaining = self.expire_time - current_time
# print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | "
# f"过期时间 {datetime.fromtimestamp(self.expire_time)} | "
# f"剩余 {remaining:.2f}秒")
return time.time() > self.expire_time
def _construct_request_url(self) -> str:
"""构造请求URL,包含参数"""
def _is_token_expired(self):
"""Check if Token is expired"""
if not self.expire_time:
return False # Long-term Token does not expire
# Added debug log
# current_time = time.time()
request = f"{self.base_url}?appkey={self.app_key}"
request += f"&format={self.format}"
request += f"&sample_rate={self.sample_rate}"
@ -165,16 +163,16 @@ class ASRProvider(ASRProviderBase):
return request
async def _send_request(self, pcm_data: bytes) -> Optional[str]:
"""发送请求到阿里云ASR服务"""
"""Send request to Aliyun ASR service"""
try:
# 设置HTTP头
# Set HTTP headers
headers = {
"X-NLS-Token": self.token,
"Content-type": "application/octet-stream",
"Content-Length": str(len(pcm_data)),
}
# 创建连接并发送请求
# Create connection and send request
conn = http.client.HTTPSConnection(self.host)
request_url = self._construct_request_url()
@ -186,56 +184,56 @@ class ASRProvider(ASRProviderBase):
),
)
# 获取响应
# Get response
response = await loop.run_in_executor(None, conn.getresponse)
body = await loop.run_in_executor(None, response.read)
conn.close()
# 解析响应
# Parse response
try:
body_json = json.loads(body)
status = body_json.get("status")
if status == 20000000:
result = body_json.get("result", "")
logger.bind(tag=TAG).debug(f"ASR结果: {result}")
logger.bind(tag=TAG).debug(f"ASR result: {result}")
return result
else:
logger.bind(tag=TAG).error(f"ASR失败,状态码: {status}")
logger.bind(tag=TAG).error(f"ASR failed, status code: {status}")
return None
except ValueError:
logger.bind(tag=TAG).error("响应不是JSON格式")
logger.bind(tag=TAG).error("Response is not in JSON format")
return None
except Exception as e:
logger.bind(tag=TAG).error(f"ASR请求失败: {e}", exc_info=True)
logger.bind(tag=TAG).error(f"ASR request failed: {e}", exc_info=True)
return None
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
"""Convert speech data to text"""
if self._is_token_expired():
logger.warning("Token已过期,正在自动刷新...")
logger.warning("Token expired, refreshing automatically...")
self._refresh_token()
file_path = None
try:
# 解码Opus为PCM
# Decode Opus to PCM
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件
# Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
file_path = self.save_audio_to_file(pcm_data, session_id)
# 发送请求并获取文本
# Send request and obtain text
text = await self._send_request(combined_pcm_data)
if text:
@ -244,5 +242,5 @@ class ASRProvider(ASRProviderBase):
return "", file_path
except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
logger.bind(tag=TAG).error(f"Speech recognition failed: {e}", exc_info=True)
return "", file_path

View file

@ -74,19 +74,19 @@ class ASRProvider(ASRProviderBase):
self.asr_ws = None
self.forward_task = None
self.is_processing = False
self.server_ready = False # 服务器准备状态
self.server_ready = False # Server ready status
# 基础配置
# Basic configuration
self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret")
self.appkey = config.get("appkey")
self.token = config.get("token")
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
# 如果配置的是内网地址(包含-internal.aliyuncs.com),则使用ws协议,默认是wss协议
# If internal address is configured (contains -internal.aliyuncs.com), use ws protocol, default is wss protocol
if "-internal." in self.host:
self.ws_url = f"ws://{self.host}/ws/v1"
else:
# 默认使用wss协议
# Default to wss protocol
self.ws_url = f"wss://{self.host}/ws/v1"
self.max_sentence_silence = config.get("max_sentence_silence")
@ -96,17 +96,17 @@ class ASRProvider(ASRProviderBase):
self.task_id = uuid.uuid4().hex
# Token管理
# Token management
if self.access_key_id and self.access_key_secret:
self._refresh_token()
elif not self.token:
raise ValueError("必须提供access_key_id+access_key_secret或者直接提供token")
raise ValueError("Must provide access_key_id+access_key_secret or token directly")
def _refresh_token(self):
"""刷新Token"""
"""Refresh Token"""
self.token, expire_time_str = AccessToken.create_token(self.access_key_id, self.access_key_secret)
if not self.token:
raise ValueError("无法获取有效的访问Token")
raise ValueError("Failed to obtain valid access Token")
try:
expire_str = str(expire_time_str).strip()
@ -119,7 +119,7 @@ class ASRProvider(ASRProviderBase):
self.expire_time = None
def _is_token_expired(self):
"""检查Token是否过期"""
"""Check if Token is expired"""
return self.expire_time and time.time() > self.expire_time
async def open_audio_channels(self, conn):
@ -137,12 +137,12 @@ class ASRProvider(ASRProviderBase):
conn.asr_audio.append(audio)
conn.asr_audio = conn.asr_audio[-10:]
# 只在有声音且没有连接时建立连接(排除正在停止的情况)
# Establish connection only if there is voice and no connection exists (excluding stopping cases)
if audio_have_voice and not self.is_processing and not self.asr_ws:
try:
await self._start_recognition(conn)
except Exception as e:
logger.bind(tag=TAG).error(f"开始识别失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to start recognition: {str(e)}")
await self._cleanup()
return
@ -151,15 +151,15 @@ class ASRProvider(ASRProviderBase):
pcm_frame = self.decoder.decode(audio, 960)
await self.asr_ws.send(pcm_frame)
except Exception as e:
logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}")
logger.bind(tag=TAG).warning(f"Failed to send audio: {str(e)}")
await self._cleanup(conn)
async def _start_recognition(self, conn):
"""开始识别会话"""
"""Start recognition session"""
if self._is_token_expired():
self._refresh_token()
# 建立连接
# Establish connection
headers = {"X-NLS-Token": self.token}
self.asr_ws = await websockets.connect(
self.ws_url,
@ -172,13 +172,13 @@ class ASRProvider(ASRProviderBase):
self.task_id = uuid.uuid4().hex
logger.bind(tag=TAG).debug(f"WebSocket连接建立成功, task_id: {self.task_id}")
logger.bind(tag=TAG).debug(f"WebSocket connection established, task_id: {self.task_id}")
self.is_processing = True
self.server_ready = False # 重置服务器准备状态
self.server_ready = False # Reset server ready status
self.forward_task = asyncio.create_task(self._forward_results(conn))
# 发送开始请求
# Send start request
start_request = {
"header": {
"namespace": "SpeechTranscriber",
@ -198,10 +198,10 @@ class ASRProvider(ASRProviderBase):
}
}
await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False))
logger.bind(tag=TAG).debug("已发送开始请求,等待服务器准备...")
logger.bind(tag=TAG).debug("Start request sent, waiting for server preparation...")
async def _forward_results(self, conn):
"""转发识别结果"""
"""Forward recognition results"""
try:
while not conn.stop_event.is_set():
try:
@ -215,58 +215,58 @@ class ASRProvider(ASRProviderBase):
if status != 20000000:
if status == 40010004:
logger.bind(tag=TAG).warning(f"请在服务端响应完成后再关闭链接,状态码: {status}")
logger.bind(tag=TAG).warning(f"Please close connection after server response is complete, status code: {status}")
break
if status in [40000004, 40010003]: # 连接超时或客户端断开
logger.bind(tag=TAG).warning(f"连接问题,状态码: {status}")
if status in [40000004, 40010003]: # Connection timeout or client disconnect
logger.bind(tag=TAG).warning(f"Connection issue, status code: {status}")
break
elif status in [40270002, 40270003]: # 音频问题
logger.bind(tag=TAG).warning(f"音频处理问题,状态码: {status}")
elif status in [40270002, 40270003]: # Audio issue
logger.bind(tag=TAG).warning(f"Audio processing issue, status code: {status}")
continue
else:
logger.bind(tag=TAG).error(f"识别错误,状态码: {status}, 消息: {header.get('status_text', '')}")
logger.bind(tag=TAG).error(f"Recognition error, status code: {status}, message: {header.get('status_text', '')}")
continue
# 收到TranscriptionStarted表示服务器准备好接收音频数据
# Received TranscriptionStarted indicating server is ready to receive audio data
if message_name == "TranscriptionStarted":
self.server_ready = True
logger.bind(tag=TAG).debug("服务器已准备,开始发送缓存音频...")
logger.bind(tag=TAG).debug("Server ready, starting to send cached audio...")
# 发送缓存音频
# Send cached audio
if conn.asr_audio:
for cached_audio in conn.asr_audio[-10:]:
try:
pcm_frame = self.decoder.decode(cached_audio, 960)
await self.asr_ws.send(pcm_frame)
except Exception as e:
logger.bind(tag=TAG).warning(f"发送缓存音频失败: {e}")
logger.bind(tag=TAG).warning(f"Failed to send cached audio: {e}")
break
continue
elif message_name == "SentenceEnd":
# 句子结束(每个句子都会触发)
# Sentence end (triggered for each sentence)
text = payload.get("result", "")
if text:
logger.bind(tag=TAG).info(f"识别到文本: {text}")
logger.bind(tag=TAG).info(f"Recognized text: {text}")
# 手动模式下累积识别结果
# Accumulate recognition results in manual mode
if conn.client_listen_mode == "manual":
if self.text:
self.text += text
else:
self.text = text
# 手动模式下,只有在收到stop信号后才触发处理(仅处理一次)
# In manual mode, only trigger processing after receiving stop signal (process only once)
if conn.client_voice_stop:
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
if len(audio_data) > 0:
logger.bind(tag=TAG).debug("收到最终识别结果,触发处理")
logger.bind(tag=TAG).debug("Received final result, trigger processing")
await self.handle_voice_stop(conn, audio_data)
# 清理音频缓存
# Clear audio cache
conn.asr_audio.clear()
conn.reset_vad_states()
break
else:
# 自动模式下直接覆盖
# Overwrite directly in auto mode
self.text = text
conn.reset_vad_states()
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
@ -274,20 +274,20 @@ class ASRProvider(ASRProviderBase):
break
except asyncio.TimeoutError:
logger.bind(tag=TAG).error("接收结果超时")
logger.bind(tag=TAG).error("Receive result timeout")
break
except websockets.ConnectionClosed:
logger.bind(tag=TAG).info("ASR服务连接已关闭")
logger.bind(tag=TAG).info("ASR service connection closed")
self.is_processing = False
break
except Exception as e:
logger.bind(tag=TAG).error(f"处理结果失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to process result: {str(e)}")
break
except Exception as e:
logger.bind(tag=TAG).error(f"结果转发失败: {str(e)}")
logger.bind(tag=TAG).error(f"Result forwarding failed: {str(e)}")
finally:
# 清理连接的音频缓存
# Clear connected audio cache
await self._cleanup()
if conn:
if hasattr(conn, 'asr_audio_for_voiceprint'):
@ -296,10 +296,10 @@ class ASRProvider(ASRProviderBase):
conn.asr_audio = []
async def _send_stop_request(self):
"""发送停止识别请求(不关闭连接)"""
"""Send stop recognition request (without closing connection)"""
if self.asr_ws:
try:
# 先停止音频发送
# Stop audio sending first
self.is_processing = False
stop_msg = {
@ -311,44 +311,44 @@ class ASRProvider(ASRProviderBase):
"appkey": self.appkey
}
}
logger.bind(tag=TAG).debug("停止识别请求已发送")
logger.bind(tag=TAG).debug("Stop recognition request sent")
await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False))
except Exception as e:
logger.bind(tag=TAG).error(f"发送停止识别请求失败: {e}")
logger.bind(tag=TAG).error(f"Failed to send stop recognition request: {e}")
async def _cleanup(self):
"""清理资源(关闭连接)"""
logger.bind(tag=TAG).debug(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}")
"""Cleanup resources (close connection)"""
logger.bind(tag=TAG).debug(f"Starting ASR session cleanup | Current Status: processing={self.is_processing}, server_ready={self.server_ready}")
# 状态重置
# Reset status
self.is_processing = False
self.server_ready = False
logger.bind(tag=TAG).debug("ASR状态已重置")
logger.bind(tag=TAG).debug("ASR status reset")
# 关闭连接
# Close connection
if self.asr_ws:
try:
logger.bind(tag=TAG).debug("正在关闭WebSocket连接")
logger.bind(tag=TAG).debug("Closing WebSocket connection")
await asyncio.wait_for(self.asr_ws.close(), timeout=2.0)
logger.bind(tag=TAG).debug("WebSocket连接已关闭")
logger.bind(tag=TAG).debug("WebSocket connection closed")
except Exception as e:
logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}")
logger.bind(tag=TAG).error(f"Failed to close WebSocket connection: {e}")
finally:
self.asr_ws = None
# 清理任务引用
# Clean up task reference
self.forward_task = None
logger.bind(tag=TAG).debug("ASR会话清理完成")
logger.bind(tag=TAG).debug("ASR session cleanup completed")
async def speech_to_text(self, opus_data, session_id, audio_format):
"""获取识别结果"""
"""Get recognition result"""
result = self.text
self.text = ""
return result, None
async def close(self):
"""关闭资源"""
"""Close resources"""
await self._cleanup(None)
if hasattr(self, 'decoder') and self.decoder is not None:
try:
@ -356,4 +356,4 @@ class ASRProvider(ASRProviderBase):
self.decoder = None
logger.bind(tag=TAG).debug("Aliyun decoder resources released")
except Exception as e:
logger.bind(tag=TAG).debug(f"释放Aliyun decoder资源时出错: {e}")
logger.bind(tag=TAG).debug(f"Error when releasing Aliyun decoder resources: {e}")

View file

@ -22,16 +22,16 @@ class ASRProvider(ASRProviderBase):
self.asr_ws = None
self.forward_task = None
self.is_processing = False
self.server_ready = False # 服务器准备状态
self.task_id = None # 当前任务ID
self.server_ready = False # Server ready status
self.task_id = None # Current task ID
# 阿里百炼配置
# Aliyun Bailian configuration
self.api_key = config.get("api_key")
self.model = config.get("model", "paraformer-realtime-v2")
self.sample_rate = config.get("sample_rate", 16000)
self.format = config.get("format", "pcm")
# 可选参数
# Optional parameters
self.vocabulary_id = config.get("vocabulary_id")
self.disfluency_removal_enabled = config.get("disfluency_removal_enabled", False)
self.language_hints = config.get("language_hints")
@ -52,40 +52,40 @@ class ASRProvider(ASRProviderBase):
await super().open_audio_channels(conn)
async def receive_audio(self, conn, audio, audio_have_voice):
# 初始化音频缓存
# Initialize audio buffer
if not hasattr(conn, 'asr_audio_for_voiceprint'):
conn.asr_audio_for_voiceprint = []
# 存储音频数据
# Store audio data
if audio:
conn.asr_audio_for_voiceprint.append(audio)
conn.asr_audio.append(audio)
conn.asr_audio = conn.asr_audio[-10:]
# 只在有声音且没有连接时建立连接
# Establish connection only if there is voice and no connection exists
if audio_have_voice and not self.is_processing and not self.asr_ws:
try:
await self._start_recognition(conn)
except Exception as e:
logger.bind(tag=TAG).error(f"开始识别失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to start recognition: {str(e)}")
await self._cleanup()
return
# 发送音频数据
# Send audio data
if self.asr_ws and self.is_processing and self.server_ready:
try:
pcm_frame = self.decoder.decode(audio, 960)
# 直接发送PCM音频数据(二进制)
# Directly send PCM audio data (binary)
await self.asr_ws.send(pcm_frame)
except Exception as e:
logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}")
logger.bind(tag=TAG).warning(f"Failed to send audio: {str(e)}")
await self._cleanup()
async def _start_recognition(self, conn):
"""开始识别会话"""
"""Start recognition session"""
try:
# 如果为手动模式,设置超时时长为最大值
# If manual mode, set timeout to max value
if conn.client_listen_mode == "manual":
self.max_sentence_silence = 6000
@ -97,7 +97,7 @@ class ASRProvider(ASRProviderBase):
"Authorization": f"Bearer {self.api_key}"
}
logger.bind(tag=TAG).debug(f"正在连接阿里百炼ASR服务, task_id: {self.task_id}")
logger.bind(tag=TAG).debug(f"Connecting to Aliyun Bailian ASR service, task_id: {self.task_id}")
self.asr_ws = await websockets.connect(
self.ws_url,
@ -108,18 +108,18 @@ class ASRProvider(ASRProviderBase):
close_timeout=5,
)
logger.bind(tag=TAG).debug("WebSocket连接建立成功")
logger.bind(tag=TAG).debug("WebSocket connection established")
self.server_ready = False
self.forward_task = asyncio.create_task(self._forward_results(conn))
# 发送run-task指令
# Send run-task command
run_task_msg = self._build_run_task_message()
await self.asr_ws.send(json.dumps(run_task_msg, ensure_ascii=False))
logger.bind(tag=TAG).debug("已发送run-task指令,等待服务器准备...")
logger.bind(tag=TAG).debug("Sent run-task command, waiting for server preparation...")
except Exception as e:
logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to establish ASR connection: {str(e)}")
if self.asr_ws:
await self.asr_ws.close()
self.asr_ws = None
@ -127,7 +127,7 @@ class ASRProvider(ASRProviderBase):
raise
def _build_run_task_message(self) -> dict:
"""构建run-task指令"""
"""Build run-task command"""
message = {
"header": {
"action": "run-task",
@ -153,7 +153,7 @@ class ASRProvider(ASRProviderBase):
}
}
# 只有当模型名称以v2结尾时才添加vocabulary_id参数
# Add vocabulary_id only if model name ends with v2
if self.model.lower().endswith("v2"):
message["payload"]["parameters"]["vocabulary_id"] = self.vocabulary_id
@ -163,7 +163,7 @@ class ASRProvider(ASRProviderBase):
return message
async def _forward_results(self, conn):
"""转发识别结果"""
"""Forward recognition results"""
try:
while not conn.stop_event.is_set():
try:
@ -174,23 +174,23 @@ class ASRProvider(ASRProviderBase):
payload = result.get("payload", {})
event = header.get("event", "")
# 处理task-started事件
# Handle task-started event
if event == "task-started":
self.server_ready = True
logger.bind(tag=TAG).debug("服务器已准备,开始发送缓存音频...")
logger.bind(tag=TAG).debug("Server ready, starting to send cached audio...")
# 发送缓存音频
# Send cached audio
if conn.asr_audio:
for cached_audio in conn.asr_audio[-10:]:
try:
pcm_frame = self.decoder.decode(cached_audio, 960)
await self.asr_ws.send(pcm_frame)
except Exception as e:
logger.bind(tag=TAG).warning(f"发送缓存音频失败: {e}")
logger.bind(tag=TAG).warning(f"Failed to send cached audio: {e}")
break
continue
# 处理result-generated事件
# Handle result-generated event
elif event == "result-generated":
output = payload.get("output", {})
sentence = output.get("sentence", {})
@ -199,63 +199,63 @@ class ASRProvider(ASRProviderBase):
sentence_end = sentence.get("sentence_end", False)
end_time = sentence.get("end_time")
# 判断是否为最终结果(sentence_end为True且end_time不为null)
# Determine if it is final result (sentence_end is True and end_time is not null)
is_final = sentence_end and end_time is not None
if is_final:
logger.bind(tag=TAG).info(f"识别到文本: {text}")
logger.bind(tag=TAG).info(f"Recognized text: {text}")
# 手动模式下累积识别结果
# Accumulate recognition results in manual mode
if conn.client_listen_mode == "manual":
if self.text:
self.text += text
else:
self.text = text
# 手动模式下,只有在收到stop信号后才触发处理
# In manual mode, only trigger processing after receiving stop signal
if conn.client_voice_stop:
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
if len(audio_data) > 0:
logger.bind(tag=TAG).debug("收到最终识别结果,触发处理")
logger.bind(tag=TAG).debug("Received final recognition result, triggering processing")
await self.handle_voice_stop(conn, audio_data)
# 清理音频缓存
# Clear audio cache
conn.asr_audio.clear()
conn.reset_vad_states()
break
else:
# 自动模式下直接覆盖
# Overwrite directly in auto mode
self.text = text
conn.reset_vad_states()
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
await self.handle_voice_stop(conn, audio_data)
break
# 处理task-finished事件
# Handle task-finished event
elif event == "task-finished":
logger.bind(tag=TAG).debug("任务已完成")
logger.bind(tag=TAG).debug("Task finished")
break
# 处理task-failed事件
# Handle task-failed event
elif event == "task-failed":
error_code = header.get("error_code", "UNKNOWN")
error_message = header.get("error_message", "未知错误")
logger.bind(tag=TAG).error(f"任务失败: {error_code} - {error_message}")
error_message = header.get("error_message", "Unknown error")
logger.bind(tag=TAG).error(f"Task failed: {error_code} - {error_message}")
break
except asyncio.TimeoutError:
continue
except websockets.ConnectionClosed:
logger.bind(tag=TAG).info("ASR服务连接已关闭")
logger.bind(tag=TAG).info("ASR service connection closed")
self.is_processing = False
break
except Exception as e:
logger.bind(tag=TAG).error(f"处理结果失败: {str(e)}")
logger.bind(tag=TAG).error(f"Result processing failed: {str(e)}")
break
except Exception as e:
logger.bind(tag=TAG).error(f"结果转发失败: {str(e)}")
logger.bind(tag=TAG).error(f"Result forwarding failed: {str(e)}")
finally:
# 清理连接的音频缓存
# Clean up connected audio cache
await self._cleanup()
if conn:
if hasattr(conn, 'asr_audio_for_voiceprint'):
@ -264,19 +264,19 @@ class ASRProvider(ASRProviderBase):
conn.asr_audio = []
async def _send_stop_request(self):
"""发送停止请求(用于手动模式停止录音)"""
"""Send stop request (for manual mode stop recording)"""
if self.asr_ws:
try:
# 先停止音频发送
# Stop sending audio first
self.is_processing = False
logger.bind(tag=TAG).debug("收到停止请求,发送finish-task指令")
logger.bind(tag=TAG).debug("Received stop request, sending finish-task command")
await self._send_finish_task()
except Exception as e:
logger.bind(tag=TAG).error(f"发送停止请求失败: {e}")
logger.bind(tag=TAG).error(f"Failed to send stop request: {e}")
async def _send_finish_task(self):
"""发送finish-task指令"""
"""Send finish-task command"""
if self.asr_ws and self.task_id:
try:
finish_msg = {
@ -290,49 +290,49 @@ class ASRProvider(ASRProviderBase):
}
}
await self.asr_ws.send(json.dumps(finish_msg, ensure_ascii=False))
logger.bind(tag=TAG).debug("已发送finish-task指令")
logger.bind(tag=TAG).debug("Sent finish-task command")
except Exception as e:
logger.bind(tag=TAG).error(f"发送finish-task指令失败: {e}")
logger.bind(tag=TAG).error(f"Failed to send finish-task command: {e}")
async def _cleanup(self):
"""清理资源"""
logger.bind(tag=TAG).debug(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}")
"""Cleanup resources"""
logger.bind(tag=TAG).debug(f"Starting ASR session cleanup | Current Status: processing={self.is_processing}, server_ready={self.server_ready}")
# 状态重置
# Reset status
self.is_processing = False
self.server_ready = False
logger.bind(tag=TAG).debug("ASR状态已重置")
logger.bind(tag=TAG).debug("ASR status reset")
# 关闭连接
if self.asr_ws:
try:
# 先发送finish-task指令
# Send finish-task command first
await self._send_finish_task()
# 等待一小段时间让服务器处理
# Wait for server to process
await asyncio.sleep(0.1)
logger.bind(tag=TAG).debug("正在关闭WebSocket连接")
logger.bind(tag=TAG).debug("Closing WebSocket connection")
await asyncio.wait_for(self.asr_ws.close(), timeout=2.0)
logger.bind(tag=TAG).debug("WebSocket连接已关闭")
logger.bind(tag=TAG).debug("WebSocket connection closed")
except Exception as e:
logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}")
logger.bind(tag=TAG).error(f"Failed to close WebSocket connection: {e}")
finally:
self.asr_ws = None
# 清理任务引用
# Clean up task reference
self.forward_task = None
self.task_id = None
logger.bind(tag=TAG).debug("ASR会话清理完成")
logger.bind(tag=TAG).debug("ASR session cleanup completed")
async def speech_to_text(self, opus_data, session_id, audio_format):
"""获取识别结果"""
"""Get recognition result"""
result = self.text
self.text = ""
return result, None
async def close(self):
"""关闭资源"""
"""Close resources"""
await self._cleanup()
if hasattr(self, 'decoder') and self.decoder is not None:
try:
@ -340,4 +340,4 @@ class ASRProvider(ASRProviderBase):
self.decoder = None
logger.bind(tag=TAG).debug("Aliyun BL decoder resources released")
except Exception as e:
logger.bind(tag=TAG).debug(f"释放Aliyun BL decoder资源时出错: {e}")
logger.bind(tag=TAG).debug(f"Error releasing Aliyun BL decoder resources: {e}")

View file

@ -26,39 +26,42 @@ class ASRProvider(ASRProviderBase):
self.client = AipSpeech(str(self.app_id), self.api_key, self.secret_key)
# 确保输出目录存在
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""Convert speech data to text"""
if not opus_data:
logger.bind(tag=TAG).warning("音频数据为空!")
logger.bind(tag=TAG).warning("Audio data is empty!")
return None, None
file_path = None
try:
# 检查配置是否已设置
# Check if configuration is set
if not self.app_id or not self.api_key or not self.secret_key:
logger.bind(tag=TAG).error("百度语音识别配置未设置,无法进行识别")
logger.bind(tag=TAG).error("Baidu speech recognition configuration not set, cannot perform recognition")
return None, file_path
# 将Opus音频数据解码为PCM
# Decode Opus audio data to PCM
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件
# Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
self.save_audio_to_file(pcm_data, session_id)
start_time = time.time()
# 识别本地文件
# Recognize local file
result = self.client.asr(
combined_pcm_data,
"pcm",
@ -70,16 +73,16 @@ class ASRProvider(ASRProviderBase):
if result and result["err_no"] == 0:
logger.bind(tag=TAG).debug(
f"百度语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}"
f"Baidu speech recognition time: {time.time() - start_time:.3f}s | Result: {result}"
)
result = result["result"][0]
return result, file_path
else:
raise Exception(
f"百度语音识别失败,错误码: {result['err_no']},错误信息: {result['err_msg']}"
f"Baidu speech recognition failed, error code: {result['err_no']}, error message: {result['err_msg']}"
)
return None, file_path
except Exception as e:
logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True)
logger.bind(tag=TAG).error(f"Error occurred while processing audio! {e}", exc_info=True)
return None, file_path

View file

@ -9,12 +9,13 @@ import asyncio
import traceback
import threading
import opuslib_next
from datetime import datetime
from abc import ABC, abstractmethod
from config.logger import setup_logging
from typing import Optional, Tuple, List
from core.handle.receiveAudioHandle import startToChat
from core.handle.reportHandle import enqueue_asr_report
from core.utils.util import remove_punctuation_and_length
from core.utils.util import remove_punctuation_and_length, check_for_noise
from core.handle.receiveAudioHandle import handleAudioMessage
TAG = __name__
@ -25,18 +26,30 @@ class ASRProviderBase(ABC):
def __init__(self):
pass
# 打开音频通道
# Open audio channel
async def open_audio_channels(self, conn):
conn.asr_priority_thread = threading.Thread(
target=self.asr_text_priority_thread, args=(conn,), daemon=True
)
conn.asr_priority_thread.start()
# 有序处理ASR音频
# Process ASR audio in order
def asr_text_priority_thread(self, conn):
while not conn.stop_event.is_set():
try:
message = conn.asr_audio_queue.get(timeout=1)
# STRICT GATE: Drop audio if client is supposed to be speaking (prevent self-echo/voxing)
if conn.client_is_speaking:
# Clear the queue to discard accumulated echo
while not conn.asr_audio_queue.empty():
try:
conn.asr_audio_queue.get_nowait()
except queue.Empty:
break
logger.bind(tag=TAG).debug("Dropped ASR packet/cleared queue because client_is_speaking=True")
continue
future = asyncio.run_coroutine_threadsafe(
handleAudioMessage(conn, message),
conn.loop,
@ -46,17 +59,17 @@ class ASRProviderBase(ABC):
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"处理ASR文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
f"Failed to process ASR text: {str(e)}, Type: {type(e).__name__}, Stack: {traceback.format_exc()}"
)
continue
# 接收音频
# Receive audio
async def receive_audio(self, conn, audio, audio_have_voice):
if conn.client_listen_mode == "manual":
# 手动模式:缓存音频用于ASR识别
# Manual mode: Cache audio for ASR recognition
conn.asr_audio.append(audio)
else:
# 自动/实时模式:使用VAD检测
# Auto/Real-time mode: Use VAD detection
have_voice = audio_have_voice
conn.asr_audio.append(audio)
@ -64,7 +77,7 @@ class ASRProviderBase(ABC):
conn.asr_audio = conn.asr_audio[-10:]
return
# 自动模式下通过VAD检测到语音停止时触发识别
# Trigger recognition when voice stop detected by VAD in auto mode
if conn.client_voice_stop:
asr_audio_task = conn.asr_audio.copy()
conn.asr_audio.clear()
@ -73,13 +86,13 @@ class ASRProviderBase(ABC):
if len(asr_audio_task) > 15:
await self.handle_voice_stop(conn, asr_audio_task)
# 处理语音停止
# Handle voice stop
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
"""并行处理ASR和声纹识别"""
"""Process ASR and voiceprint recognition in parallel"""
try:
total_start_time = time.monotonic()
# 准备音频数据
# Prepare audio data
if conn.audio_format == "pcm":
pcm_data = asr_audio_task
else:
@ -87,17 +100,37 @@ class ASRProviderBase(ABC):
combined_pcm_data = b"".join(pcm_data)
# 预先准备WAV数据
# Energy-based Noise Filtering:
# Drop audio if it matches the criteria (Short & Low Energy)
if check_for_noise(combined_pcm_data):
logger.bind(tag=TAG).debug(f"Dropped audio packet due to low energy/noise (Size: {len(combined_pcm_data)})")
return
# Prepare WAV data in advance
wav_data = None
if conn.voiceprint_provider and combined_pcm_data:
if (conn.voiceprint_provider or conn.config.get("gemini_speech_to_model")) and combined_pcm_data:
wav_data = self._pcm_to_wav(combined_pcm_data)
# 定义ASR任务
asr_task = self.speech_to_text(asr_audio_task, conn.session_id, conn.audio_format)
# Speech-to-Model check
if conn.config.get("llm", {}).get("provider") == "gemini" and conn.config.get("gemini_speech_to_model"):
logger.bind(tag=TAG).info("Speech-to-Model enabled for Gemini, bypassing ASR.")
speaker_name = ""
if conn.voiceprint_provider and wav_data:
try:
speaker_name = await conn.voiceprint_provider.identify_speaker(wav_data, conn.session_id)
except Exception as e:
logger.bind(tag=TAG).error(f"Voiceprint failed in Speech-to-Model: {e}")
enhanced_text = self._build_enhanced_text("[Speech Input]", speaker_name)
await startToChat(conn, enhanced_text, audio_data=wav_data)
return
# Define ASR task
asr_task = self.speech_to_text(asr_audio_task, conn.session_id, conn.audio_format, client_id=getattr(conn, "client_id", None))
if conn.voiceprint_provider and wav_data:
voiceprint_task = conn.voiceprint_provider.identify_speaker(wav_data, conn.session_id)
# 并发等待两个结果
# Wait for both results concurrently
asr_result, voiceprint_result = await asyncio.gather(
asr_task, voiceprint_task, return_exceptions=True
)
@ -105,69 +138,71 @@ class ASRProviderBase(ABC):
asr_result = await asr_task
voiceprint_result = None
# 记录识别结果 - 检查是否为异常
# Record recognition results - check for exceptions
if isinstance(asr_result, Exception):
logger.bind(tag=TAG).error(f"ASR识别失败: {asr_result}")
logger.bind(tag=TAG).error(f"ASR recognition failed: {asr_result}")
raw_text = ""
else:
raw_text, _ = asr_result
if isinstance(voiceprint_result, Exception):
logger.bind(tag=TAG).error(f"声纹识别失败: {voiceprint_result}")
logger.bind(tag=TAG).error(f"Voiceprint recognition failed: {voiceprint_result}")
speaker_name = ""
else:
speaker_name = voiceprint_result
# 判断 ASR 结果类型
# Determine ASR result type
if isinstance(raw_text, dict):
# FunASR 返回的 dict 格式
# Dict format returned by FunASR
if speaker_name:
raw_text["speaker"] = speaker_name
# 记录识别结果
# Record recognition results
if raw_text.get("language"):
logger.bind(tag=TAG).info(f"识别语言: {raw_text['language']}")
logger.bind(tag=TAG).info(f"Detected language: {raw_text['language']}")
if raw_text.get("emotion"):
logger.bind(tag=TAG).info(f"识别情绪: {raw_text['emotion']}")
logger.bind(tag=TAG).info(f"Detected emotion: {raw_text['emotion']}")
if raw_text.get("content"):
logger.bind(tag=TAG).info(f"识别文本: {raw_text['content']}")
logger.bind(tag=TAG).info(f"Detected text: {raw_text['content']}")
if speaker_name:
logger.bind(tag=TAG).info(f"识别说话人: {speaker_name}")
logger.bind(tag=TAG).info(f"Identified speaker: {speaker_name}")
# 转换为 JSON 字符串用于下游
# Convert to JSON string for downstream
enhanced_text = json.dumps(raw_text, ensure_ascii=False)
content_for_length_check = raw_text.get("content", "")
else:
# 其他 ASR 返回的纯文本
# Plain text returned by other ASRs
if raw_text:
logger.bind(tag=TAG).info(f"识别文本: {raw_text}")
logger.bind(tag=TAG).info(f"Detected text: {raw_text}")
if speaker_name:
logger.bind(tag=TAG).info(f"识别说话人: {speaker_name}")
logger.bind(tag=TAG).info(f"Identified speaker: {speaker_name}")
# 构建包含说话人信息的JSON字符串
# Build JSON string containing speaker info
enhanced_text = self._build_enhanced_text(raw_text, speaker_name)
content_for_length_check = raw_text
# 性能监控
# Performance monitoring
total_time = time.monotonic() - total_start_time
logger.bind(tag=TAG).debug(f"总处理耗时: {total_time:.3f}s")
logger.bind(tag=TAG).debug(f"Total processing time: {total_time:.3f}s")
# 检查文本长度
# Check text length
text_len, _ = remove_punctuation_and_length(content_for_length_check)
self.stop_ws_connection()
if text_len > 0:
# 使用自定义模块进行上报
# Use custom module for reporting
await startToChat(conn, enhanced_text)
enqueue_asr_report(conn, enhanced_text, asr_audio_task)
elif content_for_length_check:
logger.bind(tag=TAG).info(f"Ignored noise/hallucination: {content_for_length_check}")
except Exception as e:
logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
logger.bind(tag=TAG).error(f"Failed to handle voice stop: {e}")
import traceback
logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}")
logger.bind(tag=TAG).debug(f"Exception details: {traceback.format_exc()}")
def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str:
"""构建包含说话人信息的文本(仅用于纯文本ASR)"""
"""Build text containing speaker info (only for plain text ASR)"""
if speaker_name and speaker_name.strip():
return json.dumps({
"speaker": speaker_name,
@ -177,22 +212,22 @@ class ASRProviderBase(ABC):
return text
def _pcm_to_wav(self, pcm_data: bytes) -> bytes:
"""将PCM数据转换为WAV格式"""
"""Convert PCM data to WAV format"""
if len(pcm_data) == 0:
logger.bind(tag=TAG).warning("PCM数据为空,无法转换WAV")
logger.bind(tag=TAG).warning("PCM data is empty, cannot convert to WAV")
return b""
# 确保数据长度是偶数(16位音频)
# Ensure data length is even (16-bit audio)
if len(pcm_data) % 2 != 0:
pcm_data = pcm_data[:-1]
# 创建WAV文件头
# Create WAV file header
wav_buffer = io.BytesIO()
try:
with wave.open(wav_buffer, 'wb') as wav_file:
wav_file.setnchannels(1) # 单声道
wav_file.setsampwidth(2) # 16位
wav_file.setframerate(16000) # 16kHz采样率
wav_file.setnchannels(1) # Mono
wav_file.setsampwidth(2) # 16-bit
wav_file.setframerate(16000) # 16kHz sample rate
wav_file.writeframes(pcm_data)
wav_buffer.seek(0)
@ -200,17 +235,32 @@ class ASRProviderBase(ABC):
return wav_data
except Exception as e:
logger.bind(tag=TAG).error(f"WAV转换失败: {e}")
logger.bind(tag=TAG).error(f"WAV conversion failed: {e}")
return b""
def stop_ws_connection(self):
pass
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
"""PCM数据保存为WAV文件"""
module_name = __name__.split(".")[-1]
file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
file_path = os.path.join(self.output_dir, file_name)
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str, client_id: str = None) -> str:
"""Save PCM data as WAV file"""
if client_id:
# Client-specific directory: data/{client_id}/
# Get project root (assuming output_dir is relative to project root or use absolute path)
# We'll assume current working directory is project root or close enough
client_dir = os.path.join("data", client_id)
if not os.path.exists(client_dir):
os.makedirs(client_dir, exist_ok=True)
# Timestamp suffix: YYMMDD-hhmmss-ffffff
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
file_name = f"ASR_{timestamp}.wav"
file_path = os.path.join(client_dir, file_name)
else:
# Fallback to default behavior
module_name = __name__.split(".")[-1]
file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
# output_dir from config
file_path = os.path.join(self.output_dir, file_name)
with wave.open(file_path, "wb") as wf:
wf.setnchannels(1)
@ -220,21 +270,54 @@ class ASRProviderBase(ABC):
return file_path
def save_audio_background(self, pcm_data: List[bytes], session_id: str, client_id: str = None) -> str:
"""Save PCM data as WAV file in background (non-blocking)"""
# Generate path first
if client_id:
client_dir = os.path.join("data", client_id)
if not os.path.exists(client_dir):
os.makedirs(client_dir, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
file_name = f"ASR_{timestamp}.wav"
file_path = os.path.join(client_dir, file_name)
else:
module_name = __name__.split(".")[-1]
file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
file_path = os.path.join(self.output_dir, file_name)
# Define write operation
def _write():
try:
# Ensure directory exists (again, just in case of race/thread safety)
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with wave.open(file_path, "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(16000)
wf.writeframes(b"".join(pcm_data))
except Exception as e:
logger.bind(tag=TAG).error(f"Background audio save failed: {e}")
# Fire and forget
threading.Thread(target=_write, daemon=True).start()
return file_path
@abstractmethod
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
self, opus_data: List[bytes], session_id: str, audio_format="opus", client_id: str = None
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
"""Convert speech data to text"""
pass
@staticmethod
def decode_opus(opus_data: List[bytes]) -> List[bytes]:
"""将Opus音频数据解码为PCM数据"""
"""Decode Opus audio data to PCM data"""
decoder = None
try:
decoder = opuslib_next.Decoder(16000, 1)
pcm_data = []
buffer_size = 960 # 每次处理960个采样点 (60ms at 16kHz)
buffer_size = 960 # Process 960 samples each time (60ms at 16kHz)
for i, opus_packet in enumerate(opus_data):
try:
@ -246,18 +329,18 @@ class ASRProviderBase(ABC):
pcm_data.append(pcm_frame)
except opuslib_next.OpusError as e:
logger.bind(tag=TAG).warning(f"Opus解码错误,跳过数据包 {i}: {e}")
logger.bind(tag=TAG).warning(f"Opus decoding error, skipping packet {i}: {e}")
except Exception as e:
logger.bind(tag=TAG).error(f"音频处理错误,数据包 {i}: {e}")
logger.bind(tag=TAG).error(f"Audio processing error, packet {i}: {e}")
return pcm_data
except Exception as e:
logger.bind(tag=TAG).error(f"音频解码过程发生错误: {e}")
logger.bind(tag=TAG).error(f"Error during audio decoding process: {e}")
return []
finally:
if decoder is not None:
try:
del decoder
except Exception as e:
logger.bind(tag=TAG).debug(f"释放decoder资源时出错: {e}")
logger.bind(tag=TAG).debug(f"Error releasing decoder resources: {e}")

View file

@ -37,9 +37,12 @@ def parse_response(res):
protocol_version(4 bits), header_size(4 bits),
message_type(4 bits), message_type_specific_flags(4 bits)
serialization_method(4 bits) message_compression(4 bits)
reserved (8bits) 保留字段
header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) )
payload 类似与http 请求体
protocol_version(4 bits), header_size(4 bits),
message_type(4 bits), message_type_specific_flags(4 bits)
serialization_method(4 bits) message_compression(4 bits)
reserved (8bits)
header_extensions (size equals 8 * 4 * (header_size - 1))
payload (similar to http request body)
"""
protocol_version = res[0] >> 4
header_size = res[0] & 0x0F
@ -97,7 +100,7 @@ class ASRProvider(ASRProviderBase):
self.success_code = 1000
self.seg_duration = 15000
# 确保输出目录存在
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
@staticmethod
@ -168,7 +171,7 @@ class ASRProvider(ASRProviderBase):
if (
"payload_msg" in result
and result["payload_msg"]["code"] != self.success_code
and result["payload_msg"]["code"] != 1013 # 忽略无有效语音的错误
and result["payload_msg"]["code"] != 1013 # Ignore error for no valid voice
):
logger.bind(tag=TAG).error(f"ASR error: {result}")
return None
@ -205,7 +208,7 @@ class ASRProvider(ASRProviderBase):
return result["payload_msg"]["result"][0]["text"]
return None
elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
# 无有效语音,返回空字符串
# No valid voice, return empty string
return ""
else:
logger.bind(tag=TAG).error(f"ASR error: {result}")
@ -234,38 +237,38 @@ class ASRProvider(ASRProviderBase):
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
"""Convert speech data to text"""
file_path = None
try:
# 合并所有opus数据包
# Merge all opus data packets
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件
# Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
file_path = self.save_audio_to_file(pcm_data, session_id)
# 直接使用PCM数据
# 计算分段大小 (单声道, 16bit, 16kHz采样率)
# Use PCM data directly
# Calculate segment size (mono, 16bit, 16kHz sample rate)
size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate
segment_size = int(size_per_sec * self.seg_duration / 1000)
# 语音识别
# Speech recognition
start_time = time.time()
text = await self._send_request(combined_pcm_data, segment_size)
if text:
logger.bind(tag=TAG).debug(
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
)
return text, file_path
return "", file_path
except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
logger.bind(tag=TAG).error(f"Speech recognition failed: {e}", exc_info=True)
return "", file_path

View file

@ -21,9 +21,9 @@ class ASRProvider(ASRProviderBase):
self.decoder = opuslib_next.Decoder(16000, 1)
self.asr_ws = None
self.forward_task = None
self.is_processing = False # 添加处理状态标志
self.is_processing = False # Add processing status flag
# 配置参数
# Configuration parameters
self.appid = str(config.get("appid"))
self.cluster = config.get("cluster")
self.access_token = config.get("access_token")
@ -32,7 +32,7 @@ class ASRProvider(ASRProviderBase):
self.output_dir = config.get("output_dir", "tmp/")
self.delete_audio_file = delete_audio_file
# 火山引擎ASR配置
# Volcengine ASR configuration
enable_multilingual = config.get("enable_multilingual", False)
self.enable_multilingual = False if str(enable_multilingual).lower() == 'false' else True
if self.enable_multilingual:
@ -47,7 +47,7 @@ class ASRProvider(ASRProviderBase):
self.format = config.get("format", "pcm")
self.codec = config.get("codec", "pcm")
self.rate = config.get("sample_rate", 16000)
# language参数仅在多语种模式(bigmodel_nostream)下有效
# language parameter is only valid in multilingual mode (bigmodel_nostream)
self.language = config.get("language") if self.enable_multilingual else None
self.bits = config.get("bits", 16)
self.channel = config.get("channel", 1)
@ -62,23 +62,23 @@ class ASRProvider(ASRProviderBase):
async def receive_audio(self, conn, audio, audio_have_voice):
conn.asr_audio.append(audio)
conn.asr_audio = conn.asr_audio[-10:]
# 存储音频数据
# Store audio data
if not hasattr(conn, 'asr_audio_for_voiceprint'):
conn.asr_audio_for_voiceprint = []
conn.asr_audio_for_voiceprint.append(audio)
# 当没有音频数据时处理完整语音片段
# Process complete voice segment when no audio data
if conn.client_listen_mode != "manual" and not audio and len(conn.asr_audio_for_voiceprint) > 0:
await self.handle_voice_stop(conn, conn.asr_audio_for_voiceprint)
conn.asr_audio_for_voiceprint = []
# 如果本次有声音,且之前没有建立连接
# If voice detected, and connection not established
if audio_have_voice and self.asr_ws is None and not self.is_processing:
try:
self.is_processing = True
# 建立新的WebSocket连接
# Establish new WebSocket connection
headers = self.token_auth() if self.auth_method == "token" else None
logger.bind(tag=TAG).info(f"正在连接ASR服务,headers: {headers}")
logger.bind(tag=TAG).info(f"Connecting to ASR service, headers: {headers}")
self.asr_ws = await websockets.connect(
self.ws_url,
@ -89,7 +89,7 @@ class ASRProvider(ASRProviderBase):
close_timeout=10,
)
# 发送初始化请求
# Send initialization request
request_params = self.construct_request(str(uuid.uuid4()))
try:
payload_bytes = str.encode(json.dumps(request_params))
@ -98,30 +98,30 @@ class ASRProvider(ASRProviderBase):
full_client_request.extend((len(payload_bytes)).to_bytes(4, "big"))
full_client_request.extend(payload_bytes)
logger.bind(tag=TAG).info(f"发送初始化请求: {request_params}")
logger.bind(tag=TAG).info(f"Send initialization request: {request_params}")
await self.asr_ws.send(full_client_request)
# 等待初始化响应
# Wait for initialization response
init_res = await self.asr_ws.recv()
result = self.parse_response(init_res)
logger.bind(tag=TAG).info(f"收到初始化响应: {result}")
logger.bind(tag=TAG).info(f"Received initialization response: {result}")
# 检查初始化响应
# Check initialization response
if "code" in result and result["code"] != 1000:
error_msg = f"ASR服务初始化失败: {result.get('payload_msg', {}).get('error', '未知错误')}"
error_msg = f"ASR service initialization failed: {result.get('payload_msg', {}).get('error', 'Unknown error')}"
logger.bind(tag=TAG).error(error_msg)
raise Exception(error_msg)
except Exception as e:
logger.bind(tag=TAG).error(f"发送初始化请求失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to send initialization request: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
raise e
# 启动接收ASR结果的异步任务
# Start async task to receive ASR results
self.forward_task = asyncio.create_task(self._forward_asr_results(conn))
# 发送缓存的音频数据
# Send cached audio data
if conn.asr_audio and len(conn.asr_audio) > 0:
for cached_audio in conn.asr_audio[-10:]:
try:
@ -135,20 +135,20 @@ class ASRProvider(ASRProviderBase):
await self.asr_ws.send(audio_request)
except Exception as e:
logger.bind(tag=TAG).info(
f"发送缓存音频数据时发生错误: {e}"
f"Error sending cached audio data: {e}"
)
except Exception as e:
logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to establish ASR connection: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
if self.asr_ws:
await self.asr_ws.close()
self.asr_ws = None
self.is_processing = False
return
# 发送当前音频数据
# Send current audio data
if self.asr_ws and self.is_processing:
try:
pcm_frame = self.decoder.decode(audio, 960)
@ -158,52 +158,52 @@ class ASRProvider(ASRProviderBase):
audio_request.extend(payload)
await self.asr_ws.send(audio_request)
except Exception as e:
logger.bind(tag=TAG).info(f"发送音频数据时发生错误: {e}")
logger.bind(tag=TAG).info(f"Error sending audio data: {e}")
async def _forward_asr_results(self, conn):
try:
while self.asr_ws and not conn.stop_event.is_set():
# 获取当前连接的音频数据
# Get audio data of current connection
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
try:
response = await self.asr_ws.recv()
result = self.parse_response(response)
logger.bind(tag=TAG).debug(f"收到ASR结果: {result}")
logger.bind(tag=TAG).debug(f"Received ASR result: {result}")
if "payload_msg" in result:
payload = result["payload_msg"]
# 检查是否是错误码1013(无有效语音)
# Check if it is error code 1013 (no valid voice)
if "code" in payload and payload["code"] == 1013:
# 静默处理,不记录错误日志
# Silent handling, do not log error
continue
if "result" in payload:
utterances = payload["result"].get("utterances", [])
# 检查duration和空文本的情况
# Check duration and empty text cases
if (
not self.enable_multilingual # 注意:多语种模式不返回中间结果,需要等待最终结果
not self.enable_multilingual # Note: Multilingual mode does not return intermediate results, need to wait for final result
and payload.get("audio_info", {}).get("duration", 0) > 2000
and not utterances
and not payload["result"].get("text")
and conn.client_listen_mode != "manual"
):
logger.bind(tag=TAG).error(f"识别文本:空")
logger.bind(tag=TAG).error(f"Recognition text: Empty")
self.text = ""
conn.reset_vad_states()
if len(audio_data) > 15: # 确保有足够音频数据
if len(audio_data) > 15: # Ensure enough audio data
await self.handle_voice_stop(conn, audio_data)
break
# 专门处理没有文本的识别结果(手动模式下可能已经识别完成但是没松按键)
# Handle cases with no text result (Manual mode might have finished recognition but button not released)
elif not payload["result"].get("text") and not utterances:
# 多语种模式会持续返回空文本,直到最后返回完整结果,所以需要排除
# Multilingual mode keeps returning empty text until final result, so exclude it
if self.enable_multilingual:
continue
if conn.client_listen_mode == "manual" and conn.client_voice_stop and len(audio_data) > 0:
logger.bind(tag=TAG).debug("消息结束收到停止信号,触发处理")
logger.bind(tag=TAG).debug("Received stop signal at end of message, trigger processing")
await self.handle_voice_stop(conn, audio_data)
# 清理音频缓存
# Clear audio cache
conn.asr_audio.clear()
conn.reset_vad_states()
break
@ -212,51 +212,51 @@ class ASRProvider(ASRProviderBase):
if utterance.get("definite", False):
current_text = utterance["text"]
logger.bind(tag=TAG).info(
f"识别到文本: {current_text}"
f"Recognized text: {current_text}"
)
# 手动模式下累积识别结果
# Accumulate recognition results in manual mode
if conn.client_listen_mode == "manual":
if self.text:
self.text += current_text
else:
self.text = current_text
# 在接收消息中途时收到停止信号
# Received stop signal in the middle of message
if conn.client_voice_stop and len(audio_data) > 0:
logger.bind(tag=TAG).debug("消息中途收到停止信号,触发处理")
logger.bind(tag=TAG).debug("Received stop signal in middle of message, trigger processing")
await self.handle_voice_stop(conn, audio_data)
# 清理音频缓存
# Clear audio cache
conn.asr_audio.clear()
conn.reset_vad_states()
break
else:
# 自动模式下直接覆盖
# Overwrite directly in auto mode
self.text = current_text
conn.reset_vad_states()
if len(audio_data) > 15: # 确保有足够音频数据
if len(audio_data) > 15: # Ensure enough audio data
await self.handle_voice_stop(conn, audio_data)
break
elif "error" in payload:
error_msg = payload.get("error", "未知错误")
logger.bind(tag=TAG).error(f"ASR服务返回错误: {error_msg}")
error_msg = payload.get("error", "Unknown error")
logger.bind(tag=TAG).error(f"ASR service returned error: {error_msg}")
break
except websockets.ConnectionClosed:
logger.bind(tag=TAG).info("ASR服务连接已关闭")
logger.bind(tag=TAG).info("ASR service connection closed")
self.is_processing = False
break
except Exception as e:
logger.bind(tag=TAG).error(f"处理ASR结果时发生错误: {str(e)}")
logger.bind(tag=TAG).error(f"Error processing ASR result: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
self.is_processing = False
break
except Exception as e:
logger.bind(tag=TAG).error(f"ASR结果转发任务发生错误: {str(e)}")
logger.bind(tag=TAG).error(f"ASR result forwarding task error: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
finally:
if self.asr_ws:
await self.asr_ws.close()
@ -275,18 +275,18 @@ class ASRProvider(ASRProviderBase):
self.is_processing = False
async def _send_stop_request(self):
"""发送最后一个音频帧以通知服务器结束"""
"""Send last audio frame to notify server to end"""
if self.asr_ws:
try:
# 发送结束标记的音频帧(gzip压缩的空数据)
# Send audio frame with end marker (gzip compressed empty data)
empty_payload = gzip.compress(b"")
last_audio_request = bytearray(self.generate_last_audio_default_header())
last_audio_request.extend(len(empty_payload).to_bytes(4, "big"))
last_audio_request.extend(empty_payload)
await self.asr_ws.send(last_audio_request)
logger.bind(tag=TAG).debug("已发送结束音频帧")
logger.bind(tag=TAG).debug("Sent end audio frame")
except Exception as e:
logger.bind(tag=TAG).debug(f"发送结束音频帧时出错: {e}")
logger.bind(tag=TAG).debug(f"Error sending end audio frame: {e}")
def construct_request(self, reqid):
req = {
@ -321,7 +321,7 @@ class ASRProvider(ASRProviderBase):
req["audio"]["language"] = self.language
logger.bind(tag=TAG).debug(
f"构造请求参数: {json.dumps(req, ensure_ascii=False)}"
f"Construct request parameters: {json.dumps(req, ensure_ascii=False)}"
)
return req
@ -372,16 +372,16 @@ class ASRProvider(ASRProviderBase):
def parse_response(self, res: bytes) -> dict:
try:
# 检查响应长度
# Check response length
if len(res) < 4:
logger.bind(tag=TAG).error(f"响应数据长度不足: {len(res)}")
return {"error": "响应数据长度不足"}
logger.bind(tag=TAG).error(f"Insufficient response data length: {len(res)}")
return {"error": "Insufficient response data length"}
# 获取消息头
# Get message header
header = res[:4]
message_type = header[1] >> 4
# 如果是错误响应
# If error response
if message_type == 0x0F: # SERVER_ERROR_RESPONSE
code = int.from_bytes(res[4:8], "big", signed=False)
msg_length = int.from_bytes(res[8:12], "big", signed=False)
@ -392,25 +392,25 @@ class ASRProvider(ASRProviderBase):
"payload_msg": error_msg,
}
# 获取JSON数据(跳过12字节头部)
# Get JSON data (skip 12 bytes header)
try:
json_data = res[12:].decode("utf-8")
result = json.loads(json_data)
logger.bind(tag=TAG).debug(f"成功解析JSON响应: {result}")
logger.bind(tag=TAG).debug(f"Successfully parsed JSON response: {result}")
return {"payload_msg": result}
except (UnicodeDecodeError, json.JSONDecodeError) as e:
logger.bind(tag=TAG).error(f"JSON解析失败: {str(e)}")
logger.bind(tag=TAG).error(f"原始数据: {res}")
logger.bind(tag=TAG).error(f"JSON parsing failed: {str(e)}")
logger.bind(tag=TAG).error(f"Original data: {res}")
raise
except Exception as e:
logger.bind(tag=TAG).error(f"解析响应失败: {str(e)}")
logger.bind(tag=TAG).error(f"原始响应数据: {res.hex()}")
logger.bind(tag=TAG).error(f"Failed to parse response: {str(e)}")
logger.bind(tag=TAG).error(f"Original response data: {res.hex()}")
raise
async def speech_to_text(self, opus_data, session_id, audio_format):
result = self.text
self.text = "" # 清空text
self.text = "" # Clear text
return result, None
async def close(self):

View file

@ -17,10 +17,10 @@ TAG = __name__
logger = setup_logging()
MAX_RETRIES = 2
RETRY_DELAY = 1 # 重试延迟(秒)
RETRY_DELAY = 1 # Retry delay (seconds)
# 捕获标准输出
# Capture standard output
class CaptureOutput:
def __enter__(self):
self._output = io.StringIO()
@ -32,7 +32,7 @@ class CaptureOutput:
self.output = self._output.getvalue()
self._output.close()
# 将捕获到的内容通过 logger 输出
# Output captured content via logger
if self.output:
logger.bind(tag=TAG).info(self.output.strip())
@ -41,38 +41,39 @@ class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
# 内存检测,要求大于2G
# Memory check, requires > 2G
min_mem_bytes = 2 * 1024 * 1024 * 1024
total_mem = psutil.virtual_memory().total
if total_mem < min_mem_bytes:
logger.bind(tag=TAG).error(f"可用内存不足2G,当前仅有 {total_mem / (1024*1024):.2f} MB,可能无法启动FunASR")
logger.bind(tag=TAG).error(f"Available memory less than 2G, currently only {total_mem / (1024*1024):.2f} MB, FunASR might not start")
self.interface_type = InterfaceType.LOCAL
self.model_dir = config.get("model_dir")
self.output_dir = config.get("output_dir") # 修正配置键名
self.output_dir = config.get("output_dir") # Correct config key name
self.device = config.get("device", "cpu")
self.delete_audio_file = delete_audio_file
# 确保输出目录存在
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
with CaptureOutput():
self.model = AutoModel(
model=self.model_dir,
vad_kwargs={"max_single_segment_time": 30000},
disable_update=True,
hub="hf",
# device="cuda:0", # 启用GPU加速
hub="ms",
device=self.device,
)
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
self, opus_data: List[bytes], session_id: str, audio_format="opus", client_id: str = None
) -> Tuple[Optional[str], Optional[str]]:
"""语音转文本主处理逻辑"""
"""Main speech-to-text processing logic"""
file_path = None
retry_count = 0
while retry_count < MAX_RETRIES:
try:
# 合并所有opus数据包
# Merge all Opus packets
if audio_format == "pcm":
pcm_data = opus_data
else:
@ -80,19 +81,19 @@ class ASRProvider(ASRProviderBase):
combined_pcm_data = b"".join(pcm_data)
# 检查磁盘空间
# Check disk space
if not self.delete_audio_file:
free_space = shutil.disk_usage(self.output_dir).free
if free_space < len(combined_pcm_data) * 2: # 预留2倍空间
raise OSError("磁盘空间不足")
if free_space < len(combined_pcm_data) * 2: # Reserve 2x space
raise OSError("Insufficient disk space")
# 判断是否保存为WAV文件
# Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
file_path = self.save_audio_to_file(pcm_data, session_id)
file_path = self.save_audio_background(pcm_data, session_id, client_id=client_id)
# 语音识别 - 使用线程池避免阻塞事件循环
# Speech recognition - use thread pool to avoid blocking event loop
start_time = time.time()
result = await asyncio.to_thread(
self.model.generate,
@ -102,9 +103,26 @@ class ASRProvider(ASRProviderBase):
use_itn=True,
batch_size_s=60,
)
text = lang_tag_filter(result[0]["text"])
# Parse content based on different model return structures
raw_text = ""
if isinstance(result, list) and len(result) > 0:
item = result[0]
if isinstance(item, dict):
raw_text = item.get("text", "")
elif isinstance(item, str):
raw_text = item
else:
raw_text = str(item)
elif isinstance(result, dict):
raw_text = result.get("text", "")
else:
raw_text = str(result)
text = lang_tag_filter(raw_text)
log_content = text["content"] if isinstance(text, dict) else text
logger.bind(tag=TAG).debug(
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text['content']}"
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {log_content}"
)
return text, file_path
@ -113,25 +131,25 @@ class ASRProvider(ASRProviderBase):
retry_count += 1
if retry_count >= MAX_RETRIES:
logger.bind(tag=TAG).error(
f"语音识别失败(已重试{retry_count}次): {e}", exc_info=True
f"Speech recognition failed (retried {retry_count} times): {e}", exc_info=True
)
return "", file_path
logger.bind(tag=TAG).warning(
f"语音识别失败,正在重试({retry_count}/{MAX_RETRIES}): {e}"
f"Speech recognition failed, retrying ({retry_count}/{MAX_RETRIES}): {e}"
)
time.sleep(RETRY_DELAY)
except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
logger.bind(tag=TAG).error(f"Speech recognition failed: {e}", exc_info=True)
return "", file_path
finally:
# 文件清理逻辑
# File cleanup logic
if self.delete_audio_file and file_path and os.path.exists(file_path):
try:
os.remove(file_path)
logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
logger.bind(tag=TAG).debug(f"Deleted temp audio file: {file_path}")
except Exception as e:
logger.bind(tag=TAG).error(
f"文件删除失败: {file_path} | 错误: {e}"
f"File deletion failed: {file_path} | Error: {e}"
)

View file

@ -116,7 +116,7 @@ class ASRProvider(ASRProviderBase):
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件
# Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:

View file

@ -32,7 +32,7 @@ class ASRProvider(ASRProviderBase):
file_path = self.save_audio_to_file(pcm_data, session_id)
logger.bind(tag=TAG).debug(
f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}"
f"Audio file saved in: {time.time() - start_time:.3f}s | Path: {file_path}"
)
logger.bind(tag=TAG).info(f"file path: {file_path}")
@ -40,13 +40,13 @@ class ASRProvider(ASRProviderBase):
"Authorization": f"Bearer {self.api_key}",
}
# 使用data参数传递模型名称
# Use data parameter to pass model name
data = {
"model": self.model
}
with open(file_path, "rb") as audio_file: # 使用with语句确保文件关闭
with open(file_path, "rb") as audio_file: # Use with statement to ensure file closure
files = {
"file": audio_file
}
@ -59,24 +59,24 @@ class ASRProvider(ASRProviderBase):
headers=headers
)
logger.bind(tag=TAG).debug(
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {response.text}"
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {response.text}"
)
if response.status_code == 200:
text = response.json().get("text", "")
return text, file_path
else:
raise Exception(f"API请求失败: {response.status_code} - {response.text}")
raise Exception(f"API request failed: {response.status_code} - {response.text}")
except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}")
logger.bind(tag=TAG).error(f"Speech recognition failed: {e}")
return "", None
finally:
# 文件清理逻辑
# File cleanup logic
if self.delete_audio_file and file_path and os.path.exists(file_path):
try:
os.remove(file_path)
logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
logger.bind(tag=TAG).debug(f"Temporary audio file deleted: {file_path}")
except Exception as e:
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
logger.bind(tag=TAG).error(f"Failed to delete file: {file_path} | Error: {e}")

View file

@ -13,59 +13,67 @@ logger = setup_logging()
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
# 音频文件上传类型,流式文本识别输出
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
# Audio file upload type, stream text recognition output
self.interface_type = InterfaceType.NON_STREAM
"""Qwen3-ASR-Flash ASR初始化"""
"""Qwen3-ASR-Flash ASR initialization"""
# 配置参数
# Configuration parameters
self.api_key = config.get("api_key")
if not self.api_key:
raise ValueError("Qwen3-ASR-Flash 需要配置 api_key")
raise ValueError("Qwen3-ASR-Flash needs api_key configuration")
self.model_name = config.get("model_name", "qwen3-asr-flash")
self.output_dir = config.get("output_dir", "./audio_output")
self.delete_audio_file = delete_audio_file
# ASR选项配置
self.enable_lid = config.get("enable_lid", True) # 自动语种检测
self.enable_itn = config.get("enable_itn", True) # 逆文本归一化
self.language = config.get("language", None) # 指定语种,默认自动检测
self.context = config.get("context", "") # 上下文信息,用于提高识别准确率
self.delete_audio_file = delete_audio_file
# 确保输出目录存在
# ASR option configuration
self.enable_lid = config.get("enable_lid", True) # Auto language detection
self.enable_itn = config.get("enable_itn", True) # Inverse text normalization
self.language = config.get("language", None) # Specify language, default auto detect
self.context = config.get("context", "") # Context info to improve recognition accuracy
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
def _prepare_audio_file(self, pcm_data: bytes) -> str:
"""将PCM数据转换为WAV文件并返回文件路径"""
"""Convert PCM data to WAV file and return file path"""
try:
import wave
# 创建临时WAV文件
# Create temporary WAV file
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_file:
temp_path = temp_file.name
# 写入WAV格式
# Write WAV format
with wave.open(temp_path, 'wb') as wav_file:
wav_file.setnchannels(1) # 单声道
wav_file.setsampwidth(2) # 16位
wav_file.setframerate(16000) # 16kHz采样率
wav_file.setnchannels(1) # Mono
wav_file.setsampwidth(2) # 16-bit
wav_file.setframerate(16000) # 16kHz sample rate
wav_file.writeframes(pcm_data)
return temp_path
except Exception as e:
logger.bind(tag=tag).error(f"音频文件准备失败: {e}")
logger.bind(tag=tag).error(f"Failed to prepare audio file: {e}")
return None
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""Convert speech data to text"""
temp_file_path = None
file_path = None
try:
# 解码音频数据
# Decode audio data
if audio_format == "pcm":
pcm_data = opus_data
else:
@ -73,19 +81,19 @@ class ASRProvider(ASRProviderBase):
combined_pcm_data = b"".join(pcm_data)
if len(combined_pcm_data) == 0:
logger.bind(tag=tag).warning("音频数据为空")
logger.bind(tag=tag).warning("Audio data is empty")
return "", None
# 准备音频文件
# Prepare audio file
temp_file_path = self._prepare_audio_file(combined_pcm_data)
if not temp_file_path:
return "", None
# 保存音频文件(如果需要)
# Save audio file (if needed)
if not self.delete_audio_file:
file_path = self.save_audio_to_file(pcm_data, session_id)
# 构造请求消息
# Construct request messages
messages = [
{
"role": "user",
@ -95,7 +103,7 @@ class ASRProvider(ASRProviderBase):
}
]
# 如果有上下文信息,添加system消息
# If context info exists, add system message
if self.context:
messages.insert(0, {
"role": "system",
@ -104,20 +112,20 @@ class ASRProvider(ASRProviderBase):
]
})
# 准备ASR选项
# Prepare ASR options
asr_options = {
"enable_lid": self.enable_lid,
"enable_itn": self.enable_itn
}
# 如果指定了语种,添加到选项中
# If language specified, add to options
if self.language:
asr_options["language"] = self.language
# 设置API密钥
# Set API key
dashscope.api_key = self.api_key
# 发送流式请求
# Send streaming request
response = dashscope.MultiModalConversation.call(
model=self.model_name,
messages=messages,
@ -126,12 +134,12 @@ class ASRProvider(ASRProviderBase):
stream=True
)
# 处理流式响应
# Handle streaming response
full_text = ""
for chunk in response:
try:
text = chunk["output"]["choices"][0]["message"].content[0]["text"]
# 更新为最新的完整文本
# Update to latest complete text
full_text = text.strip()
except:
pass
@ -139,13 +147,13 @@ class ASRProvider(ASRProviderBase):
return full_text, file_path
except Exception as e:
logger.bind(tag=tag).error(f"语音识别失败: {e}")
logger.bind(tag=tag).error(f"Speech recognition failed: {e}")
return "", file_path
finally:
# 清理临时文件
# Clean up temporary file
if temp_file_path and os.path.exists(temp_file_path):
try:
os.unlink(temp_file_path)
except Exception as e:
logger.bind(tag=tag).warning(f"清理临时文件失败: {e}")
logger.bind(tag=tag).warning(f"Failed to clean up temporary file: {e}")

View file

@ -17,7 +17,7 @@ TAG = __name__
logger = setup_logging()
# 捕获标准输出
# Capture standard output
class CaptureOutput:
def __enter__(self):
self._output = io.StringIO()
@ -29,7 +29,7 @@ class CaptureOutput:
self.output = self._output.getvalue()
self._output.close()
# 将捕获到的内容通过 logger 输出
# Log captured content through logger
if self.output:
logger.bind(tag=TAG).info(self.output.strip())
@ -40,23 +40,23 @@ class ASRProvider(ASRProviderBase):
self.interface_type = InterfaceType.LOCAL
self.model_dir = config.get("model_dir")
self.output_dir = config.get("output_dir")
self.model_type = config.get("model_type", "sense_voice") # 支持 paraformer
self.model_type = config.get("model_type", "sense_voice") # Support paraformer
self.delete_audio_file = delete_audio_file
# 确保输出目录存在
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
# 初始化模型文件路径
# Initialize model file paths
model_files = {
"model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"),
"tokens.txt": os.path.join(self.model_dir, "tokens.txt"),
}
# 下载并检查模型文件
# Download and check model files
try:
for file_name, file_path in model_files.items():
if not os.path.isfile(file_path):
logger.bind(tag=TAG).info(f"正在下载模型文件: {file_name}")
logger.bind(tag=TAG).info(f"Downloading model file: {file_name}")
model_file_download(
model_id="pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue",
file_path=file_name,
@ -64,13 +64,13 @@ class ASRProvider(ASRProviderBase):
)
if not os.path.isfile(file_path):
raise FileNotFoundError(f"模型文件下载失败: {file_path}")
raise FileNotFoundError(f"Failed to download model file: {file_path}")
self.model_path = model_files["model.int8.onnx"]
self.tokens_path = model_files["tokens.txt"]
except Exception as e:
logger.bind(tag=TAG).error(f"模型文件处理失败: {str(e)}")
logger.bind(tag=TAG).error(f"Model file processing failed: {str(e)}")
raise
with CaptureOutput():
@ -123,10 +123,10 @@ class ASRProvider(ASRProviderBase):
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""语音转文本主处理逻辑"""
"""Main logic for speech to text"""
file_path = None
try:
# 保存音频文件
# Save audio file
start_time = time.time()
if audio_format == "pcm":
pcm_data = opus_data
@ -134,10 +134,10 @@ class ASRProvider(ASRProviderBase):
pcm_data = self.decode_opus(opus_data)
file_path = self.save_audio_to_file(pcm_data, session_id)
logger.bind(tag=TAG).debug(
f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}"
f"Audio file saved in: {time.time() - start_time:.3f}s | Path: {file_path}"
)
# 语音识别
# Speech recognition
start_time = time.time()
s = self.model.create_stream()
samples, sample_rate = self.read_wave(file_path)
@ -145,19 +145,19 @@ class ASRProvider(ASRProviderBase):
self.model.decode_stream(s)
text = s.result.text
logger.bind(tag=TAG).debug(
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
)
return text, file_path
except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
logger.bind(tag=TAG).error(f"Speech recognition failed: {e}", exc_info=True)
return "", file_path
finally:
# 文件清理逻辑
# File cleanup logic
if self.delete_audio_file and file_path and os.path.exists(file_path):
try:
os.remove(file_path)
logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
logger.bind(tag=TAG).debug(f"Temporary audio file deleted: {file_path}")
except Exception as e:
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
logger.bind(tag=TAG).error(f"Failed to delete file: {file_path} | Error: {e}")

View file

@ -18,7 +18,7 @@ logger = setup_logging()
class ASRProvider(ASRProviderBase):
API_URL = "https://asr.tencentcloudapi.com"
API_VERSION = "2019-06-14"
FORMAT = "pcm" # 支持的音频格式:pcm, wav, mp3
FORMAT = "pcm" # Supported audio formats: pcm, wav, mp3
def __init__(self, config: dict, delete_audio_file: bool = True):
super().__init__()
@ -28,103 +28,107 @@ class ASRProvider(ASRProviderBase):
self.output_dir = config.get("output_dir")
self.delete_audio_file = delete_audio_file
# 确保输出目录存在
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""Convert speech data to text"""
if not opus_data:
logger.bind(tag=TAG).warning("音频数据为空!")
logger.bind(tag=TAG).warning("Audio data is empty!")
return None, None
file_path = None
try:
# 检查配置是否已设置
# Check if configuration is set
if not self.secret_id or not self.secret_key:
logger.bind(tag=TAG).error("腾讯云语音识别配置未设置,无法进行识别")
logger.bind(tag=TAG).error("Tencent Cloud Speech Recognition configuration not set, cannot perform recognition")
return None, file_path
# 将Opus音频数据解码为PCM
# Decode Opus audio data to PCM
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件
# Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
self.save_audio_to_file(pcm_data, session_id)
# 将音频数据转换为Base64编码
# Convert audio data to Base64 encoding
base64_audio = base64.b64encode(combined_pcm_data).decode("utf-8")
# 构建请求体
# Build request body
request_body = self._build_request_body(base64_audio)
# 获取认证头
# Get auth headers
timestamp, authorization = self._get_auth_headers(request_body)
# 发送请求
# Send request
start_time = time.time()
result = self._send_request(request_body, timestamp, authorization)
if result:
logger.bind(tag=TAG).debug(
f"腾讯云语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}"
f"Tencent Cloud speech recognition time: {time.time() - start_time:.3f}s | Result: {result}"
)
return result, file_path
except Exception as e:
logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True)
logger.bind(tag=TAG).error(f"Error occurred while processing audio! {e}", exc_info=True)
return None, file_path
def _build_request_body(self, base64_audio: str) -> str:
"""构建请求体"""
def _build_request_body(self, base64_audio: str) -> str:
"""Build request body"""
request_map = {
"ProjectId": 0,
"SubServiceType": 2, # 一句话识别
"EngSerViceType": "16k_zh", # 中文普通话通用
"SourceType": 1, # 音频数据来源为语音文件
"VoiceFormat": self.FORMAT, # 音频格式
"Data": base64_audio, # Base64编码的音频数据
"DataLen": len(base64_audio), # 数据长度
"SubServiceType": 2, # Sentence recognition
"EngSerViceType": "16k_zh", # Mandarin Chinese general
"SourceType": 1, # Audio data source is voice file
"VoiceFormat": self.FORMAT, # Audio format
"Data": base64_audio, # Base64 encoded audio data
"DataLen": len(base64_audio), # Data length
}
return json.dumps(request_map)
def _get_auth_headers(self, request_body: str) -> Tuple[str, str]:
"""获取认证头"""
"""Get auth headers"""
try:
# 获取当前UTC时间戳
# Get current UTC timestamp
now = datetime.now(timezone.utc)
timestamp = str(int(now.timestamp()))
date = now.strftime("%Y-%m-%d")
# 服务名称必须是 "asr"
# Service name must be "asr"
service = "asr"
# 拼接凭证范围
# Splicing credential scope
credential_scope = f"{date}/{service}/tc3_request"
# 使用TC3-HMAC-SHA256签名方法
# Use TC3-HMAC-SHA256 signature method
algorithm = "TC3-HMAC-SHA256"
# 构建规范请求字符串
# Build canonical request string
http_request_method = "POST"
canonical_uri = "/"
canonical_query_string = ""
# 注意:头部信息需要按照ASCII升序排列,且key和value都转为小写
# 必须包含content-type和host头部
# Note: Header information needs to be arranged in ASCII ascending order, and keys and values are converted to lowercase
# Must include content-type and host headers
content_type = "application/json; charset=utf-8"
host = "asr.tencentcloudapi.com"
action = "SentenceRecognition" # 接口名称
action = "SentenceRecognition" # Interface name
# 构建规范头部信息,注意顺序和格式
# Build canonical header information, pay attention to order and format
canonical_headers = (
f"content-type:{content_type.lower()}\n"
+ f"host:{host.lower()}\n"
@ -133,10 +137,10 @@ class ASRProvider(ASRProviderBase):
signed_headers = "content-type;host;x-tc-action"
# 请求体哈希值
# Request body hash value
payload_hash = self._sha256_hex(request_body)
# 构建规范请求字符串
# Build canonical request string
canonical_request = (
f"{http_request_method}\n"
+ f"{canonical_uri}\n"
@ -146,10 +150,10 @@ class ASRProvider(ASRProviderBase):
+ f"{payload_hash}"
)
# 计算规范请求的哈希值
# Calculate hash value of canonical request
hashed_canonical_request = self._sha256_hex(canonical_request)
# 构建待签名字符串
# Build string to sign
string_to_sign = (
f"{algorithm}\n"
+ f"{timestamp}\n"
@ -157,17 +161,17 @@ class ASRProvider(ASRProviderBase):
+ f"{hashed_canonical_request}"
)
# 计算签名密钥
# Calculate signature key
secret_date = self._hmac_sha256(f"TC3{self.secret_key}", date)
secret_service = self._hmac_sha256(secret_date, service)
secret_signing = self._hmac_sha256(secret_service, "tc3_request")
# 计算签名
# Calculate signature
signature = self._bytes_to_hex(
self._hmac_sha256(secret_signing, string_to_sign)
)
# 构建授权头
# Build authorization header
authorization = (
f"{algorithm} "
+ f"Credential={self.secret_id}/{credential_scope}, "
@ -178,13 +182,13 @@ class ASRProvider(ASRProviderBase):
return timestamp, authorization
except Exception as e:
logger.bind(tag=TAG).error(f"生成认证头失败: {e}", exc_info=True)
raise RuntimeError(f"生成认证头失败: {e}")
logger.bind(tag=TAG).error(f"Failed to generate auth header: {e}", exc_info=True)
raise RuntimeError(f"Failed to generate auth header: {e}")
def _send_request(
self, request_body: str, timestamp: str, authorization: str
) -> Optional[str]:
"""发送请求到腾讯云API"""
"""Send request to Tencent Cloud API"""
headers = {
"Content-Type": "application/json; charset=utf-8",
"Host": "asr.tencentcloudapi.com",
@ -199,40 +203,40 @@ class ASRProvider(ASRProviderBase):
response = requests.post(self.API_URL, headers=headers, data=request_body)
if not response.ok:
raise IOError(f"请求失败: {response.status_code} {response.reason}")
raise IOError(f"Request failed: {response.status_code} {response.reason}")
response_json = response.json()
# 检查是否有错误
# Check for errors
if "Response" in response_json and "Error" in response_json["Response"]:
error = response_json["Response"]["Error"]
error_code = error["Code"]
error_message = error["Message"]
raise IOError(f"API返回错误: {error_code}: {error_message}")
raise IOError(f"API returned error: {error_code}: {error_message}")
# 提取识别结果
# Extract recognition result
if "Response" in response_json and "Result" in response_json["Response"]:
return response_json["Response"]["Result"]
else:
logger.bind(tag=TAG).warning(f"响应中没有识别结果: {response_json}")
logger.bind(tag=TAG).warning(f"No recognition result in response: {response_json}")
return ""
except Exception as e:
logger.bind(tag=TAG).error(f"发送请求失败: {e}", exc_info=True)
logger.bind(tag=TAG).error(f"Failed to send request: {e}", exc_info=True)
return None
def _sha256_hex(self, data: str) -> str:
"""计算字符串的SHA256哈希值"""
"""Calculate SHA256 hash of a string"""
digest = hashlib.sha256(data.encode("utf-8")).digest()
return self._bytes_to_hex(digest)
def _hmac_sha256(self, key, data: str) -> bytes:
"""计算HMAC-SHA256"""
"""Calculate HMAC-SHA256"""
if isinstance(key, str):
key = key.encode("utf-8")
return hmac.new(key, data.encode("utf-8"), hashlib.sha256).digest()
def _bytes_to_hex(self, bytes_data: bytes) -> str:
"""字节数组转十六进制字符串"""
"""Convert byte array to hexadecimal string"""
return "".join(f"{b:02x}" for b in bytes_data)

View file

@ -4,7 +4,7 @@ from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
EMOTION_EMOJI_MAP = {
EMOTION__MAP = {
"HAPPY": "🙂",
"SAD": "😔",
"ANGRY": "😡",
@ -14,7 +14,7 @@ EMOTION_EMOJI_MAP = {
"SURPRISED": "😲",
"EMO_UNKNOWN": "😶", # 未知情绪默认用中性表情
}
# EVENT_EMOJI_MAP = {
# EVENT__MAP = {
# "<|BGM|>": "🎼",
# "<|Speech|>": "",
# "<|Applause|>": "👏",
@ -33,15 +33,15 @@ def lang_tag_filter(text: str) -> dict | str:
text: ASR 识别的原始文本,可能包含多种标签
Returns:
dict: {"language": "zh", "emotion": "SAD", "emoji": "😔", "content": "你好"} 如果有标签
dict: {"language": "zh", "emotion": "SAD", "": "😔", "content": "你好"} 如果有标签
str: 纯文本,如果没有标签
Examples:
FunASR 输出格式:<|语种|><|情绪|><|事件|><|其他选项|>原文
>>> lang_tag_filter("<|zh|><|SAD|><|Speech|><|withitn|>你好啊,测试测试。")
{"language": "zh", "emotion": "SAD", "emoji": "😔", "content": "你好啊,测试测试。"}
{"language": "zh", "emotion": "SAD", "": "😔", "content": "你好啊,测试测试。"}
>>> lang_tag_filter("<|en|><|HAPPY|><|Speech|><|withitn|>Hello hello.")
{"language": "en", "emotion": "HAPPY", "emoji": "🙂", "content": "Hello hello."}
{"language": "en", "emotion": "HAPPY", "": "🙂", "content": "Hello hello."}
>>> lang_tag_filter("plain text")
"plain text"
"""
@ -68,12 +68,12 @@ def lang_tag_filter(text: str) -> dict | str:
# "event": event,
}
# 添加 emoji 映射
if emotion in EMOTION_EMOJI_MAP:
result["emotion"] = EMOTION_EMOJI_MAP[emotion]
# 添加 映射
if emotion in EMOTION__MAP:
result["emotion"] = EMOTION__MAP[emotion]
# 事件标签暂不使用
# if event in EVENT_EMOJI_MAP:
# result["event"] = EVENT_EMOJI_MAP[event]
# if event in EVENT__MAP:
# result["event"] = EVENT__MAP[event]
return result

View file

@ -18,66 +18,66 @@ class ASRProvider(ASRProviderBase):
self.output_dir = config.get("output_dir", "tmp/")
self.delete_audio_file = delete_audio_file
# 初始化VOSK模型
# Initialize VOSK model
self.model = None
self.recognizer = None
self._load_model()
# 确保输出目录存在
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
def _load_model(self):
"""加载VOSK模型"""
"""Load VOSK model"""
try:
if not os.path.exists(self.model_path):
raise FileNotFoundError(f"VOSK模型路径不存在: {self.model_path}")
raise FileNotFoundError(f"VOSK model path does not exist: {self.model_path}")
logger.bind(tag=TAG).info(f"正在加载VOSK模型: {self.model_path}")
logger.bind(tag=TAG).info(f"Loading VOSK model: {self.model_path}")
self.model = vosk.Model(self.model_path)
# 初始化VOSK识别器(采样率必须为16kHz)
# Initialize VOSK recognizer (sample rate must be 16kHz)
self.recognizer = vosk.KaldiRecognizer(self.model, 16000)
logger.bind(tag=TAG).info("VOSK模型加载成功")
logger.bind(tag=TAG).info("VOSK model loaded successfully")
except Exception as e:
logger.bind(tag=TAG).error(f"加载VOSK模型失败: {e}")
logger.bind(tag=TAG).error(f"Failed to load VOSK model: {e}")
raise
async def speech_to_text(
self, audio_data: List[bytes], session_id: str, audio_format: str = "opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
"""Convert speech data to text"""
file_path = None
try:
# 检查模型是否加载成功
# Check if model loaded successfully
if not self.model:
logger.bind(tag=TAG).error("VOSK模型未加载,无法进行识别")
logger.bind(tag=TAG).error("VOSK model not loaded, cannot perform recognition")
return "", None
# 解码音频(如果原始格式是Opus)
# Decode audio (if original format is Opus)
if audio_format == "pcm":
pcm_data = audio_data
else:
pcm_data = self.decode_opus(audio_data)
if not pcm_data:
logger.bind(tag=TAG).warning("解码后的PCM数据为空,无法进行识别")
logger.bind(tag=TAG).warning("Decoded PCM data is empty, cannot perform recognition")
return "", None
# 合并PCM数据
# Combine PCM data
combined_pcm_data = b"".join(pcm_data)
if len(combined_pcm_data) == 0:
logger.bind(tag=TAG).warning("合并后的PCM数据为空")
logger.bind(tag=TAG).warning("Combined PCM data is empty")
return "", None
# 判断是否保存为WAV文件
# Determine whether to save as WAV file
if not self.delete_audio_file:
file_path = self.save_audio_to_file(pcm_data, session_id)
file_path = self.save_audio_background(pcm_data, session_id)
start_time = time.time()
# 进行识别(VOSK推荐每次送入2000字节的数据)
# Perform recognition (VOSK recommends sending 2000 bytes of data each time)
chunk_size = 2000
text_result = ""
@ -89,26 +89,26 @@ class ASRProvider(ASRProviderBase):
if text:
text_result += text + " "
# 获取最终结果
# Get final result
final_result = json.loads(self.recognizer.FinalResult())
final_text = final_result.get('text', '')
if final_text:
text_result += final_text
logger.bind(tag=TAG).debug(
f"VOSK语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text_result.strip()}"
f"VOSK speech recognition time: {time.time() - start_time:.3f}s | Result: {text_result.strip()}"
)
return text_result.strip(), file_path
except Exception as e:
logger.bind(tag=TAG).error(f"VOSK语音识别失败: {e}")
logger.bind(tag=TAG).error(f"VOSK speech recognition failed: {e}")
return "", None
finally:
# 文件清理逻辑
# File cleanup logic
if self.delete_audio_file and file_path and os.path.exists(file_path):
try:
os.remove(file_path)
logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
logger.bind(tag=TAG).debug(f"Removed temporary audio file: {file_path}")
except Exception as e:
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
logger.bind(tag=TAG).error(f"Failed to delete file: {file_path} | Error: {e}")

View file

@ -18,10 +18,10 @@ from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
# 帧状态常量
STATUS_FIRST_FRAME = 0 # 第一帧的标识
STATUS_CONTINUE_FRAME = 1 # 中间帧标识
STATUS_LAST_FRAME = 2 # 最后一帧的标识
# Frame status constants
STATUS_FIRST_FRAME = 0 # First frame identifier
STATUS_CONTINUE_FRAME = 1 # Intermediate frame identifier
STATUS_LAST_FRAME = 2 # Last frame identifier
class ASRProvider(ASRProviderBase):
@ -36,15 +36,17 @@ class ASRProvider(ASRProviderBase):
self.is_processing = False
self.server_ready = False
# 讯飞配置
self.server_ready = False
# Xunfei config
self.app_id = config.get("app_id")
self.api_key = config.get("api_key")
self.api_secret = config.get("api_secret")
if not all([self.app_id, self.api_key, self.api_secret]):
raise ValueError("必须提供app_id、api_key和api_secret")
raise ValueError("Must provide app_id, api_key and api_secret")
# 识别参数
# Recognition parameters
self.iat_params = {
"domain": config.get("domain", "slm"),
"language": config.get("language", "zh_cn"),
@ -56,18 +58,22 @@ class ASRProvider(ASRProviderBase):
self.delete_audio_file = delete_audio_file
def create_url(self) -> str:
"""生成认证URL"""
"""Generate Auth URL"""
url = "ws://iat.cn-huabei-1.xf-yun.com/v1"
# 生成RFC1123格式的时间戳
# Generate RFC1123 format timestamp
now = datetime.now()
date = format_date_time(mktime(now.timetuple()))
# 拼接字符串
date = format_date_time(mktime(now.timetuple()))
# Concatenate string
signature_origin = "host: " + "iat.cn-huabei-1.xf-yun.com" + "\n"
signature_origin += "date: " + date + "\n"
signature_origin += "GET " + "/v1 " + "HTTP/1.1"
# 进行hmac-sha256进行加密
signature_origin += "GET " + "/v1 " + "HTTP/1.1"
# Encrypt with hmac-sha256
signature_sha = hmac.new(
self.api_secret.encode("utf-8"),
signature_origin.encode("utf-8"),
@ -83,14 +89,18 @@ class ASRProvider(ASRProviderBase):
encoding="utf-8"
)
# 将请求的鉴权参数组合为字典
)
# Combine auth parameters into dictionary
v = {
"authorization": authorization,
"date": date,
"host": "iat.cn-huabei-1.xf-yun.com",
}
# 拼接鉴权参数,生成url
}
# Concatenate auth parameters to generate URL
url = url + "?" + urlencode(v)
return url
@ -98,41 +108,43 @@ class ASRProvider(ASRProviderBase):
await super().open_audio_channels(conn)
async def receive_audio(self, conn, audio, audio_have_voice):
# 先调用父类方法处理基础逻辑
# Call parent method to handle basic logic
await super().receive_audio(conn, audio, audio_have_voice)
# 存储音频数据用于声纹识别
# Store audio data for voiceprint recognition
if not hasattr(conn, "asr_audio_for_voiceprint"):
conn.asr_audio_for_voiceprint = []
conn.asr_audio_for_voiceprint.append(audio)
# 如果本次有声音,且之前没有建立连接
# If voice detected, and connection not established
if audio_have_voice and self.asr_ws is None and not self.is_processing:
try:
await self._start_recognition(conn)
except Exception as e:
logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to establish ASR connection: {str(e)}")
await self._cleanup()
return
# 发送当前音频数据
return
# Send current audio data
if self.asr_ws and self.is_processing and self.server_ready:
try:
pcm_frame = self.decoder.decode(audio, 960)
await self._send_audio_frame(pcm_frame, STATUS_CONTINUE_FRAME)
except Exception as e:
logger.bind(tag=TAG).warning(f"发送音频数据时发生错误: {e}")
logger.bind(tag=TAG).warning(f"Error sending audio data: {e}")
await self._cleanup()
async def _start_recognition(self, conn):
"""开始识别会话"""
"""Start recognition session"""
try:
self.is_processing = True
# 建立WebSocket连接
# Establish WebSocket connection
ws_url = self.create_url()
logger.bind(tag=TAG).info(f"正在连接ASR服务: {ws_url[:50]}...")
logger.bind(tag=TAG).info(f"Connecting to ASR service: {ws_url[:50]}...")
# 如果为手动模式,设置超时时长为一分钟
# If manual mode, set timeout to 1 minute
if conn.client_listen_mode == "manual":
self.iat_params["eos"] = 60000
@ -144,11 +156,11 @@ class ASRProvider(ASRProviderBase):
close_timeout=10,
)
logger.bind(tag=TAG).info("ASR WebSocket连接已建立")
logger.bind(tag=TAG).info("ASR WebSocket connection established")
self.server_ready = False
self.forward_task = asyncio.create_task(self._forward_results(conn))
# 发送首帧音频
# Send first audio frame
if conn.asr_audio and len(conn.asr_audio) > 0:
first_audio = conn.asr_audio[-1] if conn.asr_audio else b""
pcm_frame = (
@ -156,21 +168,21 @@ class ASRProvider(ASRProviderBase):
)
await self._send_audio_frame(pcm_frame, STATUS_FIRST_FRAME)
self.server_ready = True
logger.bind(tag=TAG).info("已发送首帧,开始识别")
logger.bind(tag=TAG).info("First frame sent, starting recognition")
# 发送缓存的音频数据
# Send cached audio data
for cached_audio in conn.asr_audio[-10:]:
try:
pcm_frame = self.decoder.decode(cached_audio, 960)
await self._send_audio_frame(pcm_frame, STATUS_CONTINUE_FRAME)
except Exception as e:
logger.bind(tag=TAG).info(f"发送缓存音频数据时发生错误: {e}")
logger.bind(tag=TAG).info(f"Error sending cached audio data: {e}")
break
except Exception as e:
logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to establish ASR connection: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
if self.asr_ws:
await self.asr_ws.close()
self.asr_ws = None
@ -178,7 +190,7 @@ class ASRProvider(ASRProviderBase):
raise
async def _send_audio_frame(self, audio_data: bytes, status: int):
"""发送音频帧"""
"""Send audio frame"""
if not self.asr_ws:
return
@ -195,13 +207,13 @@ class ASRProvider(ASRProviderBase):
await self.asr_ws.send(json.dumps(frame_data, ensure_ascii=False))
async def _forward_results(self, conn):
"""转发识别结果"""
"""Forward recognition results"""
try:
while not conn.stop_event.is_set():
try:
response = await asyncio.wait_for(self.asr_ws.recv(), timeout=60)
result = json.loads(response)
logger.bind(tag=TAG).debug(f"收到ASR结果: {result}")
logger.bind(tag=TAG).debug(f"Received ASR result: {result}")
header = result.get("header", {})
payload = result.get("payload", {})
@ -210,20 +222,20 @@ class ASRProvider(ASRProviderBase):
if code != 0:
logger.bind(tag=TAG).error(
f"识别错误,错误码: {code}, 消息: {header.get('message', '')}"
f"Recognition error, code: {code}, message: {header.get('message', '')}"
)
if code in [10114, 10160]: # 连接问题
if code in [10114, 10160]: # Connection issue
break
continue
# 处理识别结果
# Process recognition result
if payload and "result" in payload:
text_data = payload["result"]["text"]
if text_data:
# 解码base64文本
# Decode base64 text
decoded_text = base64.b64decode(text_data).decode("utf-8")
text_json = json.loads(decoded_text)
# 提取文本内容
# Extract text content
text_ws = text_json.get("ws", [])
for i in text_ws:
for j in i.get("cw", []):
@ -234,36 +246,36 @@ class ASRProvider(ASRProviderBase):
if conn.client_listen_mode == "manual":
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
if len(audio_data) > 0:
logger.bind(tag=TAG).debug("收到最终识别结果,触发处理")
logger.bind(tag=TAG).debug("Received final result, trigger processing")
await self.handle_voice_stop(conn, audio_data)
# 清理音频缓存
# Clear audio cache
conn.asr_audio.clear()
conn.reset_vad_states()
break
except asyncio.TimeoutError:
logger.bind(tag=TAG).error("接收结果超时")
logger.bind(tag=TAG).error("Receive result timeout")
break
except websockets.ConnectionClosed:
logger.bind(tag=TAG).info("ASR服务连接已关闭")
logger.bind(tag=TAG).info("ASR service connection closed")
self.is_processing = False
break
except Exception as e:
logger.bind(tag=TAG).error(f"处理ASR结果时发生错误: {str(e)}")
logger.bind(tag=TAG).error(f"Error processing ASR result: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
self.is_processing = False
break
except Exception as e:
logger.bind(tag=TAG).error(f"ASR结果转发任务发生错误: {str(e)}")
logger.bind(tag=TAG).error(f"ASR result forwarding task error: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
finally:
# 清理连接资源
# Clean up connection resources
await self._cleanup()
# 清理连接的音频缓存
# Clean up connected audio cache
if conn:
if hasattr(conn, "asr_audio_for_voiceprint"):
conn.asr_audio_for_voiceprint = []
@ -271,24 +283,24 @@ class ASRProvider(ASRProviderBase):
conn.asr_audio = []
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
"""处理语音停止,发送最后一帧并处理识别结果"""
"""Handle voice stop, send last frame and process recognition results"""
try:
# 先发送最后一帧表示音频结束
# Send last frame to indicate audio end
if self.asr_ws and self.is_processing:
try:
await self._send_audio_frame(b"", STATUS_LAST_FRAME)
logger.bind(tag=TAG).debug(f"已发送停止请求")
logger.bind(tag=TAG).debug(f"Stop request sent")
await asyncio.sleep(0.25)
except Exception as e:
logger.bind(tag=TAG).error(f"发送停止请求失败: {e}")
logger.bind(tag=TAG).error(f"Failed to send stop request: {e}")
await super().handle_voice_stop(conn, asr_audio_task)
except Exception as e:
logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
logger.bind(tag=TAG).error(f"Failed to handle voice stop: {e}")
import traceback
logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}")
logger.bind(tag=TAG).debug(f"Exception details: {traceback.format_exc()}")
def stop_ws_connection(self):
if self.asr_ws:
@ -297,51 +309,51 @@ class ASRProvider(ASRProviderBase):
self.is_processing = False
async def _send_stop_request(self):
"""发送停止识别请求(不关闭连接)"""
"""Send stop recognition request (without closing connection)"""
if self.asr_ws:
try:
# 先停止音频发送
# Stop sending audio first
self.is_processing = False
await self._send_audio_frame(b"", STATUS_LAST_FRAME)
logger.bind(tag=TAG).debug("已发送停止请求")
logger.bind(tag=TAG).debug("Stop request sent")
except Exception as e:
logger.bind(tag=TAG).error(f"发送停止请求失败: {e}")
logger.bind(tag=TAG).error(f"Failed to send stop request: {e}")
async def _cleanup(self):
"""清理资源(关闭连接)"""
"""Cleanup resources (close connection)"""
logger.bind(tag=TAG).debug(
f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}"
f"Starting ASR session cleanup | Current Status: processing={self.is_processing}, server_ready={self.server_ready}"
)
# 状态重置
# Reset status
self.is_processing = False
self.server_ready = False
logger.bind(tag=TAG).debug("ASR状态已重置")
logger.bind(tag=TAG).debug("ASR status reset")
# 关闭连接
# Close connection
if self.asr_ws:
try:
logger.bind(tag=TAG).debug("正在关闭WebSocket连接")
logger.bind(tag=TAG).debug("Closing WebSocket connection")
await asyncio.wait_for(self.asr_ws.close(), timeout=2.0)
logger.bind(tag=TAG).debug("WebSocket连接已关闭")
logger.bind(tag=TAG).debug("WebSocket connection closed")
except Exception as e:
logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}")
logger.bind(tag=TAG).error(f"Failed to close WebSocket connection: {e}")
finally:
self.asr_ws = None
# 清理任务引用
# Clean up task reference
self.forward_task = None
logger.bind(tag=TAG).debug("ASR会话清理完成")
logger.bind(tag=TAG).debug("ASR session cleanup completed")
async def speech_to_text(self, opus_data, session_id, audio_format):
"""获取识别结果"""
"""Get recognition result"""
result = self.text
self.text = ""
return result, None
async def close(self):
"""资源清理方法"""
"""Resource cleanup method"""
if self.asr_ws:
await self.asr_ws.close()
self.asr_ws = None
@ -354,16 +366,16 @@ class ASRProvider(ASRProviderBase):
self.forward_task = None
self.is_processing = False
# 显式释放decoder资源
# Explicitly release decoder resources
if hasattr(self, 'decoder') and self.decoder is not None:
try:
del self.decoder
self.decoder = None
logger.bind(tag=TAG).debug("Xunfei decoder resources released")
except Exception as e:
logger.bind(tag=TAG).debug(f"释放Xunfei decoder资源时出错: {e}")
logger.bind(tag=TAG).debug(f"Error releasing Xunfei decoder resources: {e}")
# 清理所有连接的音频缓冲区
# Clean up all connected audio buffers
if hasattr(self, "_connections"):
for conn in self._connections.values():
if hasattr(conn, "asr_audio_for_voiceprint"):

View file

@ -12,22 +12,21 @@ class IntentProviderBase(ABC):
def set_llm(self, llm):
self.llm = llm
# 获取模型名称和类型信息
# Get model name and type info
model_name = getattr(llm, "model_name", str(llm.__class__.__name__))
# 记录更详细的日志
logger.bind(tag=TAG).info(f"意图识别设置LLM: {model_name}")
# Log more detailed info
logger.bind(tag=TAG).info(f"Intent recognition LLM set to: {model_name}")
@abstractmethod
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
"""
检测用户最后一句话的意图
Detect intent of the user's last sentence
Args:
dialogue_history: 对话历史记录列表,每条记录包含role和content
dialogue_history: List of dialogue history records, each containing role and content
Returns:
返回识别出的意图,格式为:
- "继续聊天"
- "结束聊天"
- "播放音乐 歌名" 或 "随机播放音乐"
- "查询天气 地点名" 或 "查询天气 [当前位置]"
Identified intent string, format:
- "continue_chat"
- "handle_exit_intent"
...
"""
pass

View file

@ -9,12 +9,12 @@ logger = setup_logging()
class IntentProvider(IntentProviderBase):
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
"""
默认的意图识别实现,始终返回继续聊天
Default intent recognition implementation, always returns 'continue chat'.
Args:
dialogue_history: 对话历史记录列表
text: 本次对话记录
dialogue_history: List of dialogue history records
text: Current dialogue text
Returns:
固定返回"继续聊天"
Always returns 'continue chat'
"""
logger.bind(tag=TAG).debug(
"Using functionCallProvider, always returning continue chat"

View file

@ -16,108 +16,73 @@ class IntentProvider(IntentProviderBase):
super().__init__(config)
self.llm = None
self.promot = ""
# 导入全局缓存管理器
# Import global cache manager
from core.utils.cache.manager import cache_manager, CacheType
self.cache_manager = cache_manager
self.CacheType = CacheType
self.history_count = 4 # 默认使用最近4条对话记录
self.history_count = 4 # Default to using the last 4 dialogue records
def get_intent_system_prompt(self, functions_list: str) -> str:
def get_intent_system_prompt(self, functions_list: list) -> str:
"""
根据配置的意图选项和可用函数动态生成系统提示词
Args:
functions: 可用的函数列表,JSON格式字符串
Returns:
格式化后的系统提示词
Dynamically generate a concise English system prompt for intent recognition.
"""
# 构建函数说明部分
functions_desc = "可用的函数列表:\n"
# Build tool description section
functions_desc = "AVAILABLE TOOLS:\n"
for func in functions_list:
func_info = func.get("function", {})
name = func_info.get("name", "")
desc = func_info.get("description", "")
params = func_info.get("parameters", {})
functions_desc += f"\n函数名: {name}\n"
functions_desc += f"描述: {desc}\n"
functions_desc += f"\n- {name}: {desc}\n"
if params:
functions_desc += "参数:\n"
for param_name, param_info in params.get("properties", {}).items():
param_desc = param_info.get("description", "")
param_type = param_info.get("type", "")
functions_desc += f"- {param_name} ({param_type}): {param_desc}\n"
functions_desc += "---\n"
props = params.get("properties", {})
for p_name, p_info in props.items():
functions_desc += f" * {p_name} ({p_info.get('type')}): {p_info.get('description')}\n"
prompt = (
"【严格格式要求】你必须只能返回JSON格式,绝对不能返回任何自然语言!\n\n"
"你是一个意图识别助手。请分析用户的最后一句话,判断用户意图并调用相应的函数。\n\n"
"【重要规则】以下类型的查询请直接返回result_for_context,无需调用函数:\n"
"- 询问当前时间(如:现在几点、当前时间、查询时间等)\n"
"- 询问今天日期(如:今天几号、今天星期几、今天是什么日期等)\n"
"- 询问今天农历(如:今天农历几号、今天什么节气等)\n"
"- 询问所在城市(如:我现在在哪里、你知道我在哪个城市吗等)"
"系统会根据上下文信息直接构建回答。\n\n"
"- 如果用户使用疑问词(如'怎么'、'为什么'、'如何')询问退出相关的问题(例如'怎么退出了?'),注意这不是让你退出,请返回 {'function_call': {'name': 'continue_chat'}\n"
"- 仅当用户明确使用'退出系统'、'结束对话'、'我不想和你说话了'等指令时,才触发 handle_exit_intent\n\n"
"You are a strict code interpreter. Your ONLY job is to route user input to a tool.\n"
"OUTPUT valid JSON ONLY. NO explanation.\n\n"
"TOOLS:\n"
f"{functions_desc}\n"
"处理步骤:\n"
"1. 分析用户输入,确定用户意图\n"
"2. 检查是否为上述基础信息查询(时间、日期等),如是则返回result_for_context\n"
"3. 从可用函数列表中选择最匹配的函数\n"
"4. 如果找到匹配的函数,生成对应的function_call 格式\n"
'5. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n\n'
"返回格式要求:\n"
"1. 必须返回纯JSON格式,不要包含任何其他文字\n"
"2. 必须包含function_call字段\n"
"3. function_call必须包含name字段\n"
"4. 如果函数需要参数,必须包含arguments字段\n\n"
"示例:\n"
"```\n"
"用户: 现在几点了?\n"
'返回: {"function_call": {"name": "result_for_context"}}\n'
"```\n"
"```\n"
"用户: 当前电池电量是多少?\n"
'返回: {"function_call": {"name": "get_battery_level", "arguments": {"response_success": "当前电池电量为{value}%", "response_failure": "无法获取Battery的当前电量百分比"}}}\n'
"```\n"
"```\n"
"用户: 当前屏幕亮度是多少?\n"
'返回: {"function_call": {"name": "self_screen_get_brightness"}}\n'
"```\n"
"```\n"
"用户: 设置屏幕亮度为50%\n"
'返回: {"function_call": {"name": "self_screen_set_brightness", "arguments": {"brightness": 50}}}\n'
"```\n"
"```\n"
"用户: 我想结束对话\n"
'返回: {"function_call": {"name": "handle_exit_intent", "arguments": {"say_goodbye": "goodbye"}}}\n'
"```\n"
"```\n"
"用户: 你好啊\n"
'返回: {"function_call": {"name": "continue_chat"}}\n'
"```\n\n"
"注意:\n"
"1. 只返回JSON格式,不要包含任何其他文字\n"
'2. 优先检查用户查询是否为基础信息(时间、日期等),如是则返回{"function_call": {"name": "result_for_context"}},不需要arguments参数\n'
'3. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n'
"4. 确保返回的JSON格式正确,包含所有必要的字段\n"
"5. result_for_context不需要任何参数,系统会自动从上下文获取信息\n"
"特殊说明:\n"
"- 当用户单次输入包含多个指令时(如'打开灯并且调高音量')\n"
"- 请返回多个function_call组成的JSON数组\n"
"- 示例:{'function_calls': [{name:'light_on'}, {name:'volume_up'}]}\n\n"
"【最终警告】绝对禁止输出任何自然语言、表情符号或解释文字!只能输出有效JSON格式!违反此规则将导致系统错误!"
"MAPPING RULES:\n"
"1. WEATHER -> 'get_weather'\n"
"2. LOCATION -> 'get_location'\n"
"3. TIME/DATE -> {'function_call': {'name': 'result_for_context'}}\n"
"4. CHANGE HARDWARE (Volume, Brightness, Theme) -> 'self_*' tool\n"
"5. GET HARDWARE STATUS (Battery, Volume, Wifi, etc.) -> 'self_get_device_status'\n"
"6. TAKE PHOTO/VISION -> 'self_camera_take_photo'\n"
"7. GENERAL KNOWLEDGE (e.g. Science, History) -> {'function_call': {'name': 'continue_chat'}}\n"
"8. OTHER -> {'function_call': {'name': 'continue_chat'}}\n\n"
"EXAMPLES:\n"
"User: Hello\n"
"{\"function_call\": {\"name\": \"continue_chat\"}}\n\n"
"User: What is your battery level?\n"
"{\"function_call\": {\"name\": \"self_get_device_status\"}}\n\n"
"User: Is the wifi connected?\n"
"{\"function_call\": {\"name\": \"self_get_device_status\"}}\n\n"
"User: Weather in Tokyo?\n"
"{\"function_call\": {\"name\": \"get_weather\", \"arguments\": {\"location\": \"Tokyo\"}}}\n\n"
"User: Volume up\n"
"{\"function_call\": {\"name\": \"self_audio_speaker_set_volume\", \"arguments\": {\"volume\": 80}}}\n\n"
"User: Set brightness to 50%\n"
"{\"function_call\": {\"name\": \"self_screen_set_brightness\", \"arguments\": {\"brightness\": 50}}}\n\n"
"User: Take a photo of this\n"
"{\"function_call\": {\"name\": \"self_camera_take_photo\", \"arguments\": {\"question\": \"Describe this photo\"}}}\n\n"
"User: Who won the game?\n"
"{\"function_call\": {\"name\": \"continue_chat\"}}\n"
"User: Okay, thanks\n"
"{\"function_call\": {\"name\": \"continue_chat\"}}\n"
"User: Where are we?\n"
"{\"function_call\": {\"name\": \"get_location\"}}\n"
)
return prompt
def replyResult(self, text: str, original_text: str):
llm_result = self.llm.response_no_stream(
system_prompt=text,
user_prompt="请根据以上内容,像人类一样说话的口吻回复用户,要求简洁,请直接返回结果。用户现在说:"
user_prompt="Based on the above, reply to the user in a human-like tone. Be concise and return the result directly. The user says: "
+ original_text,
)
return llm_result
@ -128,22 +93,22 @@ class IntentProvider(IntentProviderBase):
if conn.func_handler is None:
return '{"function_call": {"name": "continue_chat"}}'
# 记录整体开始时间
# Record total start time
total_start_time = time.time()
# 打印使用的模型信息
# Print model info
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
logger.bind(tag=TAG).debug(f"使用意图识别模型: {model_info}")
logger.bind(tag=TAG).debug(f"Using intent model: {model_info}")
# 计算缓存键
# Calculate cache key
cache_key = hashlib.md5((conn.device_id + text).encode()).hexdigest()
# 检查缓存
# Check cache
cached_intent = self.cache_manager.get(self.CacheType.INTENT, cache_key)
if cached_intent is not None:
cache_time = time.time() - total_start_time
logger.bind(tag=TAG).debug(
f"使用缓存的意图: {cache_key} -> {cached_intent}, 耗时: {cache_time:.4f}秒"
f"Using cached intent: {cache_key} -> {cached_intent}, Time: {cache_time:.4f}s"
)
return cached_intent
@ -168,17 +133,17 @@ class IntentProvider(IntentProviderBase):
else:
devices = []
if len(devices) > 0:
hass_prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n"
hass_prompt = "\nHere is my list of smart devices (location, device name, entity_id), which can be controlled via Home Assistant\n"
for device in devices:
hass_prompt += device + "\n"
prompt_music += hass_prompt
logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
# 构建用户对话历史的提示
# Build user dialogue history prompt
msgStr = ""
# 获取最近的对话历史
# Get recent dialogue history
start_idx = max(0, len(dialogue_history) - self.history_count)
for i in range(start_idx, len(dialogue_history)):
msgStr += f"{dialogue_history[i].role}: {dialogue_history[i].content}\n"
@ -186,85 +151,120 @@ class IntentProvider(IntentProviderBase):
msgStr += f"User: {text}\n"
user_prompt = f"current dialogue:\n{msgStr}"
# 记录预处理完成时间
# Record preprocessing completion time
preprocess_time = time.time() - total_start_time
logger.bind(tag=TAG).debug(f"意图识别预处理耗时: {preprocess_time:.4f}秒")
logger.bind(tag=TAG).debug(f"Intent preprocessing time: {preprocess_time:.4f}s")
# 使用LLM进行意图识别
# Use LLM for intent recognition
llm_start_time = time.time()
logger.bind(tag=TAG).debug(f"开始LLM意图识别调用, 模型: {model_info}")
logger.bind(tag=TAG).debug(f"Start LLM intent call, model: {model_info}")
intent = self.llm.response_no_stream(
system_prompt=prompt_music, user_prompt=user_prompt
system_prompt=prompt_music, user_prompt=user_prompt, response_format={"type": "json_object"}
)
# 记录LLM调用完成时间
# Record LLM call completion time
llm_time = time.time() - llm_start_time
logger.bind(tag=TAG).debug(
f"外挂的大模型意图识别完成, 模型: {model_info}, 调用耗时: {llm_time:.4f}秒"
f"External LLM intent completed, model: {model_info}, Time: {llm_time:.4f}s"
)
# 记录后处理开始时间
# Record post-processing start time
postprocess_start_time = time.time()
# 清理和解析响应
# Clean and parse response
intent = intent.strip()
# 尝试提取JSON部分
# Try to extract JSON part
match = re.search(r"\{.*\}", intent, re.DOTALL)
if match:
intent = match.group(0)
# 记录总处理时间
# Record total processing time
total_time = time.time() - total_start_time
logger.bind(tag=TAG).debug(
f"【意图识别性能】模型: {model_info}, 总耗时: {total_time:.4f}秒, LLM调用: {llm_time:.4f}秒, 查询: '{text[:20]}...'"
f"[Intent Performance] Model: {model_info}, Total: {total_time:.4f}s, LLM: {llm_time:.4f}s, Query: '{text[:20]}...'"
)
# 尝试解析为JSON
# Try to parse as JSON
try:
intent_data = json.loads(intent)
# 如果包含function_call,则格式化为适合处理的格式
if "function_call" in intent_data:
function_data = intent_data["function_call"]
function_name = function_data.get("name")
function_args = function_data.get("arguments", {})
except json.JSONDecodeError:
# Fallback regex parsing
logger.bind(tag=TAG).warning(f"JSON extract failed for: {intent}, attempting regex fallback")
# Try to find function name
name_match = re.search(r'"name"\s*:\s*"([^"]+)"', intent)
if not name_match:
# Try to find name without quotes if model is very broken
name_match = re.search(r'name\s*:\s*"([^"]+)"', intent)
if name_match:
func_name = name_match.group(1)
args = {}
# Try to find simple arguments
# This is a very basic extraction
args_match = re.search(r'"arguments"\s*:\s*({[^}]+})', intent)
if args_match:
try:
args = json.loads(args_match.group(1))
except:
pass
intent_data = {
"function_call": {
"name": func_name,
"arguments": args
}
}
logger.bind(tag=TAG).info(f"Regex recovery successful: {func_name}")
else:
postprocess_time = time.time() - postprocess_start_time
logger.bind(tag=TAG).error(
f"Cannot parse intent JSON: {intent}, Post-process time: {postprocess_time:.4f}s"
)
return '{"function_call": {"name": "continue_chat"}}'
# 记录识别到的function call
# If it contains function_call, format it for processing
if "function_call" in intent_data:
function_data = intent_data["function_call"]
function_name = function_data.get("name")
function_args = function_data.get("arguments", {})
# Record identified function call
logger.bind(tag=TAG).info(
f"LLM identified intent: {function_name}, args: {function_args}"
)
# Handle different types of intents
if function_name == "result_for_context":
# Handle basic info query, answer directly from context
logger.bind(tag=TAG).info(
f"llm 识别到意图: {function_name}, 参数: {function_args}"
"Detected result_for_context intent, answering directly from context"
)
# 处理不同类型的意图
if function_name == "result_for_context":
# 处理基础信息查询,直接从context构建结果
logger.bind(tag=TAG).info(
"检测到result_for_context意图,将使用上下文信息直接回答"
)
elif function_name == "continue_chat":
# Handle normal chat
# Keep non-tool related messages
clean_history = [
msg
for msg in conn.dialogue.dialogue
if msg.role not in ["tool", "function"]
]
conn.dialogue.dialogue = clean_history
elif function_name == "continue_chat":
# 处理普通对话
# 保留非工具相关的消息
clean_history = [
msg
for msg in conn.dialogue.dialogue
if msg.role not in ["tool", "function"]
]
conn.dialogue.dialogue = clean_history
else:
# Handle function call
logger.bind(tag=TAG).info(f"Detected function call intent: {function_name}")
else:
# 处理函数调用
logger.bind(tag=TAG).info(f"检测到函数调用意图: {function_name}")
# Unified cache processing and return
# Re-dump to ensure valid JSON string is returned even if we repaired it
final_intent_str = json.dumps(intent_data)
# 统一缓存处理和返回
self.cache_manager.set(self.CacheType.INTENT, cache_key, intent)
postprocess_time = time.time() - postprocess_start_time
logger.bind(tag=TAG).debug(f"意图后处理耗时: {postprocess_time:.4f}秒")
return intent
except json.JSONDecodeError:
# 后处理时间
postprocess_time = time.time() - postprocess_start_time
logger.bind(tag=TAG).error(
f"无法解析意图JSON: {intent}, 后处理耗时: {postprocess_time:.4f}秒"
)
# 如果解析失败,默认返回继续聊天意图
return '{"function_call": {"name": "continue_chat"}}'
# Log the entire JSON structure if it's a function call (MCP request)
if "function_call" in intent_data:
logger.bind(tag=TAG).info(f"Intent LLM Response: {final_intent_str}")
self.cache_manager.set(self.CacheType.INTENT, cache_key, final_intent_str)
postprocess_time = time.time() - postprocess_start_time
logger.bind(tag=TAG).debug(f"Intent post-processing time: {postprocess_time:.4f}s")
return final_intent_str

View file

@ -9,12 +9,12 @@ logger = setup_logging()
class IntentProvider(IntentProviderBase):
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
"""
默认的意图识别实现,始终返回继续聊天
Default intent recognition implementation, always returns 'continue chat'
Args:
dialogue_history: 对话历史记录列表
text: 本次对话记录
dialogue_history: List of dialogue history records
text: Current dialogue text
Returns:
固定返回"继续聊天"
Always returns 'continue chat'
"""
logger.bind(tag=TAG).debug(
"Using NoIntentProvider, always returning continue chat"

View file

@ -17,45 +17,45 @@ class LLMProvider(LLMProviderBase):
self.base_url = config.get("base_url")
self.is_No_prompt = config.get("is_no_prompt")
self.memory_id = config.get("ali_memory_id")
self.streaming_chunk_size = config.get("streaming_chunk_size", 3) # 每次流式返回的字符数
self.streaming_chunk_size = config.get("streaming_chunk_size", 3) # Number of characters returned in each stream chunk
check_model_key("AliBLLLM", self.api_key)
def response(self, session_id, dialogue):
try:
# 处理dialogue
# Process dialogue
if self.is_No_prompt:
dialogue.pop(0)
logger.bind(tag=TAG).debug(
f"【阿里百练API服务】处理后的dialogue: {dialogue}"
f"【Aliyun Bailian API Service】Processed dialogue: {dialogue}"
)
# 构造调用参数
# Construct call parameters
call_params = {
"api_key": self.api_key,
"app_id": self.app_id,
"session_id": session_id,
"messages": dialogue,
# 开启SDK原生流式
# Enable SDK native streaming
"stream": True,
}
if self.memory_id != False:
# 百练memory需要prompt参数
# Bailian memory needs prompt parameter
prompt = dialogue[-1].get("content")
call_params["memory_id"] = self.memory_id
call_params["prompt"] = prompt
logger.bind(tag=TAG).debug(
f"【阿里百练API服务】处理后的prompt: {prompt}"
f"【Aliyun Bailian API Service】Processed prompt: {prompt}"
)
# 可选地设置自定义API基地址(若配置为兼容模式URL则忽略)
# Optionally set custom API base address (ignored if configured as compatibility mode URL)
if self.base_url and ("/api/" in self.base_url):
dashscope.base_http_api_url = self.base_url
responses = Application.call(**call_params)
# 流式处理(SDK在stream=True时返回可迭代对象;否则返回单次响应对象)
# Stream processing (SDK returns iterable object when stream=True; otherwise returns single response object)
logger.bind(tag=TAG).debug(
f"【阿里百练API服务】构造参数: {dict(call_params, api_key='***')}"
f"【Aliyun Bailian API Service】Construct parameters: {dict(call_params, api_key='***')}"
)
last_text = ""
@ -63,32 +63,32 @@ class LLMProvider(LLMProviderBase):
for resp in responses:
if resp.status_code != HTTPStatus.OK:
logger.bind(tag=TAG).error(
f"code={resp.status_code}, message={resp.message}, 请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code"
f"code={resp.status_code}, message={resp.message}, please refer to document: https://help.aliyun.com/zh/model-studio/developer-reference/error-code"
)
continue
current_text = getattr(getattr(resp, "output", None), "text", None)
if current_text is None:
continue
# SDK流式为增量覆盖,计算差量输出
# SDK streaming is incremental overwrite, calculate delta output
if len(current_text) >= len(last_text):
delta = current_text[len(last_text):]
else:
# 避免偶发回退
# Avoid occasional rollback
delta = current_text
if delta:
yield delta
last_text = current_text
except TypeError:
# 非流式回落(一次性返回)
# Non-streaming fallback (single return)
if responses.status_code != HTTPStatus.OK:
logger.bind(tag=TAG).error(
f"code={responses.status_code}, message={responses.message}, 请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code"
f"code={responses.status_code}, message={responses.message}, please refer to document: https://help.aliyun.com/zh/model-studio/developer-reference/error-code"
)
yield "【阿里百练API服务响应异常】"
yield "【Aliyun Bailian API Service Response Exception】"
else:
full_text = getattr(getattr(responses, "output", None), "text", "")
logger.bind(tag=TAG).info(
f"【阿里百练API服务】完整响应长度: {len(full_text)}"
f"【Aliyun Bailian API Service】Full response length: {len(full_text)}"
)
for i in range(0, len(full_text), self.streaming_chunk_size):
chunk = full_text[i:i + self.streaming_chunk_size]
@ -96,14 +96,14 @@ class LLMProvider(LLMProviderBase):
yield chunk
except Exception as e:
logger.bind(tag=TAG).error(f"【阿里百练API服务】响应异常: {e}")
yield "【LLM服务响应异常】"
logger.bind(tag=TAG).error(f"【Aliyun Bailian API Service】Response Exception: {e}")
yield "【LLM Service Response Exception】"
def response_with_functions(self, session_id, dialogue, functions=None):
# 阿里百练当前未支持原生的 function call。为保持兼容,这里回退到普通文本流式输出。
# 上层会按 (content, tool_calls) 的形式消费,这里始终返回 (token, None)
# Aliyun Bailian currently does not support native function call. To maintain compatibility, fallback to plain text streaming output here.
# The upper layer will consume in the form of (content, tool_calls), here always return (token, None)
logger.bind(tag=TAG).warning(
"阿里百练未实现原生 function call,已回退为纯文本流式输出"
"Aliyun Bailian does not implement native function call, has fallen back to plain text streaming output"
)
for token in self.response(session_id, dialogue):
yield token, None

View file

@ -12,19 +12,28 @@ class LLMProviderBase(ABC):
def response_no_stream(self, system_prompt, user_prompt, **kwargs):
try:
# 构造对话格式
# Construct dialogue format
dialogue = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
]
timeout = kwargs.get("timeout")
import time
start_time = time.time()
result = ""
for part in self.response("", dialogue, **kwargs):
# Strict wall-clock check
if timeout and (time.time() - start_time) > timeout:
logger.bind(tag=TAG).warning(f"Response consumption exceeded timeout of {timeout}s, returning partial.")
break
result += part
return result
except Exception as e:
logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}")
return "【LLM服务响应异常】"
logger.bind(tag=TAG).error(f"Error in LLM response generation: {e}")
return "[LLM Service Response Error]"
def response_with_functions(self, session_id, dialogue, functions=None):
"""

View file

@ -22,7 +22,7 @@ class LLMProvider(LLMProviderBase):
self.personal_access_token = config.get("personal_access_token")
self.bot_id = str(config.get("bot_id"))
self.user_id = str(config.get("user_id"))
self.session_conversation_map = {} # 存储session_id和conversation_id的映射
self.session_conversation_map = {} # Store mapping of session_id and conversation_id
model_key_msg = check_model_key("CozeLLM", self.personal_access_token)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
@ -36,11 +36,11 @@ class LLMProvider(LLMProviderBase):
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)
conversation_id = self.session_conversation_map.get(session_id)
# 如果没有找到conversation_id,则创建新的对话
# If conversation_id is not found, create a new conversation
if not conversation_id:
conversation = coze.conversations.create(messages=[])
conversation_id = conversation.id
self.session_conversation_map[session_id] = conversation_id # 更新映射
self.session_conversation_map[session_id] = conversation_id # Update mapping
for event in coze.chat.stream(
bot_id=self.bot_id,
@ -56,13 +56,13 @@ class LLMProvider(LLMProviderBase):
def response_with_functions(self, session_id, dialogue, functions=None):
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
# 第一次调用llm, 取最后一条用户消息,附加tool提示词
# First LLM call, get the last user message, append tool prompt
last_msg = dialogue[-1]["content"]
function_str = json.dumps(functions, ensure_ascii=False)
modify_msg = get_system_prompt_for_function(function_str) + last_msg
dialogue[-1]["content"] = modify_msg
# 如果最后一个是 role="tool",附加到user上
# If the last one is role="tool", append to user
if len(dialogue) > 1 and dialogue[-1]["role"] == "tool":
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
while len(dialogue) > 1:

View file

@ -14,18 +14,18 @@ class LLMProvider(LLMProviderBase):
self.api_key = config["api_key"]
self.mode = config.get("mode", "chat-messages")
self.base_url = config.get("base_url", "https://api.dify.ai/v1").rstrip("/")
self.session_conversation_map = {} # 存储session_id和conversation_id的映射
self.session_conversation_map = {} # Store mapping of session_id and conversation_id
model_key_msg = check_model_key("DifyLLM", self.api_key)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
def response(self, session_id, dialogue, **kwargs):
try:
# 取最后一条用户消息
# Get the last user message
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
conversation_id = self.session_conversation_map.get(session_id)
# 发起流式请求
# Initiate streaming request
if self.mode == "chat-messages":
request_json = {
"query": last_msg["content"],
@ -57,13 +57,13 @@ class LLMProvider(LLMProviderBase):
for line in r.iter_lines():
if line.startswith(b"data: "):
event = json.loads(line[6:])
# 如果没有找到conversation_id,则获取此次conversation_id
# If conversation_id is not found, get conversation_id for this time
if not conversation_id:
conversation_id = event.get("conversation_id")
self.session_conversation_map[session_id] = (
conversation_id # 更新映射
conversation_id # Update mapping
)
# 过滤 message_replace 事件,此事件会全量推一次
# Filter message_replace event, this event will push full amount once
if event.get("event") != "message_replace" and event.get(
"answer"
):
@ -76,12 +76,12 @@ class LLMProvider(LLMProviderBase):
if event["data"]["status"] == "succeeded":
yield event["data"]["outputs"]["answer"]
else:
yield "【服务响应异常】"
yield "【Service Response Exception】"
elif self.mode == "completion-messages":
for line in r.iter_lines():
if line.startswith(b"data: "):
event = json.loads(line[6:])
# 过滤 message_replace 事件,此事件会全量推一次
# Filter message_replace event, this event will push full amount once
if event.get("event") != "message_replace" and event.get(
"answer"
):
@ -89,17 +89,17 @@ class LLMProvider(LLMProviderBase):
except Exception as e:
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
yield "【服务响应异常】"
yield "【Service Response Exception】"
def response_with_functions(self, session_id, dialogue, functions=None):
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
# 第一次调用llm, 取最后一条用户消息,附加tool提示词
# First LLM call, get the last user message, append tool prompt
last_msg = dialogue[-1]["content"]
function_str = json.dumps(functions, ensure_ascii=False)
modify_msg = get_system_prompt_for_function(function_str) + last_msg
dialogue[-1]["content"] = modify_msg
# 如果最后一个是 role="tool",附加到user上
# If the last one is role="tool", append to user
if len(dialogue) > 1 and dialogue[-1]["role"] == "tool":
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
while len(dialogue) > 1:

View file

@ -20,10 +20,10 @@ class LLMProvider(LLMProviderBase):
def response(self, session_id, dialogue, **kwargs):
try:
# 取最后一条用户消息
# Get the last user message
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
# 发起流式请求
# Initiate streaming request
with requests.post(
f"{self.base_url}/chat/completions",
headers={"Authorization": f"Bearer {self.api_key}"},
@ -65,9 +65,9 @@ class LLMProvider(LLMProviderBase):
except Exception as e:
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
yield "【服务响应异常】"
yield "【Service Response Exception】"
def response_with_functions(self, session_id, dialogue, functions=None):
logger.bind(tag=TAG).error(
f"fastgpt暂未实现完整的工具调用(function call),建议使用其他意图识别"
f"FastGPT has not implemented full tool calling (function call) yet, it is recommended to use other intent recognition"
)

View file

@ -26,8 +26,8 @@ def test_proxy(proxy_url: str, test_url: str) -> bool:
def setup_proxy_env(http_proxy: str | None, https_proxy: str | None):
"""
分别测试 HTTP 和 HTTPS 代理是否可用,并设置环境变量。
如果 HTTPS 代理不可用但 HTTP 可用,会将 HTTPS_PROXY 也指向 HTTP。
Test if HTTP and HTTPS proxies are available separately, and set environment variables.
If HTTPS proxy is unavailable but HTTP is available, set HTTPS_PROXY to point to HTTP as well.
"""
test_http_url = "http://www.google.com"
test_https_url = "https://www.google.com"
@ -38,32 +38,32 @@ def setup_proxy_env(http_proxy: str | None, https_proxy: str | None):
ok_http = test_proxy(http_proxy, test_http_url)
if ok_http:
os.environ["HTTP_PROXY"] = http_proxy
log.bind(tag=TAG).info(f"配置提供的Gemini HTTPS代理连通成功: {http_proxy}")
log.bind(tag=TAG).info(f"Gemini HTTPS proxy provided in config connected successfully: {http_proxy}")
else:
log.bind(tag=TAG).warning(f"配置提供的Gemini HTTP代理不可用: {http_proxy}")
log.bind(tag=TAG).warning(f"Gemini HTTP proxy provided in config unavailable: {http_proxy}")
if https_proxy:
ok_https = test_proxy(https_proxy, test_https_url)
if ok_https:
os.environ["HTTPS_PROXY"] = https_proxy
log.bind(tag=TAG).info(f"配置提供的Gemini HTTPS代理连通成功: {https_proxy}")
log.bind(tag=TAG).info(f"Gemini HTTPS proxy provided in config connected successfully: {https_proxy}")
else:
log.bind(tag=TAG).warning(
f"配置提供的Gemini HTTPS代理不可用: {https_proxy}"
f"Gemini HTTPS proxy provided in config unavailable: {https_proxy}"
)
# 如果https_proxy不可用,但http_proxy可用且能走通https,则复用http_proxy作为https_proxy
# If https_proxy is unavailable, but http_proxy is available and can reach https, reuse http_proxy as https_proxy
if ok_http and not ok_https:
if test_proxy(http_proxy, test_https_url):
os.environ["HTTPS_PROXY"] = http_proxy
ok_https = True
log.bind(tag=TAG).info(f"复用HTTP代理作为HTTPS代理: {http_proxy}")
log.bind(tag=TAG).info(f"Reuse HTTP proxy as HTTPS proxy: {http_proxy}")
if not ok_http and not ok_https:
log.bind(tag=TAG).error(
f"Gemini 代理设置失败: HTTP 和 HTTPS 代理都不可用,请检查配置"
f"Gemini proxy setup failed: Both HTTP and HTTPS proxies are unavailable, please check configuration"
)
raise RuntimeError("HTTP 和 HTTPS 代理都不可用,请检查配置")
raise RuntimeError("Both HTTP and HTTPS proxies are unavailable, please check configuration")
class LLMProvider(LLMProviderBase):
@ -79,19 +79,19 @@ class LLMProvider(LLMProviderBase):
if http_proxy or https_proxy:
log.bind(tag=TAG).info(
f"检测到Gemini代理配置,开始测试代理连通性和设置代理环境..."
f"Gemini proxy configuration detected, starting to test proxy connectivity and setup proxy environment..."
)
setup_proxy_env(http_proxy, https_proxy)
log.bind(tag=TAG).info(
f"Gemini 代理设置成功 - HTTP: {http_proxy}, HTTPS: {https_proxy}"
f"Gemini proxy set up successfully - HTTP: {http_proxy}, HTTPS: {https_proxy}"
)
# 配置API密钥
# Configure API key
genai.configure(api_key=self.api_key)
# 设置请求超时(秒)
self.timeout = cfg.get("timeout", 120) # 默认120秒
# Set request timeout (seconds)
self.timeout = cfg.get("timeout", 120) # Default 120 seconds
# 创建模型实例
# Create model instance
self.model = genai.GenerativeModel(self.model_name)
self.gen_cfg = GenerationConfig(
@ -118,7 +118,7 @@ class LLMProvider(LLMProviderBase):
)
]
# Gemini文档提到,无需维护session-id,直接用dialogue拼接而成
# Gemini documentation mentions that session-id management is not needed, directly constructed from dialogue
def response(self, session_id, dialogue, **kwargs):
yield from self._generate(dialogue, None)
@ -128,7 +128,7 @@ class LLMProvider(LLMProviderBase):
def _generate(self, dialogue, tools):
role_map = {"assistant": "model", "user": "user"}
contents: list = []
# 拼接对话
# Splice dialogue
for m in dialogue:
r = m["role"]
@ -158,10 +158,22 @@ class LLMProvider(LLMProviderBase):
)
continue
parts = [{"text": str(m.get("content", ""))}]
# If this is the last message (user's latest input) and we have audio, attach it
if i == len(dialogue) - 1 and r == "user" and kwargs.get("audio_data"):
parts.append(
{
"inline_data": {
"mime_type": "audio/wav",
"data": kwargs.get("audio_data")
}
}
)
contents.append(
{
"role": role_map.get(r, "user"),
"parts": [{"text": str(m.get("content", ""))}],
"parts": parts,
}
)
@ -177,7 +189,7 @@ class LLMProvider(LLMProviderBase):
for chunk in stream:
cand = chunk.candidates[0]
for part in cand.content.parts:
# a) 函数调用-通常是最后一段话才是函数调用
# a) Function call - usually the last paragraph is the function call
if getattr(part, "function_call", None):
fc = part.function_call
yield None, [
@ -193,15 +205,15 @@ class LLMProvider(LLMProviderBase):
)
]
return
# b) 普通文本
# b) Plain text
if getattr(part, "text", None):
yield part.text if tools is None else (part.text, None)
finally:
if tools is not None:
yield None, None # function‑mode 结束,返回哑包
yield None, None # function-mode ended, return dummy package
# 关闭stream,预留后续打断对话功能的功能方法,官方文档推荐打断对话要关闭上一个流,可以有效减少配额计费和资源占用
# Close stream, reserved for subsequent conversation interruption function method. Official documentation recommends closing the previous stream to interrupt conversation, which can effectively reduce quota billing and resource usage
@staticmethod
def _safe_finish_stream(stream: GenerateContentResponse):
if hasattr(stream, "resolve"):
@ -209,5 +221,5 @@ class LLMProvider(LLMProviderBase):
elif hasattr(stream, "close"):
stream.close() # Gemini SDK version < 0.5.0
else:
for _ in stream: # 兜底耗尽
for _ in stream: # Exhaust fallback
pass

View file

@ -9,43 +9,43 @@ logger = setup_logging()
class LLMProvider(LLMProviderBase):
def __init__(self, config):
self.agent_id = config.get("agent_id") # 对应 agent_id
self.agent_id = config.get("agent_id") # Corresponds to agent_id
self.api_key = config.get("api_key")
self.base_url = config.get("base_url", config.get("url")) # 默认使用 base_url
self.api_url = f"{self.base_url}/api/conversation/process" # 拼接完整的 API URL
self.base_url = config.get("base_url", config.get("url")) # Default use base_url
self.api_url = f"{self.base_url}/api/conversation/process" # Splice complete API URL
def response(self, session_id, dialogue, **kwargs):
try:
# home assistant语音助手自带意图,无需使用xiaozhi ai自带的,只需要把用户说的话传递给home assistant即可
# home assistant voice assistant has its own intent, no need to use xiaozhi ai's, just pass what user said to home assistant
# 提取最后一个 role 为 'user' 的 content
# Extract content of the last role as 'user'
input_text = None
if isinstance(dialogue, list): # 确保 dialogue 是一个列表
# 逆序遍历,找到最后一个 role 为 'user' 的消息
if isinstance(dialogue, list): # Ensure dialogue is a list
# Reverse traverse, find the last message with role 'user'
for message in reversed(dialogue):
if message.get("role") == "user": # 找到 role 为 'user' 的消息
if message.get("role") == "user": # Find message with role 'user'
input_text = message.get("content", "")
break # 找到后立即退出循环
break # Exit loop immediately after finding
# 构造请求数据
# Construct request data
payload = {
"text": input_text,
"agent_id": self.agent_id,
"conversation_id": session_id, # 使用 session_id 作为 conversation_id
"conversation_id": session_id, # Use session_id as conversation_id
}
# 设置请求头
# Set request headers
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
# 发起 POST 请求
# Initiate POST request
response = requests.post(self.api_url, json=payload, headers=headers)
# 检查请求是否成功
# Check if request is successful
response.raise_for_status()
# 解析返回数据
# Parse return data
data = response.json()
speech = (
data.get("response", {})
@ -54,18 +54,18 @@ class LLMProvider(LLMProviderBase):
.get("speech", "")
)
# 返回生成的内容
# Return generated content
if speech:
yield speech
else:
logger.bind(tag=TAG).warning("API 返回数据中没有 speech 内容")
logger.bind(tag=TAG).warning("No speech content in API return data")
except RequestException as e:
logger.bind(tag=TAG).error(f"HTTP 请求错误: {e}")
logger.bind(tag=TAG).error(f"HTTP request error: {e}")
except Exception as e:
logger.bind(tag=TAG).error(f"生成响应时出错: {e}")
logger.bind(tag=TAG).error(f"Error generating response: {e}")
def response_with_functions(self, session_id, dialogue, functions=None):
logger.bind(tag=TAG).error(
f"homeassistant不支持(function call),建议使用其他意图识别"
f"homeassistant does not support (function call), it is recommended to use other intent recognition"
)

View file

@ -12,7 +12,7 @@ class LLMProvider(LLMProviderBase):
self.model_name = config.get("model_name")
self.base_url = config.get("base_url", "http://localhost:11434")
# Initialize OpenAI client with Ollama base URL
# 如果没有v1,增加v1
# If no v1, add v1
if not self.base_url.endswith("/v1"):
self.base_url = f"{self.base_url}/v1"
@ -21,34 +21,34 @@ class LLMProvider(LLMProviderBase):
api_key="ollama", # Ollama doesn't need an API key but OpenAI client requires one
)
# 检查是否是qwen3模型
# Check if it is qwen3 model
self.is_qwen3 = self.model_name and self.model_name.lower().startswith("qwen3")
def response(self, session_id, dialogue, **kwargs):
try:
# 如果是qwen3模型,在用户最后一条消息中添加/no_think指令
# If it is qwen3 model, add /no_think instruction to the last user message
if self.is_qwen3:
# 复制对话列表,避免修改原始对话
# Copy dialogue list to avoid modifying original dialogue
dialogue_copy = dialogue.copy()
# 找到最后一条用户消息
# Find the last user message
for i in range(len(dialogue_copy) - 1, -1, -1):
if dialogue_copy[i]["role"] == "user":
# 在用户消息前添加/no_think指令
# Add /no_think instruction before user message
dialogue_copy[i]["content"] = (
"/no_think " + dialogue_copy[i]["content"]
)
logger.bind(tag=TAG).debug(f"为qwen3模型添加/no_think指令")
break
# 使用修改后的对话
# Use modified dialogue
dialogue = dialogue_copy
responses = self.client.chat.completions.create(
model=self.model_name, messages=dialogue, stream=True
)
is_active = True
# 用于处理跨chunk的标签
# For handling tags across chunks
buffer = ""
for chunk in responses:
@ -61,56 +61,56 @@ class LLMProvider(LLMProviderBase):
content = delta.content if hasattr(delta, "content") else ""
if content:
# 将内容添加到缓冲区
# Append content to buffer
buffer += content
# 处理缓冲区中的标签
# Process tags in buffer
while "<think>" in buffer and "</think>" in buffer:
# 找到完整的<think></think>标签并移除
pre = buffer.split("<think>", 1)[0]
post = buffer.split("</think>", 1)[1]
buffer = pre + post
# 处理只有开始标签的情况
# Handle case with only start tag
if "<think>" in buffer:
is_active = False
buffer = buffer.split("<think>", 1)[0]
# 处理只有结束标签的情况
# Handle case with only end tag
if "</think>" in buffer:
is_active = True
buffer = buffer.split("</think>", 1)[1]
# 如果当前处于活动状态且缓冲区有内容,则输出
# If currently active and buffer has content, output
if is_active and buffer:
yield buffer
buffer = "" # 清空缓冲区
buffer = "" # Clear buffer
except Exception as e:
logger.bind(tag=TAG).error(f"Error processing chunk: {e}")
except Exception as e:
logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}")
yield "【Ollama服务响应异常】"
yield "【Ollama Service Response Exception】"
def response_with_functions(self, session_id, dialogue, functions=None):
try:
# 如果是qwen3模型,在用户最后一条消息中添加/no_think指令
# If it is qwen3 model, add /no_think instruction to the last user message
if self.is_qwen3:
# 复制对话列表,避免修改原始对话
# Copy dialogue list to avoid modifying original dialogue
dialogue_copy = dialogue.copy()
# 找到最后一条用户消息
# Find the last user message
for i in range(len(dialogue_copy) - 1, -1, -1):
if dialogue_copy[i]["role"] == "user":
# 在用户消息前添加/no_think指令
# Add /no_think instruction before user message
dialogue_copy[i]["content"] = (
"/no_think " + dialogue_copy[i]["content"]
)
logger.bind(tag=TAG).debug(f"为qwen3模型添加/no_think指令")
break
# 使用修改后的对话
# Use modified dialogue
dialogue = dialogue_copy
stream = self.client.chat.completions.create(
@ -135,41 +135,41 @@ class LLMProvider(LLMProviderBase):
delta.tool_calls if hasattr(delta, "tool_calls") else None
)
# 如果是工具调用,直接传递
# If it is tool call, pass directly
if tool_calls:
yield None, tool_calls
continue
# 处理文本内容
# Process text content
if content:
# 将内容添加到缓冲区
# Append content to buffer
buffer += content
# 处理缓冲区中的标签
# Process tags in buffer
while "<think>" in buffer and "</think>" in buffer:
# 找到完整的<think></think>标签并移除
# Find complete <think></think> tags and remove
pre = buffer.split("<think>", 1)[0]
post = buffer.split("</think>", 1)[1]
buffer = pre + post
# 处理只有开始标签的情况
# Handle case with only start tag
if "<think>" in buffer:
is_active = False
buffer = buffer.split("<think>", 1)[0]
# 处理只有结束标签的情况
# Handle case with only end tag
if "</think>" in buffer:
is_active = True
buffer = buffer.split("</think>", 1)[1]
# 如果当前处于活动状态且缓冲区有内容,则输出
# If currently active and buffer has content, output
if is_active and buffer:
yield buffer, None
buffer = "" # 清空缓冲区
buffer = "" # Clear buffer
except Exception as e:
logger.bind(tag=TAG).error(f"Error processing function chunk: {e}")
continue
except Exception as e:
logger.bind(tag=TAG).error(f"Error in Ollama function call: {e}")
yield f"【Ollama服务响应异常: {str(e)}】", None
yield f"【Ollama Service Response Exception: {str(e)}】", None

View file

@ -19,6 +19,11 @@ class LLMProvider(LLMProviderBase):
self.base_url = config.get("url")
timeout = config.get("timeout", 300)
self.timeout = int(timeout) if timeout else 300
self.num_ctx = config.get("num_ctx")
self.options = config.get("options", {})
if self.num_ctx:
self.options["num_ctx"] = int(self.num_ctx)
self.extra_body_config = config.get("extra_body", {})
param_defaults = {
"max_tokens": int,
@ -38,18 +43,26 @@ class LLMProvider(LLMProviderBase):
except (ValueError, TypeError):
setattr(self, param, None)
self.max_retries = int(config.get("max_retries", 2))
logger.debug(
f"意图识别参数初始化: {self.temperature}, {self.max_tokens}, {self.top_p}, {self.frequency_penalty}"
f"LLM initialization: {self.model_name}, timeout={self.timeout}s, max_retries={self.max_retries}"
)
model_key_msg = check_model_key("LLM", self.api_key)
if model_key_msg:
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))
self.client = openai.OpenAI(
api_key=self.api_key,
base_url=self.base_url,
timeout=httpx.Timeout(self.timeout),
max_retries=self.max_retries
)
@staticmethod
def normalize_dialogue(dialogue):
"""自动修复 dialogue 中缺失 content 的消息"""
"""Automatically fix missing content in dialogue messages"""
for msg in dialogue:
if "role" in msg and "content" not in msg:
msg["content"] = ""
@ -65,19 +78,59 @@ class LLMProvider(LLMProviderBase):
"stream": True,
}
# 添加可选参数,只有当参数不为None时才添加
# Prepare extra_body, starting with generic extra_body from config
final_extra_body = getattr(self, "extra_body_config", {}).copy()
# Merge in self.options (which includes num_ctx)
if self.options:
if "options" not in final_extra_body:
final_extra_body["options"] = {}
# self.options take precedence over generic config if distinct,
# but usually self.options ARE from config, so update is fine.
final_extra_body["options"].update(self.options)
if final_extra_body:
request_params["extra_body"] = final_extra_body
# Add optional parameters, only add if parameter is not 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),
"response_format": kwargs.get("response_format"),
}
for key, value in optional_params.items():
if value is not None:
request_params[key] = value
responses = self.client.chat.completions.create(**request_params)
# Support for checking num_ctx in config (passed via self.xxx if we add it to init)
# We need to add it to init first, or just check config again?
# Better to check if we can access config. config is passed to init.
# We should update init to read num_ctx.
# Wait, I cannot edit init in this same tool call easily if I am targeting line 81.
# I will assume I need to do 2 edits or one big edit.
# For now, let's just use getattr(self, 'num_ctx', None) and assume I added it to init.
extra_body = {}
if getattr(self, "num_ctx", None):
# Ollama uses "options" for parameters in the OpenAI endpoint often,
# BUT some versions mapping allow "num_ctx" at top level of extra_body??
# "options" is the safest for Ollama native parameters.
extra_body["options"] = {"num_ctx": int(self.num_ctx)}
# Standard OpenAI SDK per-request timeout
request_timeout = kwargs.get("timeout", self.timeout)
request_retries = kwargs.get("max_retries", self.max_retries)
responses = self.client.with_options(max_retries=request_retries).chat.completions.create(
**request_params,
timeout=request_timeout
)
is_active = True
for chunk in responses:
@ -110,6 +163,9 @@ class LLMProvider(LLMProviderBase):
"tools": functions,
}
if self.options:
request_params["extra_body"] = {"options": self.options}
optional_params = {
"max_tokens": kwargs.get("max_tokens", self.max_tokens),
"temperature": kwargs.get("temperature", self.temperature),
@ -121,7 +177,14 @@ class LLMProvider(LLMProviderBase):
if value is not None:
request_params[key] = value
stream = self.client.chat.completions.create(**request_params)
# Standard OpenAI SDK per-request timeout
request_timeout = kwargs.get("timeout", self.timeout)
request_retries = kwargs.get("max_retries", self.max_retries)
stream = self.client.with_options(max_retries=request_retries).chat.completions.create(
**request_params,
timeout=request_timeout
)
for chunk in stream:
if getattr(chunk, "choices", None):
@ -132,11 +195,11 @@ class LLMProvider(LLMProviderBase):
elif isinstance(getattr(chunk, "usage", None), CompletionUsage):
usage_info = getattr(chunk, "usage", None)
logger.bind(tag=TAG).info(
f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')},"
f"输出 {getattr(usage_info, 'completion_tokens', '未知')},"
f"共计 {getattr(usage_info, 'total_tokens', '未知')}"
f"Token usage: Input {getattr(usage_info, 'prompt_tokens', 'Unknown')}, "
f"Output {getattr(usage_info, 'completion_tokens', 'Unknown')}, "
f"Total {getattr(usage_info, 'total_tokens', 'Unknown')}"
)
except Exception as e:
logger.bind(tag=TAG).error(f"Error in function call streaming: {e}")
yield f"【OpenAI服务响应异常: {e}】", None
yield f"【OpenAI Service Response Exception: {e}】", None

View file

@ -1,8 +1,8 @@
def get_system_prompt_for_function(functions: str) -> str:
"""
生成系统提示信息
:param functions: 可用的函数列表
:return: 系统提示信息
Generate system prompt info
:param functions: Available functions list
:return: System prompt info
"""
SYSTEM_PROMPT = f"""
@ -36,13 +36,13 @@ if you got tool as follow
"type": "function",
"function": {{
"name": "handle_exit_intent",
"description": "当用户想结束对话或需要退出系统时调用",
"description": "Called when user wants to end conversation or exit system",
"parameters": {{
"type": "object",
"properties": {{
"say_goodbye": {{
"type": "string",
"description": "和用户友好结束对话的告别语",
"description": "Farewell message to end conversation friendlily",
}}
}},
"required": ["say_goodbye"],
@ -56,7 +56,7 @@ you should respond with the following format:
{{
"name": "handle_exit_intent",
"arguments": {{
"say_goodbye": "再见,祝您生活愉快!"
"say_goodbye": "Goodbye, have a nice day!"
}}
}}
</tool_call>

View file

@ -12,7 +12,7 @@ class LLMProvider(LLMProviderBase):
self.model_name = config.get("model_name")
self.base_url = config.get("base_url", "http://localhost:9997")
# Initialize OpenAI client with Xinference base URL
# 如果没有v1,增加v1
# If no v1, add v1
if not self.base_url.endswith("/v1"):
self.base_url = f"{self.base_url}/v1"
@ -61,7 +61,7 @@ class LLMProvider(LLMProviderBase):
except Exception as e:
logger.bind(tag=TAG).error(f"Error in Xinference response generation: {e}")
yield "【Xinference服务响应异常】"
yield "【Xinference Service Response Exception】"
def response_with_functions(self, session_id, dialogue, functions=None):
try:
@ -94,5 +94,5 @@ class LLMProvider(LLMProviderBase):
logger.bind(tag=TAG).error(f"Error in Xinference function call: {e}")
yield {
"type": "content",
"content": f"【Xinference服务响应异常: {str(e)}】",
"content": f"【Xinference Service Response Exception: {str(e)}】",
}

View file

@ -22,10 +22,10 @@ class MemoryProvider(MemoryProviderBase):
try:
self.client = MemoryClient(api_key=self.api_key)
logger.bind(tag=TAG).info("成功连接到 Mem0ai 服务")
logger.bind(tag=TAG).info("Successfully connected to Mem0ai service")
except Exception as e:
logger.bind(tag=TAG).error(f"连接到 Mem0ai 服务时发生错误: {str(e)}")
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
logger.bind(tag=TAG).error(f"Error connecting to Mem0ai service: {str(e)}")
logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}")
self.use_mem0 = False
async def save_memory(self, msgs, session_id=None):
@ -44,7 +44,7 @@ class MemoryProvider(MemoryProviderBase):
result = self.client.add(messages, user_id=self.role_id)
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
except Exception as e:
logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to save memory: {str(e)}")
return None
async def query_memory(self, query: str) -> str:
@ -84,5 +84,5 @@ class MemoryProvider(MemoryProviderBase):
logger.bind(tag=TAG).debug(f"Query results: {memories_str}")
return memories_str
except Exception as e:
logger.bind(tag=TAG).error(f"查询记忆失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to query memory: {str(e)}")
return ""

View file

@ -10,66 +10,66 @@ from core.utils.util import check_model_key
short_term_memory_prompt = """
# 时空记忆编织者
# Time-Space Memory Weaver
## 核心使命
构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹
根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务
## Core Mission
Construct a growable dynamic memory network that retains key information within limited space while intelligently maintaining the trajectory of information evolution.
Summarize important user information from dialogue records to provide more personalized services in future conversations.
## 记忆法则
### 1. 三维度记忆评估(每次更新必执行)
| 维度 | 评估标准 | 权重分 |
|------------|---------------------------|--------|
| 时效性 | 信息新鲜度(按对话轮次) | 40% |
| 情感强度 | 含💖标记/重复提及次数 | 35% |
| 关联密度 | 与其他信息的连接数量 | 25% |
## Memory Laws
### 1. Three-Dimensional Memory Assessment (Executed on every update)
| Dimension | Assessment Criteria | Weight |
|---|---|---|
| Timeliness | Information Freshness (by dialogue turns) | 40% |
| Emotional Intensity | Containing 💖 markers/Repetition frequency | 35% |
| Association Density | Number of connections with other information | 25% |
### 2. 动态更新机制
**名字变更处理示例:**
原始记忆:"曾用名": ["张三"], "现用名": "张三丰"
触发条件:当检测到「我叫X」「称呼我Y」等命名信号时
操作流程:
1. 将旧名移入"曾用名"列表
2. 记录命名时间轴:"2024-02-15 14:32:启用张三丰"
3. 在记忆立方追加:「从张三到张三丰的身份蜕变」
### 2. Dynamic Update Mechanism
**Name Change Handling Example:**
Original Memory: "Former Name": ["John Doe"], "Current Name": "John Smith"
Trigger Condition: When detection signals like "My name is X", "Call me Y" appear
Operation Flow:
1. Move old name to "Former Name" list
2. Record naming timeline: "2024-02-15 14:32: Enable John Smith"
3. Append to Memory Cube: "Identity transformation from John Doe to John Smith"
### 3. 空间优化策略
- **信息压缩术**:用符号体系提升密度
- ✅"张三丰[北/软工/🐱]"
- ❌"北京软件工程师,养猫"
- **淘汰预警**:当总字数≥900时触发
1. 删除权重分<60且3轮未提及的信息
2. 合并相似条目(保留时间戳最近的)
### 3. Space Optimization Strategy
- **Information Compression**: Use symbol system to increase density
- ✅"John Smith[North/SE/🐱]"
- ❌"Beijing Software Engineer, raises a cat"
- **Elimination Warning**: Triggered when total character count ≥ 900
1. Delete information with weight score < 60 and not mentioned in 3 turns
2. Merge similar entries (keep the one with latest timestamp)
## 记忆结构
输出格式必须为可解析的json字符串,不需要解释、注释和说明,保存记忆时仅从对话提取信息,不要混入示例内容
## Memory Structure
Output format must be a parsable JSON string, no explanation, comments or descriptions needed. Only extract information from dialogue when saving memory, do not mix in example content.
```json
{
"时空档案": {
"身份图谱": {
"现用名": "",
"特征标记": []
"TimeSpaceArchives": {
"IdentityGraph": {
"CurrentName": "",
"FeatureTags": []
},
"记忆立方": [
"MemoryCube": [
{
"事件": "入职新公司",
"时间戳": "2024-03-20",
"情感值": 0.9,
"关联项": ["下午茶"],
"保鲜期": 30
"Event": "Joined new company",
"Timestamp": "2024-03-20",
"EmotionalValue": 0.9,
"RelatedItems": ["Afternoon Tea"],
"ShelfLife": 30
}
]
},
"关系网络": {
"高频话题": {"职场": 12},
"暗线联系": [""]
"RelationshipNetwork": {
"HighFreqTopics": {"Work": 12},
"HiddenConnections": [""]
},
"待响应": {
"紧急事项": ["需立即处理的任务"],
"潜在关怀": ["可主动提供的帮助"]
"PendingResponse": {
"UrgentMatters": ["Tasks needing immediate attention"],
"PotentialCare": ["Help that can be proactively offered"]
},
"高光语录": [
"最打动人心的瞬间,强烈的情感表达,user的原话"
"HighlightQuotes": [
"Most touching moments, strong emotional expressions, user's original words"
]
}
```
@ -78,7 +78,7 @@ short_term_memory_prompt = """
def extract_json_data(json_code):
start = json_code.find("```json")
# 从start开始找到下一个```结束
# Find next ``` end from start
end = json_code.find("```", start + 1)
# print("start:", start, "end:", end)
if start == -1 or end == -1:
@ -111,7 +111,7 @@ class MemoryProvider(MemoryProviderBase):
self.load_memory(summary_memory)
def load_memory(self, summary_memory):
# api获取到总结记忆后直接返回
# Return directly after API gets summary memory
if summary_memory or not self.save_to_file:
self.short_memory = summary_memory
return
@ -133,11 +133,11 @@ class MemoryProvider(MemoryProviderBase):
yaml.dump(all_memory, f, allow_unicode=True)
async def save_memory(self, msgs, session_id=None):
# 打印使用的模型信息
# Print model info used
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
logger.bind(tag=TAG).debug(f"使用记忆保存模型: {model_info}")
logger.bind(tag=TAG).debug(f"Using memory save model: {model_info}")
api_key = getattr(self.llm, "api_key", None)
memory_key_msg = check_model_key("记忆总结专用LLM", api_key)
memory_key_msg = check_model_key("Memory Summary LLM", api_key)
if memory_key_msg:
logger.bind(tag=TAG).error(memory_key_msg)
if self.llm is None:
@ -154,12 +154,12 @@ class MemoryProvider(MemoryProviderBase):
elif msg.role == "assistant":
msgStr += f"Assistant: {msg.content}\n"
if self.short_memory and len(self.short_memory) > 0:
msgStr += "历史记忆:\n"
msgStr += "History Memory:\n"
msgStr += self.short_memory
# 当前时间
# Current Time
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
msgStr += f"当前时间:{time_str}"
msgStr += f"Current Time: {time_str}"
if self.save_to_file:
result = self.llm.response_no_stream(
@ -170,13 +170,13 @@ class MemoryProvider(MemoryProviderBase):
)
json_str = extract_json_data(result)
try:
json.loads(json_str) # 检查json格式是否正确
json.loads(json_str) # Check if json format is correct
self.short_memory = json_str
self.save_memory_to_file()
except Exception as e:
print("Error:", e)
else:
# 当save_to_file为False时,调用Java端的聊天记录总结接口
# When save_to_file is False, call chat record summary interface on Java side
summary_id = session_id if session_id else self.role_id
await generate_and_save_chat_summary(summary_id)
logger.bind(tag=TAG).info(

View file

@ -1,5 +1,5 @@
"""
不使用记忆,可以选择此模块
This module can be selected if no memory is used
"""
from ..base import MemoryProviderBase, logger

View file

@ -1,4 +1,4 @@
"""工具执行器基类定义"""
"""Tool executor base class definition"""
from abc import ABC, abstractmethod
from typing import Dict, Any
@ -7,21 +7,21 @@ from plugins_func.register import ActionResponse
class ToolExecutor(ABC):
"""工具执行器抽象基类"""
"""Tool executor abstract base class"""
@abstractmethod
async def execute(
self, conn, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
"""执行工具调用"""
"""Execute tool call"""
pass
@abstractmethod
def get_tools(self) -> Dict[str, ToolDefinition]:
"""获取该执行器管理的所有工具"""
"""Get all tools managed by this executor"""
pass
@abstractmethod
def has_tool(self, tool_name: str) -> bool:
"""检查是否有指定工具"""
"""Check if specified tool exists"""
pass

View file

@ -1,4 +1,4 @@
"""工具系统的类型定义"""
"""Type definitions for the tool system"""
from enum import Enum
@ -8,20 +8,20 @@ from plugins_func.register import Action
class ToolType(Enum):
"""工具类型枚举"""
"""Tool type enumeration"""
SERVER_PLUGIN = "server_plugin" # 服务端插件
SERVER_MCP = "server_mcp" # 服务端MCP
DEVICE_IOT = "device_iot" # 设备端IoT
DEVICE_MCP = "device_mcp" # 设备端MCP
MCP_ENDPOINT = "mcp_endpoint" # MCP接入点
SERVER_PLUGIN = "server_plugin" # Server Plugin
SERVER_MCP = "server_mcp" # Server MCP
DEVICE_IOT = "device_iot" # Device IoT
DEVICE_MCP = "device_mcp" # Device MCP
MCP_ENDPOINT = "mcp_endpoint" # MCP Endpoint
@dataclass
class ToolDefinition:
"""工具定义"""
"""Tool definition"""
name: str # 工具名称
description: Dict[str, Any] # 工具描述(OpenAI函数调用格式)
tool_type: ToolType # 工具类型
parameters: Optional[Dict[str, Any]] = None # 额外参数
name: str # Tool name
description: Dict[str, Any] # Tool description (OpenAI function definition format)
tool_type: ToolType # Tool type
parameters: Optional[Dict[str, Any]] = None # Extra parameters

View file

@ -1,4 +1,4 @@
"""IoT设备描述符定义"""
"""IoT device descriptor definition"""
from config.logger import setup_logging
@ -7,7 +7,7 @@ logger = setup_logging()
class IotDescriptor:
"""IoT设备描述符"""
"""IoT device descriptor"""
def __init__(self, name, description, properties, methods):
self.name = name
@ -15,7 +15,7 @@ class IotDescriptor:
self.properties = []
self.methods = []
# 根据描述创建属性
# Create properties from description
if properties is not None:
for key, value in properties.items():
property_item = {}
@ -29,13 +29,13 @@ class IotDescriptor:
property_item["value"] = ""
self.properties.append(property_item)
# 根据描述创建方法
# Create methods from description
if methods is not None:
for key, value in methods.items():
method = {}
method["description"] = value["description"]
method["name"] = key
# 检查方法是否有参数
# Check if method has parameters
if "parameters" in value:
method["parameters"] = {}
for k, v in value["parameters"].items():

View file

@ -1,4 +1,4 @@
"""设备端IoT工具执行器"""
"""IoT Device Tool Executor"""
import json
import asyncio
@ -8,7 +8,7 @@ from plugins_func.register import Action, ActionResponse
class DeviceIoTExecutor(ToolExecutor):
"""设备端IoT工具执行器"""
"""IoT Device Tool Executor"""
def __init__(self, conn):
self.conn = conn
@ -17,16 +17,16 @@ class DeviceIoTExecutor(ToolExecutor):
async def execute(
self, conn, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
"""执行设备端IoT工具"""
"""Execute IoT Device Tool"""
if not self.has_tool(tool_name):
return ActionResponse(
action=Action.NOTFOUND, response=f"IoT工具 {tool_name} 不存在"
action=Action.NOTFOUND, response=f"IoT tool {tool_name} not found"
)
try:
# 解析工具名称,获取设备名和操作类型
# Parse tool name to get device name and operation type
if tool_name.startswith("get_"):
# 查询操作:get_devicename_property
# Query operation: get_devicename_property
parts = tool_name.split("_", 2)
if len(parts) >= 3:
device_name = parts[1]
@ -34,9 +34,9 @@ class DeviceIoTExecutor(ToolExecutor):
value = await self._get_iot_status(device_name, property_name)
if value is not None:
# 处理响应模板
# Handle response template
response_success = arguments.get(
"response_success", "查询成功:{value}"
"response_success", "Query successful: {value}"
)
response = response_success.replace("{value}", str(value))
@ -46,36 +46,36 @@ class DeviceIoTExecutor(ToolExecutor):
)
else:
response_failure = arguments.get(
"response_failure", f"无法获取{device_name}的状态"
"response_failure", f"Cannot get status for {device_name}"
)
return ActionResponse(
action=Action.ERROR, response=response_failure
)
else:
# 控制操作:devicename_method
# Control operation: devicename_method
parts = tool_name.split("_", 1)
if len(parts) >= 2:
device_name = parts[0]
method_name = parts[1]
# 提取控制参数(排除响应参数)
# Extract control parameters (exclude response parameters)
control_params = {
k: v
for k, v in arguments.items()
if k not in ["response_success", "response_failure"]
}
# 发送IoT控制命令
# Send IoT control command
await self._send_iot_command(
device_name, method_name, control_params
)
# 等待状态更新
# Wait for status update
await asyncio.sleep(0.1)
response_success = arguments.get("response_success", "操作成功")
response_success = arguments.get("response_success", "Operation successful")
# 处理响应中的占位符
# Handle placeholders in response
for param_name, param_value in control_params.items():
placeholder = "{" + param_name + "}"
if placeholder in response_success:
@ -93,14 +93,14 @@ class DeviceIoTExecutor(ToolExecutor):
result=response_success,
)
return ActionResponse(action=Action.ERROR, response="无法解析IoT工具名称")
return ActionResponse(action=Action.ERROR, response="Cannot parse IoT tool name")
except Exception as e:
response_failure = arguments.get("response_failure", "操作失败")
response_failure = arguments.get("response_failure", "Operation failed")
return ActionResponse(action=Action.ERROR, response=response_failure)
async def _get_iot_status(self, device_name: str, property_name: str):
"""获取IoT设备状态"""
"""Get IoT device status"""
for key, value in self.conn.iot_descriptors.items():
if key.lower() == device_name.lower():
for property_item in value.properties:
@ -111,7 +111,7 @@ class DeviceIoTExecutor(ToolExecutor):
async def _send_iot_command(
self, device_name: str, method_name: str, parameters: Dict[str, Any]
):
"""发送IoT控制命令"""
"""Send IoT control command"""
for key, value in self.conn.iot_descriptors.items():
if key.lower() == device_name.lower():
for method in value.methods:
@ -130,15 +130,15 @@ class DeviceIoTExecutor(ToolExecutor):
await self.conn.websocket.send(send_message)
return
raise Exception(f"未找到设备{device_name}的方法{method_name}")
raise Exception(f"Method {method_name} not found for device {device_name}")
def register_iot_tools(self, descriptors: list):
"""注册IoT工具"""
"""Register IoT Tools"""
for descriptor in descriptors:
device_name = descriptor["name"]
device_desc = descriptor["description"]
# 注册查询工具
# Register query tool
if "properties" in descriptor:
for prop_name, prop_info in descriptor["properties"].items():
tool_name = f"get_{device_name.lower()}_{prop_name.lower()}"
@ -147,17 +147,17 @@ class DeviceIoTExecutor(ToolExecutor):
"type": "function",
"function": {
"name": tool_name,
"description": f"查询{device_desc}的{prop_info['description']}",
"description": f"Query {prop_info['description']} of {device_desc}",
"parameters": {
"type": "object",
"properties": {
"response_success": {
"type": "string",
"description": f"查询成功时的友好回复,必须使用{{value}}作为占位符表示查询到的值",
"description": f"Friendly response when query succeeds, must use {{value}} as placeholder for the value",
},
"response_failure": {
"type": "string",
"description": f"查询失败时的友好回复",
"description": f"Friendly response when query fails",
},
},
"required": ["response_success", "response_failure"],
@ -171,16 +171,16 @@ class DeviceIoTExecutor(ToolExecutor):
tool_type=ToolType.DEVICE_IOT,
)
# 注册控制工具
# Register control tool
if "methods" in descriptor:
for method_name, method_info in descriptor["methods"].items():
tool_name = f"{device_name.lower()}_{method_name.lower()}"
# 构建参数
# Build parameters
parameters = {}
required_params = []
# 添加方法的原始参数
# Add original method parameters
if "parameters" in method_info:
parameters.update(
{
@ -195,16 +195,16 @@ class DeviceIoTExecutor(ToolExecutor):
)
required_params.extend(method_info["parameters"].keys())
# 添加响应参数
# Add response parameters
parameters.update(
{
"response_success": {
"type": "string",
"description": "操作成功时的友好回复",
"description": "Friendly response when operation succeeds",
},
"response_failure": {
"type": "string",
"description": "操作失败时的友好回复",
"description": "Friendly response when operation fails",
},
}
)
@ -230,9 +230,9 @@ class DeviceIoTExecutor(ToolExecutor):
)
def get_tools(self) -> Dict[str, ToolDefinition]:
"""获取所有设备端IoT工具"""
"""Get all IoT device tools"""
return self.iot_tools.copy()
def has_tool(self, tool_name: str) -> bool:
"""检查是否有指定的设备端IoT工具"""
"""Check if specified IoT device tool exists"""
return tool_name in self.iot_tools

View file

@ -1,4 +1,4 @@
"""IoT设备支持模块,提供IoT设备描述符和状态处理"""
"""IoT device support module, provides IoT device descriptor and status handling"""
import asyncio
from config.logger import setup_logging
@ -9,7 +9,7 @@ logger = setup_logging()
async def handleIotDescriptors(conn, descriptors):
"""处理物联网描述"""
"""Handle IoT descriptors"""
wait_max_time = 5
while (
not hasattr(conn, "func_handler")
@ -19,31 +19,31 @@ async def handleIotDescriptors(conn, descriptors):
await asyncio.sleep(1)
wait_max_time -= 1
if wait_max_time <= 0:
logger.bind(tag=TAG).debug("连接对象没有func_handler")
logger.bind(tag=TAG).debug("Connection object has no func_handler")
return
functions_changed = False
for descriptor in descriptors:
# 如果descriptor没有properties和methods,则直接跳过
# If descriptor has no properties and methods, skip it
if "properties" not in descriptor and "methods" not in descriptor:
continue
# 处理缺失properties的情况
# Handle missing properties
if "properties" not in descriptor:
descriptor["properties"] = {}
# 从methods中提取所有参数作为properties
# Extract all parameters from methods as properties
if "methods" in descriptor:
for method_name, method_info in descriptor["methods"].items():
if "parameters" in method_info:
for param_name, param_info in method_info["parameters"].items():
# 将参数信息转换为属性信息
# Convert parameter information to property information
descriptor["properties"][param_name] = {
"description": param_info["description"],
"type": param_info["type"],
}
# 创建IOT设备描述符
# Create IOT device descriptor
iot_descriptor = IotDescriptor(
descriptor["name"],
descriptor["description"],
@ -53,16 +53,16 @@ async def handleIotDescriptors(conn, descriptors):
conn.iot_descriptors[descriptor["name"]] = iot_descriptor
functions_changed = True
# 如果注册了新函数,更新function描述列表
# If new functions are registered, update function description list
if functions_changed and hasattr(conn, "func_handler"):
# 注册IoT工具到统一工具处理器
# Register IoT tools to unified tool handler
await conn.func_handler.register_iot_tools(descriptors)
conn.func_handler.current_support_functions()
async def handleIotStatus(conn, states):
"""处理物联网状态"""
"""Handle IoT status"""
for state in states:
for key, value in conn.iot_descriptors.items():
if key == state["name"]:
@ -71,13 +71,13 @@ async def handleIotStatus(conn, states):
if property_item["name"] == k:
if type(v) != type(property_item["value"]):
logger.bind(tag=TAG).error(
f"属性{property_item['name']}的值类型不匹配"
f"Property {property_item['name']} value type mismatch"
)
break
else:
property_item["value"] = v
logger.bind(tag=TAG).info(
f"物联网状态更新: {key} , {property_item['name']} = {v}"
f"IoT status updated: {key} , {property_item['name']} = {v}"
)
break
break

View file

@ -1,4 +1,4 @@
"""设备端MCP客户端定义"""
"""Device end MCP client definition"""
import asyncio
from concurrent.futures import Future
@ -10,7 +10,7 @@ logger = setup_logging()
class MCPClient:
"""设备端MCP客户端,用于管理MCP状态和工具"""
"""Device end MCP client, used to manage MCP status and tools"""
def __init__(self):
self.tools = {} # sanitized_name -> tool_data

View file

@ -1,4 +1,4 @@
"""设备端MCP工具执行器"""
"""Device end MCP tool executor"""
from typing import Dict, Any
from ..base import ToolType, ToolDefinition, ToolExecutor
@ -7,7 +7,7 @@ from .mcp_handler import call_mcp_tool
class DeviceMCPExecutor(ToolExecutor):
"""设备端MCP工具执行器"""
"""Device end MCP tool executor"""
def __init__(self, conn):
self.conn = conn
@ -15,26 +15,26 @@ class DeviceMCPExecutor(ToolExecutor):
async def execute(
self, conn, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
"""执行设备端MCP工具"""
"""Execute device end MCP tool"""
if not hasattr(conn, "mcp_client") or not conn.mcp_client:
return ActionResponse(
action=Action.ERROR,
response="设备端MCP客户端未初始化",
response="Device end MCP client not initialized",
)
if not await conn.mcp_client.is_ready():
return ActionResponse(
action=Action.ERROR,
response="设备端MCP客户端未准备就绪",
response="Device end MCP client not ready",
)
try:
# 转换参数为JSON字符串
# Convert parameters to JSON string
import json
args_str = json.dumps(arguments) if arguments else "{}"
# 调用设备端MCP工具
# Call device end MCP tool
result = await call_mcp_tool(conn, conn.mcp_client, tool_name, args_str)
resultJson = None
@ -44,7 +44,7 @@ class DeviceMCPExecutor(ToolExecutor):
except Exception as e:
pass
# 视觉大模型不经过二次LLM处理
# Visual large models do not go through secondary LLM processing
if (
resultJson is not None
and isinstance(resultJson, dict)
@ -63,7 +63,7 @@ class DeviceMCPExecutor(ToolExecutor):
return ActionResponse(action=Action.ERROR, response=str(e))
def get_tools(self) -> Dict[str, ToolDefinition]:
"""获取所有设备端MCP工具"""
"""Get all device end MCP tools"""
if not hasattr(self.conn, "mcp_client") or not self.conn.mcp_client:
return {}
@ -82,7 +82,7 @@ class DeviceMCPExecutor(ToolExecutor):
return tools
def has_tool(self, tool_name: str) -> bool:
"""检查是否有指定的设备端MCP工具"""
"""Check if there is a specified device end MCP tool"""
if not hasattr(self.conn, "mcp_client") or not self.conn.mcp_client:
return False

View file

@ -1,8 +1,10 @@
"""设备端MCP客户端支持模块"""
"""Device-side MCP Client Support Module"""
import json
import asyncio
import re
import re
from datetime import datetime
from concurrent.futures import Future
from core.utils.util import get_vision_url, sanitize_tool_name
from core.utils.auth import AuthToken
@ -13,7 +15,7 @@ logger = setup_logging()
class MCPClient:
"""设备端MCP客户端,用于管理MCP状态和工具"""
"""Device-side MCP Client for managing state and tools"""
def __init__(self):
self.tools = {} # sanitized_name -> tool_data
@ -28,11 +30,9 @@ class MCPClient:
return name in self.tools
def get_available_tools(self) -> list:
# Check if the cache is valid
if self._cached_available_tools is not None:
return self._cached_available_tools
# If cache is not valid, regenerate the list
result = []
for tool_name, tool_data in self.tools.items():
function_def = {
@ -46,7 +46,7 @@ class MCPClient:
}
result.append({"type": "function", "function": function_def})
self._cached_available_tools = result # Store the generated list in cache
self._cached_available_tools = result
return result
async def is_ready(self) -> bool:
@ -62,9 +62,8 @@ class MCPClient:
sanitized_name = sanitize_tool_name(tool_data["name"])
self.tools[sanitized_name] = tool_data
self.name_mapping[sanitized_name] = tool_data["name"]
self._cached_available_tools = (
None # Invalidate the cache when a tool is added
)
logger.bind(tag=TAG).debug(f"Registered MCP tool: {sanitized_name} (original: {tool_data['name']})")
self._cached_available_tools = None # Invalidate cache
async def get_next_id(self) -> int:
async with self.lock:
@ -96,64 +95,68 @@ class MCPClient:
self.call_results.pop(id)
async def _background_tool_refresh(conn):
"""Refreshes LLM tools in a separate thread to prevent blocking the network"""
try:
# Offload synchronous work to threads
await asyncio.to_thread(conn.func_handler.tool_manager.refresh_tools)
await asyncio.to_thread(conn.func_handler.current_support_functions)
logger.bind(tag=TAG).info("LLM tool definitions refreshed in background.")
except Exception as e:
logger.bind(tag=TAG).error(f"Background tool refresh failed: {e}")
async def send_mcp_message(conn, payload: dict):
"""Helper to send MCP messages, encapsulating common logic."""
"""Helper to send MCP messages"""
if not conn.features.get("mcp"):
logger.bind(tag=TAG).warning("客户端不支持MCP,无法发送MCP消息")
logger.bind(tag=TAG).warning("Client does not support MCP, skipping message")
return
message = json.dumps({"type": "mcp", "payload": payload})
try:
await conn.websocket.send(message)
logger.bind(tag=TAG).debug(f"成功发送MCP消息: {message}")
logger.bind(tag=TAG).debug(f"MCP message sent: {payload.get('method', 'response')}")
except Exception as e:
logger.bind(tag=TAG).error(f"发送MCP消息失败: {e}")
logger.bind(tag=TAG).error(f"Failed to send MCP message: {e}")
async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
"""处理MCP消息,包括初始化、工具列表和工具调用响应等"""
logger.bind(tag=TAG).debug(f"处理MCP消息: {str(payload)[:100]}")
"""Process incoming MCP messages"""
logger.bind(tag=TAG).debug("Processing incoming MCP payload...")
if not isinstance(payload, dict):
logger.bind(tag=TAG).error("MCP消息缺少payload字段或格式错误")
logger.bind(tag=TAG).error("MCP message missing payload or has invalid format")
return
# Handle result
# Handle result payloads
if "result" in payload:
result = payload["result"]
msg_id = int(payload.get("id", 0))
# Check for tool call response first
if msg_id in mcp_client.call_results:
logger.bind(tag=TAG).debug(
f"收到工具调用响应,ID: {msg_id}, 结果: {result}"
)
logger.bind(tag=TAG).debug(f"Received tool call response for ID: {msg_id}")
await mcp_client.resolve_call_result(msg_id, result)
return
if msg_id == 1: # mcpInitializeID
logger.bind(tag=TAG).debug("收到MCP初始化响应")
logger.bind(tag=TAG).debug("Received MCP initialization response")
server_info = result.get("serverInfo")
if isinstance(server_info, dict):
name = server_info.get("name")
version = server_info.get("version")
logger.bind(tag=TAG).debug(
f"客户端MCP服务器信息: name={name}, version={version}"
)
logger.bind(tag=TAG).info(f"Client MCP Server: {name} v{version}")
return
elif msg_id == 2: # mcpToolsListID
logger.bind(tag=TAG).debug("收到MCP工具列表响应")
logger.bind(tag=TAG).debug("Received MCP tools list response")
if isinstance(result, dict) and "tools" in result:
tools_data = result["tools"]
if not isinstance(tools_data, list):
logger.bind(tag=TAG).error("工具列表格式错误")
logger.bind(tag=TAG).error("Tool list format is invalid")
return
logger.bind(tag=TAG).info(
f"客户端设备支持的工具数量: {len(tools_data)}"
)
logger.bind(tag=TAG).info(f"Client device supports {len(tools_data)} tools")
for i, tool in enumerate(tools_data):
if not isinstance(tool, dict):
@ -177,175 +180,155 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
"inputSchema": input_schema,
}
await mcp_client.add_tool(new_tool)
logger.bind(tag=TAG).debug(f"客户端工具 #{i+1}: {name}")
# 替换所有工具描述中的工具名称
# Replace tool names in descriptions for consistency
for tool_data in mcp_client.tools.values():
if "description" in tool_data:
description = tool_data["description"]
# 遍历所有工具名称进行替换
for (
sanitized_name,
original_name,
) in mcp_client.name_mapping.items():
description = description.replace(
original_name, sanitized_name
)
for sanitized_name, original_name in mcp_client.name_mapping.items():
description = description.replace(original_name, sanitized_name)
tool_data["description"] = description
next_cursor = result.get("nextCursor", "")
if next_cursor:
logger.bind(tag=TAG).debug(f"有更多工具,nextCursor: {next_cursor}")
logger.bind(tag=TAG).debug(f"Paginating tools, nextCursor: {next_cursor}")
await send_mcp_tools_list_continue_request(conn, next_cursor)
else:
await mcp_client.set_ready(True)
logger.bind(tag=TAG).debug("所有工具已获取,MCP客户端准备就绪")
logger.bind(tag=TAG).info(f"All tools retrieved, MCP client ready. Available tools: {list(mcp_client.tools.keys())}")
# 刷新工具缓存,确保MCP工具被包含在函数列表中
# Launch tool refresh in background to prevent blocking
if hasattr(conn, "func_handler") and conn.func_handler:
conn.func_handler.tool_manager.refresh_tools()
conn.func_handler.current_support_functions()
asyncio.create_task(_background_tool_refresh(conn))
return
# Handle method calls (requests from the client)
# Handle incoming method requests from client
elif "method" in payload:
method = payload["method"]
logger.bind(tag=TAG).info(f"收到MCP客户端请求: {method}")
logger.bind(tag=TAG).info(f"Received MCP client request: {method}")
# Handle error payloads
elif "error" in payload:
error_data = payload["error"]
error_msg = error_data.get("message", "未知错误")
logger.bind(tag=TAG).error(f"收到MCP错误响应: {error_msg}")
error_msg = error_data.get("message", "Unknown error")
logger.bind(tag=TAG).error(f"Received MCP error response: {error_msg}")
msg_id = int(payload.get("id", 0))
if msg_id in mcp_client.call_results:
await mcp_client.reject_call_result(
msg_id, Exception(f"MCP错误: {error_msg}")
)
await mcp_client.reject_call_result(msg_id, Exception(f"MCP Error: {error_msg}"))
#async def send_mcp_initialize_message(conn):
# """Send MCP initialization message"""
# vision_url = get_vision_url(conn.config)
# auth = AuthToken(conn.config["server"]["auth_key"])
# token = auth.generate_token(conn.headers.get("device-id"))
#
# vision = {"url": vision_url, "token": token}
#
# payload = {
# "jsonrpc": "2.0",
# "id": 1,
# "method": "initialize",
# "params": {
# "protocolVersion": "2024-11-05",
# "capabilities": {
# "roots": {"listChanged": True},
# "sampling": {},
# "vision": vision,
# },
# "clientInfo": {"name": "XiaozhiClient", "version": "1.0.0"},
# },
# }
# logger.bind(tag=TAG).debug("Sending MCP initialize message...")
# await send_mcp_message(conn, payload)
async def send_mcp_initialize_message(conn):
"""发送MCP初始化消息"""
vision_url = get_vision_url(conn.config)
# 密钥生成token
auth = AuthToken(conn.config["server"]["auth_key"])
token = auth.generate_token(conn.headers.get("device-id"))
vision = {
"url": vision_url,
"token": token,
}
"""Simplified MCP initialization to prevent DNS/Auth hangs"""
# We are skipping get_vision_url and AuthToken generation for now
payload = {
"jsonrpc": "2.0",
"id": 1, # mcpInitializeID
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {
"roots": {"listChanged": True},
"sampling": {},
"vision": vision,
},
"clientInfo": {
"name": "XiaozhiClient",
"version": "1.0.0",
# Vision and Auth are omitted to test for network hangs
},
"clientInfo": {"name": "XiaozhiClient", "version": "1.0.0"},
},
}
logger.bind(tag=TAG).debug("发送MCP初始化消息")
logger.bind(tag=TAG).debug("Sending simplified MCP initialize message...")
await send_mcp_message(conn, payload)
async def send_mcp_tools_list_request(conn):
"""发送MCP工具列表请求"""
payload = {
"jsonrpc": "2.0",
"id": 2, # mcpToolsListID
"method": "tools/list",
}
logger.bind(tag=TAG).debug("发送MCP工具列表请求")
"""Send MCP tools list request"""
payload = {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}
logger.bind(tag=TAG).debug("Requesting MCP tool list...")
await send_mcp_message(conn, payload)
async def send_mcp_tools_list_continue_request(conn, cursor: str):
"""发送带有cursor的MCP工具列表请求"""
"""Send continuation request for tools list"""
payload = {
"jsonrpc": "2.0",
"id": 2, # mcpToolsListID (same ID for continuation)
"id": 2,
"method": "tools/list",
"params": {"cursor": cursor},
}
logger.bind(tag=TAG).info(f"发送带cursor的MCP工具列表请求: {cursor}")
logger.bind(tag=TAG).info(f"Continuing tool list request with cursor: {cursor}")
await send_mcp_message(conn, payload)
async def call_mcp_tool(
conn, mcp_client: MCPClient, tool_name: str, args: str = "{}", timeout: int = 30
):
"""
调用指定的工具,并等待响应
"""
async def call_mcp_tool(conn, mcp_client: MCPClient, tool_name: str, args: str = "{}", timeout: int = 30):
"""Call a specified MCP tool and await response"""
if not await mcp_client.is_ready():
raise RuntimeError("MCP客户端尚未准备就绪")
raise RuntimeError("MCP client is not ready yet")
if not mcp_client.has_tool(tool_name):
raise ValueError(f"工具 {tool_name} 不存在")
raise ValueError(f"Tool {tool_name} does not exist")
tool_call_id = await mcp_client.get_next_id()
result_future = asyncio.Future()
await mcp_client.register_call_result_future(tool_call_id, result_future)
# 处理参数
try:
if isinstance(args, str):
# 确保字符串是有效的JSON
if not args.strip():
arguments = {}
else:
try:
# 尝试直接解析
arguments = json.loads(args)
except json.JSONDecodeError:
# 如果解析失败,尝试合并多个JSON对象
try:
# 使用正则表达式匹配所有JSON对象
json_objects = re.findall(r"\{[^{}]*\}", args)
if len(json_objects) > 1:
# 合并所有JSON对象
merged_dict = {}
for json_str in json_objects:
try:
obj = json.loads(json_str)
if isinstance(obj, dict):
merged_dict.update(obj)
except json.JSONDecodeError:
continue
if merged_dict:
arguments = merged_dict
else:
raise ValueError(f"无法解析任何有效的JSON对象: {args}")
json_objects = re.findall(r"\{[^{}]*\}", args)
if len(json_objects) > 1:
merged_dict = {}
for json_str in json_objects:
try:
obj = json.loads(json_str)
if isinstance(obj, dict):
merged_dict.update(obj)
except json.JSONDecodeError:
continue
if merged_dict:
arguments = merged_dict
else:
raise ValueError(f"参数JSON解析失败: {args}")
except Exception as e:
logger.bind(tag=TAG).error(
f"参数JSON解析失败: {str(e)}, 原始参数: {args}"
)
raise ValueError(f"参数JSON解析失败: {str(e)}")
raise ValueError(f"Could not parse valid JSON from: {args}")
else:
raise ValueError(f"JSON parsing failed for args: {args}")
elif isinstance(args, dict):
arguments = args
else:
raise ValueError(f"参数类型错误,期望字符串或字典,实际类型: {type(args)}")
raise ValueError(f"Invalid args type: {type(args)}")
# 确保参数是字典类型
if not isinstance(arguments, dict):
raise ValueError(f"参数必须是字典类型,实际类型: {type(arguments)}")
raise ValueError(f"Arguments must be a dictionary, got: {type(arguments)}")
except Exception as e:
if not isinstance(e, ValueError):
raise ValueError(f"参数处理失败: {str(e)}")
raise ValueError(f"Argument processing failed: {str(e)}")
raise e
actual_name = mcp_client.name_mapping.get(tool_name, tool_name)
@ -356,33 +339,78 @@ async def call_mcp_tool(
"params": {"name": actual_name, "arguments": arguments},
}
logger.bind(tag=TAG).info(f"发送客户端mcp工具调用请求: {actual_name},参数: {args}")
logger.bind(tag=TAG).info(f"Initiating tool call: {actual_name} with args: {args}")
await send_mcp_message(conn, payload)
try:
# Wait for response or timeout
raw_result = await asyncio.wait_for(result_future, timeout=timeout)
logger.bind(tag=TAG).info(
f"客户端mcp工具调用 {actual_name} 成功,原始结果: {raw_result}"
)
logger.bind(tag=TAG).info(f"Tool call {actual_name} successful")
if isinstance(raw_result, dict):
if raw_result.get("isError") is True:
error_msg = raw_result.get(
"error", "工具调用返回错误,但未提供具体错误信息"
)
raise RuntimeError(f"工具调用错误: {error_msg}")
error_msg = raw_result.get("error", "No detailed error provided")
raise RuntimeError(f"Tool execution error: {error_msg}")
content = raw_result.get("content")
if isinstance(content, list) and len(content) > 0:
if isinstance(content[0], dict) and "text" in content[0]:
# 直接返回文本内容,不进行JSON解析
return content[0]["text"]
# 如果结果不是预期的格式,将其转换为字符串
result_text = content[0]["text"]
# Inject server time if this is the device status tool
if "get_device_status" in actual_name:
try:
status_data = json.loads(result_text)
if isinstance(status_data, dict):
status_data["server_timestamp"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
status_data["server_weekday"] = datetime.now().strftime("%A")
result_text = json.dumps(status_data, ensure_ascii=False)
except:
pass
return result_text
return str(raw_result)
except asyncio.TimeoutError:
await mcp_client.cleanup_call_result(tool_call_id)
raise TimeoutError("工具调用请求超时")
raise TimeoutError("The tool call request timed out")
except Exception as e:
await mcp_client.cleanup_call_result(tool_call_id)
raise e
async def sync_device_hardware_status(conn, tool_name="get_device_status"):
"""Helper to fetch hardware status (battery, volume, charging, brightness) via MCP"""
try:
logger.bind(tag=TAG).info(f"Initiating MCP hardware sync via {tool_name}...")
res = await call_mcp_tool(conn, conn.mcp_client, tool_name)
data = json.loads(res)
if isinstance(data, dict):
# 1. Battery Sync
battery_data = data.get("battery") or data
bat = battery_data.get("level") if isinstance(battery_data, dict) else battery_data
if bat is not None:
conn.mcp_battery = str(bat)
logger.bind(tag=TAG).info(f"MCP hardware sync - battery: {bat}%")
charging = battery_data.get("charging") if isinstance(battery_data, dict) else None
if charging is not None:
conn.mcp_charging = "charging" if charging else "not charging"
logger.bind(tag=TAG).info(f"MCP hardware sync - charging: {conn.mcp_charging}")
# 2. Volume Sync
audio_data = data.get("audio_speaker") or data.get("audio") or data
vol = audio_data.get("volume") if isinstance(audio_data, dict) else audio_data
if vol is not None:
conn.mcp_volume = str(vol)
logger.bind(tag=TAG).info(f"MCP hardware sync - volume: {vol}%")
# 3. Brightness Sync
screen_data = data.get("screen") or data
bright = screen_data.get("brightness") if isinstance(screen_data, dict) else None
if bright is not None:
conn.mcp_brightness = str(bright)
logger.bind(tag=TAG).info(f"MCP hardware sync - brightness: {bright}%")
if bat is None and vol is None:
logger.bind(tag=TAG).warning(f"MCP hardware sync - no primary data found in response: {data}")
except Exception as e:
logger.bind(tag=TAG).warning(f"MCP hardware status sync failed: {e}")

View file

@ -1,4 +1,4 @@
"""MCP接入点客户端定义"""
"""MCP endpoint client definition"""
import asyncio
from concurrent.futures import Future
@ -10,7 +10,7 @@ logger = setup_logging()
class MCPEndpointClient:
"""MCP接入点客户端,用于管理MCP接入点状态和工具"""
"""MCP endpoint client, used to manage MCP endpoint status and tools"""
def __init__(self, conn=None):
self.conn = conn
@ -21,7 +21,7 @@ class MCPEndpointClient:
self.next_id = 1
self.lock = asyncio.Lock()
self._cached_available_tools = None # Cache for get_available_tools
self.websocket = None # WebSocket连接
self.websocket = None # WebSocket connection
def has_tool(self, name: str) -> bool:
return name in self.tools
@ -95,18 +95,18 @@ class MCPEndpointClient:
self.call_results.pop(id)
def set_websocket(self, websocket):
"""设置WebSocket连接"""
"""Set WebSocket connection"""
self.websocket = websocket
async def send_message(self, message: str):
"""发送消息到MCP接入点"""
"""Send message to MCP endpoint"""
if self.websocket:
await self.websocket.send(message)
else:
raise RuntimeError("WebSocket连接未建立")
raise RuntimeError("WebSocket connection not established")
async def close(self):
"""关闭WebSocket连接"""
"""Close WebSocket connection"""
if self.websocket:
await self.websocket.close()
self.websocket = None

View file

@ -1,4 +1,4 @@
"""MCP接入点工具执行器"""
"""MCP endpoint tool executor"""
from typing import Dict, Any
from ..base import ToolType, ToolDefinition, ToolExecutor
@ -7,7 +7,7 @@ from .mcp_endpoint_handler import call_mcp_endpoint_tool
class MCPEndpointExecutor(ToolExecutor):
"""MCP接入点工具执行器"""
"""MCP endpoint tool executor"""
def __init__(self, conn):
self.conn = conn
@ -15,26 +15,26 @@ class MCPEndpointExecutor(ToolExecutor):
async def execute(
self, conn, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
"""执行MCP接入点工具"""
"""Execute MCP endpoint tool"""
if not hasattr(conn, "mcp_endpoint_client") or not conn.mcp_endpoint_client:
return ActionResponse(
action=Action.ERROR,
response="MCP接入点客户端未初始化",
response="MCP endpoint client not initialized",
)
if not await conn.mcp_endpoint_client.is_ready():
return ActionResponse(
action=Action.ERROR,
response="MCP接入点客户端未准备就绪",
response="MCP endpoint client not ready",
)
try:
# 转换参数为JSON字符串
# Convert parameters to JSON string
import json
args_str = json.dumps(arguments) if arguments else "{}"
# 调用MCP接入点工具
# Call MCP endpoint tool
result = await call_mcp_endpoint_tool(
conn.mcp_endpoint_client, tool_name, args_str
)
@ -46,7 +46,7 @@ class MCPEndpointExecutor(ToolExecutor):
except Exception as e:
pass
# 视觉大模型不经过二次LLM处理
# Visual large models do not go through secondary LLM processing
if (
resultJson is not None
and isinstance(resultJson, dict)
@ -65,7 +65,7 @@ class MCPEndpointExecutor(ToolExecutor):
return ActionResponse(action=Action.ERROR, response=str(e))
def get_tools(self) -> Dict[str, ToolDefinition]:
"""获取所有MCP接入点工具"""
"""Get all MCP endpoint tools"""
if (
not hasattr(self.conn, "mcp_endpoint_client")
or not self.conn.mcp_endpoint_client
@ -87,7 +87,7 @@ class MCPEndpointExecutor(ToolExecutor):
return tools
def has_tool(self, tool_name: str) -> bool:
"""检查是否有指定的MCP接入点工具"""
"""Check if there is a specified MCP endpoint tool"""
if (
not hasattr(self.conn, "mcp_endpoint_client")
or not self.conn.mcp_endpoint_client

View file

@ -1,4 +1,4 @@
"""MCP接入点处理器"""
"""MCP endpoint handler"""
import json
import asyncio
@ -12,8 +12,8 @@ logger = setup_logging()
async def connect_mcp_endpoint(mcp_endpoint_url: str, conn=None) -> MCPEndpointClient:
"""连接到MCP接入点"""
if not mcp_endpoint_url or "你的" in mcp_endpoint_url or mcp_endpoint_url == "null":
"""Connect to MCP endpoint"""
if not mcp_endpoint_url or "your" in mcp_endpoint_url or mcp_endpoint_url == "null":
return None
try:
@ -22,82 +22,82 @@ async def connect_mcp_endpoint(mcp_endpoint_url: str, conn=None) -> MCPEndpointC
mcp_client = MCPEndpointClient(conn)
mcp_client.set_websocket(websocket)
# 启动消息监听器
# Start message listener
asyncio.create_task(_message_listener(mcp_client))
# 发送初始化消息
# Send initialization message
await send_mcp_endpoint_initialize(mcp_client)
# 发送初始化完成通知
# Send initialization completion notification
await send_mcp_endpoint_notification(mcp_client, "notifications/initialized")
# 获取工具列表
# Get tools list
await send_mcp_endpoint_tools_list(mcp_client)
logger.bind(tag=TAG).info("MCP接入点连接成功")
logger.bind(tag=TAG).info("MCP endpoint connection successful")
return mcp_client
except Exception as e:
logger.bind(tag=TAG).error(f"连接MCP接入点失败: {e}")
logger.bind(tag=TAG).error(f"Connect to MCP endpoint failed: {e}")
return None
async def _message_listener(mcp_client: MCPEndpointClient):
"""监听MCP接入点消息"""
"""Listen to MCP endpoint messages"""
try:
async for message in mcp_client.websocket:
await handle_mcp_endpoint_message(mcp_client, message)
except websockets.exceptions.ConnectionClosed:
logger.bind(tag=TAG).info("MCP接入点连接已关闭")
logger.bind(tag=TAG).info("MCP endpoint connection closed")
except Exception as e:
logger.bind(tag=TAG).error(f"MCP接入点消息监听器错误: {e}")
logger.bind(tag=TAG).error(f"MCP endpoint message listener error: {e}")
finally:
await mcp_client.set_ready(False)
async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: str):
"""处理MCP接入点消息"""
"""Handle MCP endpoint message"""
try:
payload = json.loads(message)
logger.bind(tag=TAG).debug(f"收到MCP接入点消息: {payload}")
logger.bind(tag=TAG).debug(f"Received MCP endpoint message: {payload}")
if not isinstance(payload, dict):
logger.bind(tag=TAG).error("MCP接入点消息格式错误")
logger.bind(tag=TAG).error("MCP endpoint message format error")
return
# Handle result
if "result" in payload:
result = payload["result"]
# 安全地获取消息ID,如果为None则使用0
# Safely get message ID, use 0 if None
msg_id_raw = payload.get("id")
msg_id = int(msg_id_raw) if msg_id_raw is not None else 0
# Check for tool call response first
if msg_id in mcp_client.call_results:
logger.bind(tag=TAG).debug(
f"收到工具调用响应,ID: {msg_id}, 结果: {result}"
f"Received tool call response, ID: {msg_id}, result: {result}"
)
await mcp_client.resolve_call_result(msg_id, result)
return
if msg_id == 1: # mcpInitializeID
logger.bind(tag=TAG).debug("收到MCP接入点初始化响应")
logger.bind(tag=TAG).debug("Received MCP endpoint initialization response")
if result is not None and isinstance(result, dict):
server_info = result.get("serverInfo")
if isinstance(server_info, dict):
name = server_info.get("name")
version = server_info.get("version")
logger.bind(tag=TAG).info(
f"MCP接入点服务器信息: name={name}, version={version}"
f"MCP endpoint server information: name={name}, version={version}"
)
else:
logger.bind(tag=TAG).warning(
"MCP接入点初始化响应结果为空或格式错误"
"MCP endpoint initialization response result is empty or format error"
)
return
elif msg_id == 2: # mcpToolsListID
logger.bind(tag=TAG).debug("收到MCP接入点工具列表响应")
logger.bind(tag=TAG).debug("Received MCP endpoint tools list response")
if (
result is not None
and isinstance(result, dict)
@ -105,11 +105,11 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
):
tools_data = result["tools"]
if not isinstance(tools_data, list):
logger.bind(tag=TAG).error("工具列表格式错误")
logger.bind(tag=TAG).error("Tools list format error")
return
logger.bind(tag=TAG).info(
f"MCP接入点支持的工具数量: {len(tools_data)}"
f"MCP endpoint supports {len(tools_data)} tools"
)
for i, tool in enumerate(tools_data):
@ -142,13 +142,13 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
"inputSchema": input_schema,
}
await mcp_client.add_tool(new_tool)
logger.bind(tag=TAG).debug(f"MCP接入点工具 #{i+1}: {name}")
logger.bind(tag=TAG).debug(f"MCP endpoint tool #{i+1}: {name}")
# 替换所有工具描述中的工具名称
# Replace all tool names in tool descriptions
for tool_data in mcp_client.tools.values():
if "description" in tool_data:
description = tool_data["description"]
# 遍历所有工具名称进行替换
# Iterate through all tool names for replacement
for (
sanitized_name,
original_name,
@ -163,7 +163,7 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
)
if next_cursor:
logger.bind(tag=TAG).info(
f"有更多工具,nextCursor: {next_cursor}"
f"More tools available, nextCursor: {next_cursor}"
)
await send_mcp_endpoint_tools_list_continue(
mcp_client, next_cursor
@ -171,10 +171,10 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
else:
await mcp_client.set_ready(True)
logger.bind(tag=TAG).info(
"所有MCP接入点工具已获取,客户端准备就绪"
"All MCP endpoint tools have been retrieved, client is ready"
)
# 刷新工具缓存,确保MCP接入点工具被包含在函数列表中
# Refresh tool cache to ensure MCP endpoint tools are included in the function list
if (
hasattr(mcp_client, "conn")
and mcp_client.conn
@ -185,44 +185,44 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
mcp_client.conn.func_handler.current_support_functions()
logger.bind(tag=TAG).info(
f"MCP接入点工具获取完成,共 {len(mcp_client.tools)} 个工具"
f"MCP endpoint tools retrieved, total {len(mcp_client.tools)} tools"
)
else:
logger.bind(tag=TAG).warning(
"MCP接入点工具列表响应结果为空或格式错误"
"MCP endpoint tools list response result is empty or format error"
)
return
# Handle method calls (requests from the endpoint)
elif "method" in payload:
method = payload["method"]
logger.bind(tag=TAG).info(f"收到MCP接入点请求: {method}")
logger.bind(tag=TAG).info(f"Received MCP endpoint request: {method}")
elif "error" in payload:
error_data = payload["error"]
error_msg = error_data.get("message", "未知错误")
logger.bind(tag=TAG).error(f"收到MCP接入点错误响应: {error_msg}")
error_msg = error_data.get("message", "Unknown error")
logger.bind(tag=TAG).error(f"Received MCP endpoint error response: {error_msg}")
# 安全地获取消息ID,如果为None则使用0
# Safely get message ID, use 0 if None
msg_id_raw = payload.get("id")
msg_id = int(msg_id_raw) if msg_id_raw is not None else 0
if msg_id in mcp_client.call_results:
await mcp_client.reject_call_result(
msg_id, Exception(f"MCP接入点错误: {error_msg}")
msg_id, Exception(f"MCP endpoint error: {error_msg}")
)
except json.JSONDecodeError as e:
logger.bind(tag=TAG).error(f"MCP接入点消息JSON解析失败: {e}")
logger.bind(tag=TAG).error(f"MCP endpoint message JSON parsing failed: {e}")
except Exception as e:
logger.bind(tag=TAG).error(f"处理MCP接入点消息时出错: {e}")
logger.bind(tag=TAG).error(f"Error processing MCP endpoint message: {e}")
import traceback
logger.bind(tag=TAG).error(f"错误详情: {traceback.format_exc()}")
logger.bind(tag=TAG).error(f"Error details: {traceback.format_exc()}")
async def send_mcp_endpoint_initialize(mcp_client: MCPEndpointClient):
"""发送MCP接入点初始化消息"""
"""Send MCP endpoint initialization message"""
payload = {
"jsonrpc": "2.0",
"id": 1, # mcpInitializeID
@ -240,38 +240,38 @@ async def send_mcp_endpoint_initialize(mcp_client: MCPEndpointClient):
},
}
message = json.dumps(payload)
logger.bind(tag=TAG).info("发送MCP接入点初始化消息")
logger.bind(tag=TAG).info("Sending MCP endpoint initialization message")
await mcp_client.send_message(message)
async def send_mcp_endpoint_notification(mcp_client: MCPEndpointClient, method: str):
"""发送MCP接入点通知消息"""
"""Send MCP endpoint notification message"""
payload = {
"jsonrpc": "2.0",
"method": method,
"params": {},
}
message = json.dumps(payload)
logger.bind(tag=TAG).debug(f"发送MCP接入点通知: {method}")
logger.bind(tag=TAG).debug(f"Sending MCP endpoint notification: {method}")
await mcp_client.send_message(message)
async def send_mcp_endpoint_tools_list(mcp_client: MCPEndpointClient):
"""发送MCP接入点工具列表请求"""
"""Send MCP endpoint tools list request"""
payload = {
"jsonrpc": "2.0",
"id": 2, # mcpToolsListID
"method": "tools/list",
}
message = json.dumps(payload)
logger.bind(tag=TAG).debug("发送MCP接入点工具列表请求")
logger.bind(tag=TAG).debug("Sending MCP endpoint tools list request")
await mcp_client.send_message(message)
async def send_mcp_endpoint_tools_list_continue(
mcp_client: MCPEndpointClient, cursor: str
):
"""发送带有cursor的MCP接入点工具列表请求"""
"""Send MCP endpoint tools list request with cursor"""
payload = {
"jsonrpc": "2.0",
"id": 2, # mcpToolsListID (same ID for continuation)
@ -279,7 +279,7 @@ async def send_mcp_endpoint_tools_list_continue(
"params": {"cursor": cursor},
}
message = json.dumps(payload)
logger.bind(tag=TAG).info(f"发送带cursor的MCP接入点工具列表请求: {cursor}")
logger.bind(tag=TAG).info(f"Sending MCP endpoint tools list request with cursor: {cursor}")
await mcp_client.send_message(message)
@ -287,35 +287,35 @@ async def call_mcp_endpoint_tool(
mcp_client: MCPEndpointClient, tool_name: str, args: str = "{}", timeout: int = 30
):
"""
调用指定的MCP接入点工具,并等待响应
Call the specified MCP endpoint tool and wait for the response
"""
if not await mcp_client.is_ready():
raise RuntimeError("MCP接入点客户端尚未准备就绪")
raise RuntimeError("MCP endpoint client is not ready")
if not mcp_client.has_tool(tool_name):
raise ValueError(f"工具 {tool_name} 不存在")
raise ValueError(f"Tool {tool_name} does not exist")
tool_call_id = await mcp_client.get_next_id()
result_future = asyncio.Future()
await mcp_client.register_call_result_future(tool_call_id, result_future)
# 处理参数
# Process arguments
try:
if isinstance(args, str):
# 确保字符串是有效的JSON
# Ensure the string is a valid JSON
if not args.strip():
arguments = {}
else:
try:
# 尝试直接解析
# Try direct parsing
arguments = json.loads(args)
except json.JSONDecodeError:
# 如果解析失败,尝试合并多个JSON对象
# If parsing fails, try merging multiple JSON objects
try:
# 使用正则表达式匹配所有JSON对象
# Use regex to match all JSON objects
json_objects = re.findall(r"\{[^{}]*\}", args)
if len(json_objects) > 1:
# 合并所有JSON对象
# Merge all JSON objects
merged_dict = {}
for json_str in json_objects:
try:
@ -327,26 +327,26 @@ async def call_mcp_endpoint_tool(
if merged_dict:
arguments = merged_dict
else:
raise ValueError(f"无法解析任何有效的JSON对象: {args}")
raise ValueError(f"Unable to parse any valid JSON objects: {args}")
else:
raise ValueError(f"参数JSON解析失败: {args}")
raise ValueError(f"Parameter JSON parsing failed: {args}")
except Exception as e:
logger.bind(tag=TAG).error(
f"参数JSON解析失败: {str(e)}, 原始参数: {args}"
f"Parameter JSON parsing failed: {str(e)}, original parameter: {args}"
)
raise ValueError(f"参数JSON解析失败: {str(e)}")
raise ValueError(f"Parameter JSON parsing failed: {str(e)}")
elif isinstance(args, dict):
arguments = args
else:
raise ValueError(f"参数类型错误,期望字符串或字典,实际类型: {type(args)}")
raise ValueError(f"Parameter type error, expected string or dictionary, actual type: {type(args)}")
# 确保参数是字典类型
# Ensure parameters are dictionary type
if not isinstance(arguments, dict):
raise ValueError(f"参数必须是字典类型,实际类型: {type(arguments)}")
raise ValueError(f"Parameters must be dictionary type, actual type: {type(arguments)}")
except Exception as e:
if not isinstance(e, ValueError):
raise ValueError(f"参数处理失败: {str(e)}")
raise ValueError(f"Parameter processing failed: {str(e)}")
raise e
actual_name = mcp_client.name_mapping.get(tool_name, tool_name)
@ -359,7 +359,7 @@ async def call_mcp_endpoint_tool(
message = json.dumps(payload)
logger.bind(tag=TAG).info(
f"发送MCP接入点工具调用请求: {actual_name},参数: {json.dumps(arguments, ensure_ascii=False)}"
f"Sending MCP endpoint tool call request: {actual_name}, parameters: {json.dumps(arguments, ensure_ascii=False)}"
)
await mcp_client.send_message(message)
@ -367,26 +367,26 @@ async def call_mcp_endpoint_tool(
# Wait for response or timeout
raw_result = await asyncio.wait_for(result_future, timeout=timeout)
logger.bind(tag=TAG).info(
f"MCP接入点工具调用 {actual_name} 成功,原始结果: {raw_result}"
f"MCP endpoint tool call {actual_name} successful, raw result: {raw_result}"
)
if isinstance(raw_result, dict):
if raw_result.get("isError") is True:
error_msg = raw_result.get(
"error", "工具调用返回错误,但未提供具体错误信息"
"error", "Tool call returned error, but no specific error information provided"
)
raise RuntimeError(f"工具调用错误: {error_msg}")
raise RuntimeError(f"Tool call error: {error_msg}")
content = raw_result.get("content")
if isinstance(content, list) and len(content) > 0:
if isinstance(content[0], dict) and "text" in content[0]:
# 直接返回文本内容,不进行JSON解析
# Directly return text content, no JSON parsing
return content[0]["text"]
# 如果结果不是预期的格式,将其转换为字符串
# If the result is not in the expected format, convert it to a string
return str(raw_result)
except asyncio.TimeoutError:
await mcp_client.cleanup_call_result(tool_call_id)
raise TimeoutError("工具调用请求超时")
await mcp_client.cleanup_call_result(tool_call_id) # Clean up call result
raise TimeoutError("Tool call request timed out")
except Exception as e:
await mcp_client.cleanup_call_result(tool_call_id)
raise e

View file

@ -1,4 +1,4 @@
"""服务端MCP客户端"""
"""Server MCP client"""
from __future__ import annotations
@ -24,13 +24,13 @@ TAG = __name__
class ServerMCPClient:
"""服务端MCP客户端,用于连接和管理MCP服务"""
"""Server MCP client, used to connect and manage MCP services"""
def __init__(self, config: Dict[str, Any]):
"""初始化服务端MCP客户端
"""Initialize the server MCP client
Args:
config: MCP服务配置字典
config: MCP server configuration dictionary
"""
self.logger = setup_logging()
self.config = config
@ -51,7 +51,7 @@ class ServerMCPClient:
logging_callback: LoggingFnT | None = None,
message_handler: MessageHandlerFnT | None = None,
client_info: Implementation | None = None):
"""初始化MCP客户端连接"""
"""Initialize the MCP client connection"""
if self._worker_task:
return
@ -67,11 +67,10 @@ class ServerMCPClient:
await self._ready_evt.wait()
self.logger.bind(tag=TAG).info(
f"服务端MCP客户端已连接,可用工具: {[name for name in self.name_mapping.values()]}"
)
f"Server MCP client connected, available tools: {[name for name in self.name_mapping.values()]}")
async def cleanup(self):
"""清理MCP客户端资源"""
"""Cleanup MCP client resources"""
if not self._worker_task:
return
@ -79,26 +78,26 @@ class ServerMCPClient:
try:
await asyncio.wait_for(self._worker_task, timeout=20)
except (asyncio.TimeoutError, Exception) as e:
self.logger.bind(tag=TAG).error(f"服务端MCP客户端关闭错误: {e}")
self.logger.bind(tag=TAG).error(f"Server MCP client shutdown error: {e}")
finally:
self._worker_task = None
def has_tool(self, name: str) -> bool:
"""检查是否包含指定工具
"""Check if the specified tool exists
Args:
name: 工具名称
name: Tool name
Returns:
bool: 是否包含该工具
bool: Whether the tool exists
"""
return name in self.tools_dict
def get_available_tools(self) -> List[Dict[str, Any]]:
"""获取所有可用工具的定义
"""Get the definition of all available tools
Returns:
List[Dict[str, Any]]: 工具定义列表
List[Dict[str, Any]]: List of tool definitions
"""
return [
{
@ -113,23 +112,23 @@ class ServerMCPClient:
]
async def call_tool(self, name: str, arguments: dict, read_timeout_seconds: timedelta | None = None, progress_callback: ProgressFnT | None = None, *, meta: dict[str, Any] | None = None) -> Any:
"""调用指定工具
"""Call the specified tool
Args:
name: 工具名称
arguments: 工具参数
name: Tool name
arguments: Tool arguments
read_timeout_seconds:
progress_callback: 进度回调函数
progress_callback: Progress callback function
meta:
Returns:
Any: 工具执行结果
Any: Tool execution result
Raises:
RuntimeError: 客户端未初始化时抛出
RuntimeError: When the client is not initialized
"""
if not self.session:
raise RuntimeError("服务端MCP客户端未初始化")
raise RuntimeError("Server MCP client not initialized")
real_name = self.name_mapping.get(name, name)
loop = self._worker_task.get_loop()
@ -142,24 +141,24 @@ class ServerMCPClient:
return await asyncio.wrap_future(fut)
def is_connected(self) -> bool:
"""检查MCP客户端是否连接正常
"""Check if the MCP client is connected normally
Returns:
bool: 如果客户端已连接并正常工作,返回True,否则返回False
bool: If the client is connected and working normally, return True, otherwise return False
"""
# 检查工作任务是否存在
# Check if the worker task exists
if self._worker_task is None:
return False
# 检查工作任务是否已经完成或取消
# Check if the worker task is done or cancelled
if self._worker_task.done():
return False
# 检查会话是否存在
# Check if the session exists
if self.session is None:
return False
# 所有检查都通过,连接正常
# All checks passed, connection is normal
return True
async def _worker(self, read_timeout_seconds: timedelta | None = None,
@ -169,10 +168,10 @@ class ServerMCPClient:
logging_callback: LoggingFnT | None = None,
message_handler: MessageHandlerFnT | None = None,
client_info: Implementation | None = None):
"""MCP客户端工作协程"""
"""MCP client worker coroutine"""
async with AsyncExitStack() as stack:
try:
# 建立 StdioClient
# Create StdioClient
if "command" in self.config:
cmd = (
shutil.which("npx")
@ -190,19 +189,19 @@ class ServerMCPClient:
)
read_stream, write_stream = stdio_r, stdio_w
# 建立SSEClient
# Create SSEClient
elif "url" in self.config:
headers = dict(self.config.get("headers", {}))
# TODO 兼容旧版本
# TODO: compatibility with old version
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'")
self.logger.bind(tag=TAG).warning(f"You are using the deprecated configuration API_ACCESS_TOKEN, please set API_ACCESS_TOKEN directly in headers in .mcp_server_settings.json, for example 'Authorization': 'Bearer API_ACCESS_TOKEN'")
# 根据transport类型选择不同的客户端,默认为SSE
# Select different clients based on transport type, default is SSE
transport_type = self.config.get("transport", "sse")
if transport_type == "streamable-http" or transport_type == "http":
# 使用 Streamable HTTP 传输
# Use Streamable HTTP transport
http_r, http_w, get_session_id = await stack.enter_async_context(
streamablehttp_client(
url=self.config["url"],
@ -214,7 +213,7 @@ class ServerMCPClient:
)
read_stream, write_stream = http_r, http_w
else:
# 使用传统的 SSE 传输
# Use traditional SSE transport
sse_r, sse_w = await stack.enter_async_context(
sse_client(
url=self.config["url"],
@ -226,7 +225,7 @@ class ServerMCPClient:
read_stream, write_stream = sse_r, sse_w
else:
raise ValueError("MCP客户端配置必须包含'command'或'url'")
raise ValueError("MCP client configuration must contain 'command' or 'url'")
self.session = await stack.enter_async_context(
ClientSession(
@ -243,7 +242,7 @@ class ServerMCPClient:
)
await self.session.initialize()
# 获取工具
# Get tools
self.tools = (await self.session.list_tools()).tools
for t in self.tools:
sanitized = sanitize_tool_name(t.name)
@ -252,10 +251,10 @@ class ServerMCPClient:
self._ready_evt.set()
# 挂起等待关闭
# Suspend and wait for shutdown
await self._shutdown_evt.wait()
except Exception as e:
self.logger.bind(tag=TAG).error(f"服务端MCP客户端工作协程错误: {e}")
self.logger.bind(tag=TAG).error(f"MCP client worker coroutine error: {e}")
self._ready_evt.set()
raise

View file

@ -1,4 +1,4 @@
"""服务端MCP工具执行器"""
"""Server MCP tool executor"""
from typing import Dict, Any, Optional
from ..base import ToolType, ToolDefinition, ToolExecutor
@ -7,7 +7,7 @@ from .mcp_manager import ServerMCPManager
class ServerMCPExecutor(ToolExecutor):
"""服务端MCP工具执行器"""
"""Server MCP tool executor"""
def __init__(self, conn):
self.conn = conn
@ -15,7 +15,7 @@ class ServerMCPExecutor(ToolExecutor):
self._initialized = False
async def initialize(self):
"""初始化MCP管理器"""
"""Initialize MCP manager"""
if not self._initialized:
self.mcp_manager = ServerMCPManager(self.conn)
self._initialized = True
@ -24,15 +24,15 @@ class ServerMCPExecutor(ToolExecutor):
async def execute(
self, conn, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
"""执行服务端MCP工具"""
"""Execute server MCP tool"""
if not self._initialized or not self.mcp_manager:
return ActionResponse(
action=Action.ERROR,
response="MCP管理器未初始化",
response="MCP manager not initialized",
)
try:
# 移除mcp_前缀(如果有)
# Remove mcp_ prefix (if any)
actual_tool_name = tool_name
if tool_name.startswith("mcp_"):
actual_tool_name = tool_name[4:]
@ -53,7 +53,7 @@ class ServerMCPExecutor(ToolExecutor):
)
def get_tools(self) -> Dict[str, ToolDefinition]:
"""获取所有服务端MCP工具"""
"""Get all server MCP tools"""
if not self._initialized or not self.mcp_manager:
return {}
@ -72,11 +72,11 @@ class ServerMCPExecutor(ToolExecutor):
return tools
def has_tool(self, tool_name: str) -> bool:
"""检查是否有指定的服务端MCP工具"""
"""Check if there is a specified server MCP tool"""
if not self._initialized or not self.mcp_manager:
return False
# 移除mcp_前缀(如果有)
# Remove mcp_ prefix (if any)
actual_tool_name = tool_name
if tool_name.startswith("mcp_"):
actual_tool_name = tool_name[4:]
@ -84,6 +84,6 @@ class ServerMCPExecutor(ToolExecutor):
return self.mcp_manager.is_mcp_tool(actual_tool_name)
async def cleanup(self):
"""清理MCP连接"""
"""Cleanup MCP connection"""
if self.mcp_manager:
await self.mcp_manager.cleanup_all()

View file

@ -1,4 +1,4 @@
"""服务端MCP管理器"""
"""Server MCP manager"""
import asyncio
import os
@ -16,23 +16,23 @@ logger = setup_logging()
class ServerMCPManager:
"""管理多个服务端MCP服务的集中管理器"""
"""Manage multiple server MCP services"""
def __init__(self, conn) -> None:
"""初始化MCP管理器"""
"""Initialize MCP manager"""
self.conn = conn
self.config_path = get_project_dir() + "data/.mcp_server_settings.json"
if not os.path.exists(self.config_path):
self.config_path = ""
logger.bind(tag=TAG).warning(
f"请检查mcp服务配置文件:data/.mcp_server_settings.json"
f"MCP server config file not found: {self.config_path}"
)
self.clients: Dict[str, ServerMCPClient] = {}
self.tools = []
self._init_lock = asyncio.Lock()
def load_config(self) -> Dict[str, Any]:
"""加载MCP服务配置"""
"""Load MCP server config"""
if len(self.config_path) == 0:
return {}
@ -47,16 +47,16 @@ class ServerMCPManager:
return {}
async def _init_server(self, name: str, srv_config: Dict[str, Any]):
"""初始化单个MCP服务"""
"""Initialize single MCP server"""
client = None
try:
# 初始化服务端MCP客户端
logger.bind(tag=TAG).info(f"初始化服务端MCP客户端: {name}")
# Initialize server MCP client
logger.bind(tag=TAG).info(f"Initialize server MCP client: {name}")
client = ServerMCPClient(srv_config)
# 设置超时时间10秒
# Set timeout to 10 seconds
await asyncio.wait_for(client.initialize(logging_callback=self.logging_callback), timeout=10)
# 使用锁保护共享状态的修改
# Use lock to protect shared state modification
async with self._init_lock:
self.clients[name] = client
client_tools = client.get_available_tools()
@ -76,7 +76,7 @@ class ServerMCPManager:
await client.cleanup()
async def initialize_servers(self) -> None:
"""初始化所有MCP服务"""
"""Initialize all MCP servers"""
config = self.load_config()
tasks = []
for name, srv_config in config.items():
@ -91,19 +91,19 @@ class ServerMCPManager:
if tasks:
await asyncio.gather(*tasks)
# 输出当前支持的服务端MCP工具列表
# Output the list of supported server MCP tools
if hasattr(self.conn, "func_handler") and self.conn.func_handler:
# 刷新工具缓存以确保服务端MCP工具被正确加载
# Refresh tool cache to ensure server MCP tools are correctly loaded
if hasattr(self.conn.func_handler, "tool_manager"):
self.conn.func_handler.tool_manager.refresh_tools()
self.conn.func_handler.current_support_functions()
def get_all_tools(self) -> List[Dict[str, Any]]:
"""获取所有服务的工具function定义"""
"""Get all tools function definitions"""
return self.tools
def is_mcp_tool(self, tool_name: str) -> bool:
"""检查是否是MCP工具"""
"""Check if it is an MCP tool"""
for tool in self.tools:
if (
tool.get("function") is not None
@ -113,13 +113,13 @@ class ServerMCPManager:
return False
async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
"""执行工具调用,失败时会尝试重新连接"""
logger.bind(tag=TAG).info(f"执行服务端MCP工具 {tool_name},参数: {arguments}")
"""Execute tool call, retry when failed"""
logger.bind(tag=TAG).info(f"Execute server MCP tool {tool_name}, arguments: {arguments}")
max_retries = 3 # 最大重试次数
retry_interval = 2 # 重试间隔(秒)
max_retries = 3 # Maximum retry times
retry_interval = 2 # Retry interval (seconds)
# 找到对应的客户端
# Find the corresponding client
client_name = None
target_client = None
for name, client in self.clients.items():
@ -129,30 +129,30 @@ class ServerMCPManager:
break
if not target_client:
raise ValueError(f"工具 {tool_name} 在任意MCP服务中未找到")
raise ValueError(f"Tool {tool_name} not found in any MCP server")
# 带重试机制的工具调用
# Tool call with retry mechanism
for attempt in range(max_retries):
try:
return await target_client.call_tool(tool_name, arguments, progress_callback=self.progress_callback)
except Exception as e:
# 最后一次尝试失败时直接抛出异常
# If the last attempt fails, throw the exception directly
if attempt == max_retries - 1:
raise
logger.bind(tag=TAG).warning(
f"执行工具 {tool_name} 失败 (尝试 {attempt+1}/{max_retries}): {e}"
f"Failed to execute tool {tool_name} (attempt {attempt+1}/{max_retries}): {e}"
)
# 尝试重新连接
# Try to reconnect before retry
logger.bind(tag=TAG).info(
f"重试前尝试重新连接 MCP 客户端 {client_name}"
f"Before retry, try to reconnect MCP client {client_name}"
)
try:
# 关闭旧的连接
# Close the old connection
await target_client.cleanup()
# 重新初始化客户端
# Reinitialize the client
config = self.load_config()
if client_name in config:
client = ServerMCPClient(config[client_name])
@ -160,7 +160,7 @@ class ServerMCPManager:
self.clients[client_name] = client
target_client = client
logger.bind(tag=TAG).info(
f"成功重新连接 MCP 客户端: {client_name}"
f"Successfully reconnected MCP client: {client_name}"
)
else:
logger.bind(tag=TAG).error(
@ -171,21 +171,21 @@ class ServerMCPManager:
f"Failed to reconnect MCP client {client_name}: {reconnect_error}"
)
# 等待一段时间再重试
# Wait for a while before retrying
await asyncio.sleep(retry_interval)
async def cleanup_all(self) -> None:
"""关闭所有 MCP客户端"""
"""Close all MCP clients"""
for name, client in list(self.clients.items()):
try:
if hasattr(client, "cleanup"):
await asyncio.wait_for(client.cleanup(), timeout=20)
logger.bind(tag=TAG).info(f"服务端MCP客户端已关闭: {name}")
logger.bind(tag=TAG).info(f"Server MCP client closed: {name}")
except (asyncio.TimeoutError, Exception) as e:
logger.bind(tag=TAG).error(f"关闭服务端MCP客户端 {name} 时出错: {e}")
logger.bind(tag=TAG).error(f"Failed to close MCP client {name}: {e}")
self.clients.clear()
# 可选回调方法
# Optional callback methods
async def logging_callback(self, params: LoggingMessageNotificationParams):
logger.bind(tag=TAG).info(f"[Server Log - {params.level.upper()}] {params.data}")

View file

@ -1,4 +1,4 @@
"""服务端插件工具执行器"""
"""Server plugin tool executor"""
from typing import Dict, Any
from ..base import ToolType, ToolDefinition, ToolExecutor
@ -6,7 +6,7 @@ from plugins_func.register import all_function_registry, Action, ActionResponse
class ServerPluginExecutor(ToolExecutor):
"""服务端插件工具执行器"""
"""Server plugin tool executor"""
def __init__(self, conn):
self.conn = conn
@ -15,18 +15,18 @@ class ServerPluginExecutor(ToolExecutor):
async def execute(
self, conn, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
"""执行服务端插件工具"""
"""Execute server plugin tool"""
func_item = all_function_registry.get(tool_name)
if not func_item:
return ActionResponse(
action=Action.NOTFOUND, response=f"插件函数 {tool_name} 不存在"
action=Action.NOTFOUND, response=f"Plugin function {tool_name} does not exist"
)
try:
# 根据工具类型决定如何调用
# Decide how to call based on tool type
if hasattr(func_item, "type"):
func_type = func_item.type
if func_type.code in [4, 5]: # SYSTEM_CTL, IOT_CTL (需要conn参数)
if func_type.code in [4, 5]: # SYSTEM_CTL, IOT_CTL (needs conn argument)
result = func_item.func(conn, **arguments)
elif func_type.code == 2: # WAIT
result = func_item.func(**arguments)
@ -35,7 +35,7 @@ class ServerPluginExecutor(ToolExecutor):
else:
result = func_item.func(**arguments)
else:
# 默认不传conn参数
# Default: do not pass conn argument
result = func_item.func(**arguments)
return result
@ -47,31 +47,31 @@ class ServerPluginExecutor(ToolExecutor):
)
def get_tools(self) -> Dict[str, ToolDefinition]:
"""获取所有注册的服务端插件工具"""
"""Get all registered server plugin tools"""
tools = {}
# 获取必要的函数
# Get necessary functions
necessary_functions = ["handle_exit_intent", "get_lunar"]
# 获取配置中的函数
# Get functions in config
config_functions = self.config["Intent"][
self.config["selected_module"]["Intent"]
].get("functions", [])
# 转换为列表
# Convert to list
if not isinstance(config_functions, list):
try:
config_functions = list(config_functions)
except TypeError:
config_functions = []
# 合并所有需要的函数
# Merge all required functions
all_required_functions = list(set(necessary_functions + config_functions))
for func_name in all_required_functions:
func_item = all_function_registry.get(func_name)
if func_item:
# 从函数注册中获取描述
# Get description from function registry
fun_description = (
self.config.get("plugins", {})
.get(func_name, {})
@ -93,5 +93,5 @@ class ServerPluginExecutor(ToolExecutor):
return tools
def has_tool(self, tool_name: str) -> bool:
"""检查是否有指定的服务端插件工具"""
"""Check if specified server plugin tool exists"""
return tool_name in all_function_registry

View file

@ -1,4 +1,4 @@
"""统一工具处理器"""
"""Unified Tool Handler"""
import json
from typing import Dict, List, Any, Optional
@ -16,24 +16,24 @@ from .mcp_endpoint import MCPEndpointExecutor
class UnifiedToolHandler:
"""统一工具处理器"""
"""Unified Tool Handler"""
def __init__(self, conn):
self.conn = conn
self.config = conn.config
self.logger = setup_logging()
# 创建工具管理器
# Create tool manager
self.tool_manager = ToolManager(conn)
# 创建各类执行器
# Create various executors
self.server_plugin_executor = ServerPluginExecutor(conn)
self.server_mcp_executor = ServerMCPExecutor(conn)
self.device_iot_executor = DeviceIoTExecutor(conn)
self.device_mcp_executor = DeviceMCPExecutor(conn)
self.mcp_endpoint_executor = MCPEndpointExecutor(conn)
# 注册执行器
# Register executors
self.tool_manager.register_executor(
ToolType.SERVER_PLUGIN, self.server_plugin_executor
)
@ -50,97 +50,97 @@ class UnifiedToolHandler:
ToolType.MCP_ENDPOINT, self.mcp_endpoint_executor
)
# 初始化标志
# Initialize flag
self.finish_init = False
async def _initialize(self):
"""异步初始化"""
"""Asynchronous initialization"""
try:
# 自动导入插件模块
# Automatically import plugin modules
auto_import_modules("plugins_func.functions")
# 初始化服务端MCP
# Initialize server MCP
await self.server_mcp_executor.initialize()
# 初始化MCP接入点
# Initialize MCP endpoint
await self._initialize_mcp_endpoint()
# 初始化Home Assistant(如果需要)
# Initialize Home Assistant (if needed)
self._initialize_home_assistant()
self.finish_init = True
self.logger.debug("统一工具处理器初始化完成")
self.logger.debug("Unified tool handler init completed")
# 输出当前支持的所有工具列表
# Output the list of currently supported tools
self.current_support_functions()
except Exception as e:
self.logger.error(f"统一工具处理器初始化失败: {e}")
self.logger.error(f"Unified tool handler init failed: {e}")
async def _initialize_mcp_endpoint(self):
"""初始化MCP接入点"""
"""Initialize MCP endpoint"""
try:
from .mcp_endpoint import connect_mcp_endpoint
# 从配置中获取MCP接入点URL
# Get MCP endpoint URL from configuration
mcp_endpoint_url = self.config.get("mcp_endpoint", "")
if (
mcp_endpoint_url
and "你的" not in mcp_endpoint_url
and "your" not in mcp_endpoint_url
and mcp_endpoint_url != "null"
):
self.logger.info(f"正在初始化MCP接入点: {mcp_endpoint_url}")
self.logger.info(f"Initializing MCP endpoint: {mcp_endpoint_url}")
mcp_endpoint_client = await connect_mcp_endpoint(
mcp_endpoint_url, self.conn
)
if mcp_endpoint_client:
# 将MCP接入点客户端保存到连接对象中
# Save MCP endpoint client to connection object
self.conn.mcp_endpoint_client = mcp_endpoint_client
self.logger.info("MCP接入点初始化成功")
self.logger.info("MCP endpoint init success")
else:
self.logger.warning("MCP接入点初始化失败")
self.logger.warning("MCP endpoint init failed")
except Exception as e:
self.logger.error(f"初始化MCP接入点失败: {e}")
self.logger.error(f"Failed to init MCP endpoint: {e}")
def _initialize_home_assistant(self):
"""初始化Home Assistant提示词"""
"""Initialize Home Assistant prompt"""
try:
from plugins_func.functions.hass_init import append_devices_to_prompt
append_devices_to_prompt(self.conn)
except ImportError:
pass # 忽略导入错误
pass # Ignore import error
except Exception as e:
self.logger.error(f"初始化Home Assistant失败: {e}")
self.logger.error(f"Failed to init Home Assistant: {e}")
def get_functions(self) -> List[Dict[str, Any]]:
"""获取所有工具的函数描述"""
"""Get function descriptions of all tools"""
return self.tool_manager.get_function_descriptions()
def current_support_functions(self) -> List[str]:
"""获取当前支持的函数名称列表"""
"""Get the list of currently supported functions"""
func_names = self.tool_manager.get_supported_tool_names()
self.logger.info(f"当前支持的函数列表: {func_names}")
self.logger.info(f"Currently supported functions: {func_names}")
return func_names
def upload_functions_desc(self):
"""刷新函数描述列表"""
"""Refresh function description list"""
self.tool_manager.refresh_tools()
self.logger.info("函数描述列表已刷新")
self.logger.info("Function descriptions refreshed")
def has_tool(self, tool_name: str) -> bool:
"""检查是否有指定工具"""
"""Check if a specified tool exists"""
return self.tool_manager.has_tool(tool_name)
async def handle_llm_function_call(
self, conn, function_call_data: Dict[str, Any]
) -> Optional[ActionResponse]:
"""处理LLM函数调用"""
"""Handle LLM function call"""
try:
# 处理多函数调用
# Handle multiple function calls
if "function_calls" in function_call_data:
responses = []
for call in function_call_data["function_calls"]:
@ -150,42 +150,42 @@ class UnifiedToolHandler:
responses.append(result)
return self._combine_responses(responses)
# 处理单函数调用
# Handle single function call
function_name = function_call_data["name"]
arguments = function_call_data.get("arguments", {})
# 如果arguments是字符串,尝试解析为JSON
# If arguments is a string, try to parse it as JSON
if isinstance(arguments, str):
try:
arguments = json.loads(arguments) if arguments else {}
except json.JSONDecodeError:
self.logger.error(f"无法解析函数参数: {arguments}")
self.logger.error(f"Cannot parse function args: {arguments}")
return ActionResponse(
action=Action.ERROR,
response="无法解析函数参数",
response="Cannot parse function args",
)
self.logger.debug(f"调用函数: {function_name}, 参数: {arguments}")
self.logger.debug(f"Call function: {function_name}, args: {arguments}")
# 执行工具调用
# Execute tool call
result = await self.tool_manager.execute_tool(function_name, arguments)
return result
except Exception as e:
self.logger.error(f"处理function call错误: {e}")
self.logger.error(f"Handle function call error: {e}")
return ActionResponse(action=Action.ERROR, response=str(e))
def _combine_responses(self, responses: List[ActionResponse]) -> ActionResponse:
"""合并多个函数调用的响应"""
"""Combine responses from multiple function calls"""
if not responses:
return ActionResponse(action=Action.NONE, response="无响应")
return ActionResponse(action=Action.NONE, response="No response")
# 如果有任何错误,返回第一个错误
# If any error, return the first error
for response in responses:
if response.action == Action.ERROR:
return response
# 合并所有成功的响应
# Combine all successful responses
contents = []
responses_text = []
@ -195,7 +195,7 @@ class UnifiedToolHandler:
if response.response:
responses_text.append(response.response)
# 确定最终的动作类型
# Determine the final action type
final_action = Action.RESPONSE
for response in responses:
if response.action == Action.REQLLM:
@ -209,27 +209,27 @@ class UnifiedToolHandler:
)
async def register_iot_tools(self, descriptors: List[Dict[str, Any]]):
"""注册IoT设备工具"""
"""Register IoT device tools"""
self.device_iot_executor.register_iot_tools(descriptors)
self.tool_manager.refresh_tools()
self.logger.info(f"注册了{len(descriptors)}个IoT设备的工具")
self.logger.info(f"Registered {len(descriptors)} IoT device tools")
def get_tool_statistics(self) -> Dict[str, int]:
"""获取工具统计信息"""
"""Get tool statistics"""
return self.tool_manager.get_tool_statistics()
async def cleanup(self):
"""清理资源"""
"""Cleanup resources"""
try:
await self.server_mcp_executor.cleanup()
# 清理MCP接入点连接
# Cleanup MCP endpoint connection
if (
hasattr(self.conn, "mcp_endpoint_client")
and self.conn.mcp_endpoint_client
):
await self.conn.mcp_endpoint_client.close()
self.logger.info("工具处理器清理完成")
self.logger.info("Tool handler cleanup completed")
except Exception as e:
self.logger.error(f"工具处理器清理失败: {e}")
self.logger.error(f"Tool handler cleanup failed: {e}")

View file

@ -1,4 +1,4 @@
"""统一工具管理器"""
"""Unified Tool Manager"""
from typing import Dict, List, Optional, Any
from config.logger import setup_logging
@ -7,7 +7,7 @@ from .base import ToolType, ToolDefinition, ToolExecutor
class ToolManager:
"""统一工具管理器,管理所有类型的工具"""
"""Unified Tool Manager, manages all types of tools"""
def __init__(self, conn):
self.conn = conn
@ -17,18 +17,18 @@ class ToolManager:
self._cached_function_descriptions: Optional[List[Dict[str, Any]]] = None
def register_executor(self, tool_type: ToolType, executor: ToolExecutor):
"""注册工具执行器"""
"""Register tool executor"""
self.executors[tool_type] = executor
self._invalidate_cache()
self.logger.debug(f"注册工具执行器: {tool_type.value}")
self.logger.debug(f"Register tool executor: {tool_type.value}")
def _invalidate_cache(self):
"""使缓存失效"""
"""Invalidate cache"""
self._cached_tools = None
self._cached_function_descriptions = None
def get_all_tools(self) -> Dict[str, ToolDefinition]:
"""获取所有工具定义"""
"""Get all tool definitions"""
if self._cached_tools is not None:
return self._cached_tools
@ -38,16 +38,16 @@ class ToolManager:
tools = executor.get_tools()
for name, definition in tools.items():
if name in all_tools:
self.logger.warning(f"工具名称冲突: {name}")
self.logger.warning(f"Tool name conflict: {name}")
all_tools[name] = definition
except Exception as e:
self.logger.error(f"获取{tool_type.value}工具时出错: {e}")
self.logger.error(f"Error getting {tool_type.value} tools: {e}")
self._cached_tools = all_tools
return all_tools
def get_function_descriptions(self) -> List[Dict[str, Any]]:
"""获取所有工具的函数描述(OpenAI格式)"""
"""Get all tool function descriptions (OpenAI format)"""
if self._cached_function_descriptions is not None:
return self._cached_function_descriptions
@ -60,12 +60,12 @@ class ToolManager:
return descriptions
def has_tool(self, tool_name: str) -> bool:
"""检查是否存在指定工具"""
"""Check if a specified tool exists"""
tools = self.get_all_tools()
return tool_name in tools
def get_tool_type(self, tool_name: str) -> Optional[ToolType]:
"""获取工具类型"""
"""Get tool type"""
tools = self.get_all_tools()
tool_def = tools.get(tool_name)
return tool_def.tool_type if tool_def else None
@ -73,14 +73,14 @@ class ToolManager:
async def execute_tool(
self, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
"""执行工具调用"""
"""Execute tool call"""
try:
# 查找工具类型
# Find tool type
tool_type = self.get_tool_type(tool_name)
if not tool_type:
return ActionResponse(
action=Action.NOTFOUND,
response=f"工具 {tool_name} 不存在",
response=f"Tool {tool_name} not found",
)
# 获取对应的执行器
@ -88,37 +88,37 @@ class ToolManager:
if not executor:
return ActionResponse(
action=Action.ERROR,
response=f"工具类型 {tool_type.value} 的执行器未注册",
response=f"Executor for tool type {tool_type.value} not registered",
)
# 执行工具
self.logger.info(f"执行工具: {tool_name},参数: {arguments}")
self.logger.info(f"Execute tool: {tool_name}, args: {arguments}")
result = await executor.execute(self.conn, tool_name, arguments)
self.logger.debug(f"工具执行结果: {result}")
self.logger.debug(f"Tool execution result: {result}")
return result
except Exception as e:
self.logger.error(f"执行工具 {tool_name} 时出错: {e}")
self.logger.error(f"Error executing tool {tool_name}: {e}")
return ActionResponse(action=Action.ERROR, response=str(e))
def get_supported_tool_names(self) -> List[str]:
"""获取所有支持的工具名称"""
"""Get all supported tool names"""
tools = self.get_all_tools()
return list(tools.keys())
def refresh_tools(self):
"""刷新工具缓存"""
"""Refresh tool cache"""
self._invalidate_cache()
self.logger.debug("工具缓存已刷新")
self.logger.debug("Tool cache refreshed")
def get_tool_statistics(self) -> Dict[str, int]:
"""获取工具统计信息"""
"""Get tool statistics"""
stats = {}
for tool_type, executor in self.executors.items():
try:
tools = executor.get_tools()
stats[tool_type.value] = len(tools)
except Exception as e:
self.logger.error(f"获取{tool_type.value}工具统计时出错: {e}")
self.logger.error(f"Error getting {tool_type.value} tool stats: {e}")
stats[tool_type.value] = 0
return stats

View file

@ -41,10 +41,10 @@ class AccessToken:
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"Version": "2019-02-28",
}
# 构造规范化的请求字符串
# Construct normalized request string
query_string = AccessToken._encode_dict(parameters)
# print('规范化的请求字符串: %s' % query_string)
# 构造待签名字符串
# print('Normalized request string: %s' % query_string)
# Construct string to sign
string_to_sign = (
"GET"
+ "&"
@ -52,25 +52,25 @@ class AccessToken:
+ "&"
+ AccessToken._encode_text(query_string)
)
# print('待签名的字符串: %s' % string_to_sign)
# 计算签名
# print('String to sign: %s' % string_to_sign)
# Calculate signature
secreted_string = hmac.new(
bytes(access_key_secret + "&", encoding="utf-8"),
bytes(string_to_sign, encoding="utf-8"),
hashlib.sha1,
).digest()
signature = base64.b64encode(secreted_string)
# print('签名: %s' % signature)
# 进行URL编码
# print('Signature: %s' % signature)
# Perform URL encoding
signature = AccessToken._encode_text(signature)
# print('URL编码后的签名: %s' % signature)
# 调用服务
# print('URL encoded signature: %s' % signature)
# Call service
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
signature,
query_string,
)
# print('url: %s' % full_url)
# 提交HTTP GET请求
# Submit HTTP GET request
response = requests.get(full_url)
if response.ok:
root_obj = response.json()
@ -88,7 +88,7 @@ class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
# 新增空值判断逻辑
# Add null value check logic
self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret")
@ -117,24 +117,24 @@ class TTSProvider(TTSProviderBase):
self.header = {"Content-Type": "application/json"}
if self.access_key_id and self.access_key_secret:
# 使用密钥对生成临时token
# Generate temporary token using key pair
self._refresh_token()
else:
# 直接使用预生成的长期token
# Use pre-generated long-term token directly
self.token = config.get("token")
self.expire_time = None
def _refresh_token(self):
"""刷新Token并记录过期时间"""
"""Refresh Token and record expiration time"""
if self.access_key_id and self.access_key_secret:
self.token, expire_time_str = AccessToken.create_token(
self.access_key_id, self.access_key_secret
)
if not expire_time_str:
raise ValueError("无法获取有效的Token过期时间")
raise ValueError("Cannot get valid Token expiration time")
try:
# 统一转换为字符串处理
# Unified conversion to string processing
expire_str = str(expire_time_str).strip()
if expire_str.isdigit():
@ -143,29 +143,29 @@ class TTSProvider(TTSProviderBase):
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
self.expire_time = expire_time.timestamp() - 60
except Exception as e:
raise ValueError(f"无效的过期时间格式: {expire_str}") from e
raise ValueError(f"Invalid expiration time format: {expire_str}") from e
else:
self.expire_time = None
if not self.token:
raise ValueError("无法获取有效的访问Token")
raise ValueError("Cannot get valid access Token")
def _is_token_expired(self):
"""检查Token是否过期"""
"""Check if Token is expired"""
if not self.expire_time:
return False # 长期Token不过期
# 新增调试日志
return False # Long-term Token does not expire
# Add debug log
# current_time = time.time()
# remaining = self.expire_time - current_time
# print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | "
# f"过期时间 {datetime.fromtimestamp(self.expire_time)} | "
# f"剩余 {remaining:.2f}秒")
# print(f"Token expiration check: Current time {datetime.fromtimestamp(current_time)} | "
# f"Expiration time {datetime.fromtimestamp(self.expire_time)} | "
# f"Remaining {remaining:.2f}s")
return time.time() > self.expire_time
async def text_to_speak(self, text, output_file):
if self._is_token_expired():
logger.warning("Token已过期,正在自动刷新...")
logger.warning("Token expired, refreshing automatically...")
self._refresh_token()
request_json = {
"appkey": self.appkey,
@ -184,12 +184,12 @@ class TTSProvider(TTSProviderBase):
resp = requests.post(
self.api_url, json.dumps(request_json), headers=self.header
)
if resp.status_code == 401: # Token过期特殊处理
if resp.status_code == 401: # Special handling for Token expiration
self._refresh_token()
resp = requests.post(
self.api_url, json.dumps(request_json), headers=self.header
)
# 检查返回请求数据的mime类型是否是audio/***,是则保存到指定路径下;返回的是binary格式的
# Check if response mime type is audio/***, if so save; response is binary
if resp.headers["Content-Type"].startswith("audio/"):
if output_file:
with open(output_file, "wb") as f:

View file

@ -38,6 +38,7 @@ class TTSProviderBase(ABC):
self.tts_text_queue = queue.Queue()
self.tts_audio_queue = queue.Queue()
self.tts_audio_first_sentence = True
self._is_first_segment = True
self.before_stop_play_files = []
self.tts_text_buff = []
@ -69,14 +70,28 @@ class TTSProviderBase(ABC):
self.processed_chars = 0
self.is_first_sentence = True
def generate_filename(self, extension=".wav"):
return os.path.join(
self.output_file,
f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
)
def generate_filename(self, extension=None):
if extension is None:
extension = f".{self.audio_file_type}"
client_id = getattr(self.conn, "client_id", None) if self.conn else None
if client_id:
# Client-specific directory: data/{client_id}/
client_dir = os.path.join("data", client_id)
if not os.path.exists(client_dir):
os.makedirs(client_dir, exist_ok=True)
# Timestamp suffix: YYMMDD-hhmmss-ffffff (microseconds)
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
return os.path.join(client_dir, f"TTS_{timestamp}{extension}")
else:
return os.path.join(
self.output_file,
f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
)
def handle_opus(self, opus_data: bytes):
logger.bind(tag=TAG).debug(f"推送数据到队列里面帧数~~ {len(opus_data)}")
logger.bind(tag=TAG).debug(f"Pushing data to queue, frame count ~~ {len(opus_data)}")
self.tts_audio_queue.put((SentenceType.MIDDLE, opus_data, None))
def handle_audio_file(self, file_audio: bytes, text):
@ -86,12 +101,14 @@ class TTSProviderBase(ABC):
text = MarkdownCleaner.clean_markdown(text)
max_repeat_time = 5
if self.delete_audio_file:
# 需要删除文件的直接转为音频数据
# Convert to audio data directly if file needs deletion
while max_repeat_time > 0:
try:
audio_bytes = asyncio.run(self.text_to_speak(text, None))
if audio_bytes:
self.tts_audio_queue.put((SentenceType.FIRST, None, text))
marker_type = SentenceType.FIRST if self._is_first_segment else SentenceType.MIDDLE
self._is_first_segment = False
self.tts_audio_queue.put((marker_type, None, text))
audio_bytes_to_data_stream(
audio_bytes,
file_type=self.audio_file_type,
@ -103,16 +120,16 @@ class TTSProviderBase(ABC):
max_repeat_time -= 1
except Exception as e:
logger.bind(tag=TAG).warning(
f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
f"TTS generation failed {5 - max_repeat_time + 1} times: {text}, Error: {e}"
)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
f"语音生成成功: {text},重试{5 - max_repeat_time}次"
f"TTS generation success: {text}, Retried {5 - max_repeat_time} times"
)
else:
logger.bind(tag=TAG).error(
f"语音生成失败: {text},请检查网络或服务是否正常"
f"TTS generation failed: {text}, please check network or service"
)
return None
else:
@ -123,22 +140,30 @@ class TTSProviderBase(ABC):
asyncio.run(self.text_to_speak(text, tmp_file))
except Exception as e:
logger.bind(tag=TAG).warning(
f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
f"TTS generation failed {5 - max_repeat_time + 1} times: {text}, Error: {e}"
)
# 未执行成功,删除文件
# Execution failed, delete file
if os.path.exists(tmp_file):
os.remove(tmp_file)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
f"语音生成成功: {text}:{tmp_file},重试{5 - max_repeat_time}次"
f"TTS generation success: {text}:{tmp_file}, Retried {5 - max_repeat_time} times"
)
else:
logger.bind(tag=TAG).error(
f"语音生成失败: {text},请检查网络或服务是否正常"
f"TTS generation failed: {text}, please check network or service"
)
self.tts_audio_queue.put((SentenceType.FIRST, None, text))
# Put a marker so the audio thread knows this sentence finished (even if empty)
marker_type = SentenceType.FIRST if self._is_first_segment else SentenceType.MIDDLE
self._is_first_segment = False
self.tts_audio_queue.put((marker_type, None, text))
return None
marker_type = SentenceType.FIRST if self._is_first_segment else SentenceType.MIDDLE
self._is_first_segment = False
self.tts_audio_queue.put((marker_type, None, text))
self._process_audio_file_stream(tmp_file, callback=opus_handler)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
@ -148,7 +173,7 @@ class TTSProviderBase(ABC):
text = MarkdownCleaner.clean_markdown(text)
max_repeat_time = 5
if self.delete_audio_file:
# 需要删除文件的直接转为音频数据
# Convert to audio data directly if file needs deletion
while max_repeat_time > 0:
try:
audio_bytes = asyncio.run(self.text_to_speak(text, None))
@ -165,16 +190,16 @@ class TTSProviderBase(ABC):
max_repeat_time -= 1
except Exception as e:
logger.bind(tag=TAG).warning(
f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
f"TTS generation failed {5 - max_repeat_time + 1} times: {text}, Error: {e}"
)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
f"语音生成成功: {text},重试{5 - max_repeat_time}次"
f"TTS generation success: {text}, Retried {5 - max_repeat_time} times"
)
else:
logger.bind(tag=TAG).error(
f"语音生成失败: {text},请检查网络或服务是否正常"
f"TTS generation failed: {text}, please check network or service"
)
return None
else:
@ -185,20 +210,20 @@ class TTSProviderBase(ABC):
asyncio.run(self.text_to_speak(text, tmp_file))
except Exception as e:
logger.bind(tag=TAG).warning(
f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
f"TTS generation failed {5 - max_repeat_time + 1} times: {text}, Error: {e}"
)
# 未执行成功,删除文件
# Execution failed, delete file
if os.path.exists(tmp_file):
os.remove(tmp_file)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
f"语音生成成功: {text}:{tmp_file},重试{5 - max_repeat_time}次"
f"TTS generation success: {text}:{tmp_file}, Retried {5 - max_repeat_time} times"
)
else:
logger.bind(tag=TAG).error(
f"语音生成失败: {text},请检查网络或服务是否正常"
f"TTS generation failed: {text}, please check network or service"
)
return tmp_file
@ -213,13 +238,13 @@ class TTSProviderBase(ABC):
def audio_to_pcm_data_stream(
self, audio_file_path, callback: Callable[[Any], Any] = None
):
"""音频文件转换为PCM编码"""
"""Convert audio file to PCM encoding"""
return audio_to_data_stream(audio_file_path, is_opus=False, callback=callback)
def audio_to_opus_data_stream(
self, audio_file_path, callback: Callable[[Any], Any] = None
):
"""音频文件转换为Opus编码"""
"""Convert audio file to Opus encoding"""
return audio_to_data_stream(audio_file_path, is_opus=True, callback=callback)
def tts_one_sentence(
@ -230,14 +255,14 @@ class TTSProviderBase(ABC):
content_file=None,
sentence_id=None,
):
"""发送一句话"""
"""Send a sentence"""
if not sentence_id:
if conn.sentence_id:
sentence_id = conn.sentence_id
else:
sentence_id = str(uuid.uuid4().hex)
conn.sentence_id = sentence_id
# 对于单句的文本,进行分段处理
# For single sentence text, process in segments
segments = re.split(r"([。!?!?;;\n])", content_detail)
for seg in segments:
self.tts_text_queue.put(
@ -252,20 +277,20 @@ class TTSProviderBase(ABC):
async def open_audio_channels(self, conn):
self.conn = conn
# tts 消化线程
# TTS consumer thread
self.tts_priority_thread = threading.Thread(
target=self.tts_text_priority_thread, daemon=True
)
self.tts_priority_thread.start()
# 音频播放 消化线程
# Audio playback consumer thread
self.audio_play_priority_thread = threading.Thread(
target=self._audio_play_priority_thread, daemon=True
)
self.audio_play_priority_thread.start()
# 这里默认是非流式的处理方式
# 流式处理方式请在子类中重写
# Default is non-streaming processing
# Override in subclass for streaming processing
def tts_text_priority_thread(self):
while not self.conn.stop_event.is_set():
try:
@ -273,19 +298,20 @@ class TTSProviderBase(ABC):
if message.sentence_type == SentenceType.FIRST:
self.conn.client_abort = False
if self.conn.client_abort:
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
logger.bind(tag=TAG).info("Received interrupt signal, terminating TTS text processing thread")
continue
if message.sentence_type == SentenceType.FIRST:
# 初始化参数
# Initialize parameters
self.tts_stop_request = False
self.processed_chars = 0
self.tts_text_buff = []
self.is_first_sentence = True
self.tts_audio_first_sentence = True
self._is_first_segment = True
elif ContentType.TEXT == message.content_type:
self.tts_text_buff.append(message.content_detail)
segment_text = self._get_segment_text()
if segment_text:
if segment_text and segment_text.strip():
self.to_tts_stream(segment_text, opus_handler=self.handle_opus)
elif ContentType.FILE == message.content_type:
self._process_remaining_text_stream(opus_handler=self.handle_opus)
@ -304,12 +330,12 @@ class TTSProviderBase(ABC):
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
f"Failed to process TTS text: {str(e)}, Type: {type(e).__name__}, Stack: {traceback.format_exc()}"
)
continue
def _audio_play_priority_thread(self):
# 需要上报的文本和音频列表
# List of text and audio to report
enqueue_text = None
enqueue_audio = None
while not self.conn.stop_event.is_set():
@ -325,30 +351,30 @@ class TTSProviderBase(ABC):
continue
if self.conn.client_abort:
logger.bind(tag=TAG).debug("收到打断信号,跳过当前音频数据")
logger.bind(tag=TAG).debug("Received interrupt signal, skipping current audio data")
enqueue_text, enqueue_audio = None, []
continue
# 收到下一个文本开始或会话结束时进行上报
# Report when next text starts or session ends
if sentence_type is not SentenceType.MIDDLE:
# 上报TTS数据
# Report TTS data
if enqueue_text is not None and enqueue_audio is not None:
enqueue_tts_report(self.conn, enqueue_text, enqueue_audio)
enqueue_audio = []
enqueue_text = text
# 收集上报音频数据
# Collect audio data for reporting
if isinstance(audio_datas, bytes) and enqueue_audio is not None:
enqueue_audio.append(audio_datas)
# 发送音频
# Send audio
future = asyncio.run_coroutine_threadsafe(
sendAudioMessage(self.conn, sentence_type, audio_datas, text),
self.conn.loop,
)
future.result()
# 记录输出和报告
# Record output and report
if self.conn.max_output_size > 0 and text:
add_device_output(self.conn.headers.get("device-id"), len(text))
@ -362,17 +388,17 @@ class TTSProviderBase(ABC):
pass
async def close(self):
"""资源清理方法"""
"""Resource cleanup method"""
if hasattr(self, "ws") and self.ws:
await self.ws.close()
def _get_segment_text(self):
# 合并当前全部文本并处理未分割部分
# Merge all current text and process unsplit parts
full_text = "".join(self.tts_text_buff)
current_text = full_text[self.processed_chars :] # 从未处理的位置开始
current_text = full_text[self.processed_chars :] # Start from unprocessed position
last_punct_pos = -1
# 根据是否是第一句话选择不同的标点符号集合
# Select punctuation set based on whether it is the first sentence
punctuations_to_use = (
self.first_sentence_punctuations
if self.is_first_sentence
@ -391,16 +417,16 @@ class TTSProviderBase(ABC):
segment_text = textUtils.get_string_no_punctuation_or_emoji(
segment_text_raw
)
self.processed_chars += len(segment_text_raw) # 更新已处理字符位置
self.processed_chars += len(segment_text_raw) # Update processed char position
# 如果是第一句话,在找到第一个逗号后,将标志设置为False
# If it is the first sentence, set flag to False after finding the first comma
if self.is_first_sentence:
self.is_first_sentence = False
return segment_text
elif self.tts_stop_request and current_text:
segment_text = current_text
self.is_first_sentence = True # 重置标志
self.is_first_sentence = True # Reset flag
return segment_text
else:
return None
@ -408,11 +434,11 @@ class TTSProviderBase(ABC):
def _process_audio_file_stream(
self, tts_file, callback: Callable[[Any], Any]
) -> None:
"""处理音频文件并转换为指定格式
"""Process audio file and convert to specified format
Args:
tts_file: 音频文件路径
callback: 文件处理函数
tts_file: Audio file path
callback: File processing function
"""
if tts_file.endswith(".p3"):
p3.decode_opus_from_file_stream(tts_file, callback=callback)
@ -438,10 +464,10 @@ class TTSProviderBase(ABC):
def _process_remaining_text_stream(
self, opus_handler: Callable[[bytes], None] = None
):
"""处理剩余的文本并生成语音
"""Process remaining text and generate speech
Returns:
bool: 是否成功处理了文本
bool: Whether text was successfully processed
"""
full_text = "".join(self.tts_text_buff)
remaining_text = full_text[self.processed_chars :]

View file

@ -4,6 +4,7 @@ import edge_tts
from datetime import datetime
from core.providers.tts.base import TTSProviderBase
TAG = __name__
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
@ -14,33 +15,53 @@ class TTSProvider(TTSProviderBase):
self.voice = config.get("voice")
self.audio_file_type = config.get("format", "mp3")
def generate_filename(self, extension=".mp3"):
return os.path.join(
self.output_file,
f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
)
async def text_to_speak(self, text, output_file):
try:
communicate = edge_tts.Communicate(text, voice=self.voice)
if output_file:
# 确保目录存在并创建空文件
os.makedirs(os.path.dirname(output_file), exist_ok=True)
with open(output_file, "wb") as f:
pass
# 流式写入音频数据
with open(output_file, "ab") as f: # 改为追加模式避免覆盖
async for chunk in communicate.stream():
if chunk["type"] == "audio": # 只处理音频数据块
f.write(chunk["data"])
else:
# 返回音频二进制数据
audio_bytes = b""
async for chunk in communicate.stream():
if chunk["type"] == "audio":
audio_bytes += chunk["data"]
return audio_bytes
# Detect if text contains Chinese but voice is English-based
# Regular expression for CJK characters
has_chinese = any('\u4e00' <= char <= '\u9fff' for char in text)
target_voice = self.voice
if has_chinese and not any(v in self.voice.lower() for v in ["chinese", "mandarin", "zh-cn"]):
from config.logger import setup_logging
logger = setup_logging()
logger.bind(tag=TAG).info(f"Detected Chinese content with English voice {self.voice}, using fallback zh-CN-XiaoxiaoNeural")
target_voice = "zh-CN-XiaoxiaoNeural"
return await self._do_communicate(text, target_voice, output_file)
except Exception as e:
error_msg = f"Edge TTS请求失败: {e}"
raise Exception(error_msg) # 抛出异常,让调用方捕获
# General fallback for generic failure
fallback_voice = "en-US-AndrewMultilingualNeural"
if self.voice == fallback_voice:
raise e
from config.logger import setup_logging
logger = setup_logging()
logger.bind(tag=TAG).warning(f"Edge TTS failed with {target_voice if 'target_voice' in locals() else self.voice}, trying fallback {fallback_voice}: {e}")
try:
return await self._do_communicate(text, fallback_voice, output_file)
except Exception as e2:
error_msg = f"Edge TTS fallback failed: {e2}"
raise Exception(error_msg)
async def _do_communicate(self, text, voice, output_file):
communicate = edge_tts.Communicate(text, voice=voice)
if output_file:
# 确保目录存在并创建空文件
os.makedirs(os.path.dirname(output_file), exist_ok=True)
with open(output_file, "wb") as f:
pass
# 流式写入音频数据
with open(output_file, "ab") as f: # 改为追加模式避免覆盖
async for chunk in communicate.stream():
if chunk["type"] == "audio": # 只处理音频数据块
f.write(chunk["data"])
return True
else:
# 返回音频二进制数据
audio_bytes = b""
async for chunk in communicate.stream():
if chunk["type"] == "audio":
audio_bytes += chunk["data"]
return audio_bytes

View file

@ -45,27 +45,27 @@ EVENT_Start_Connection = 1
EVENT_FinishConnection = 2
EVENT_ConnectionStarted = 50 # 成功建连
EVENT_ConnectionStarted = 50 # Connection successful
EVENT_ConnectionFailed = 51 # 建连失败(可能是无法通过权限认证)
EVENT_ConnectionFailed = 51 # Connection failed (possible auth failure)
EVENT_ConnectionFinished = 52 # 连接结束
EVENT_ConnectionFinished = 52 # Connection finished
# 上行Session事件
# Upstream Session Event
EVENT_StartSession = 100
EVENT_CancelSession = 101
EVENT_FinishSession = 102
# 下行Session事件
# Downstream Session Event
EVENT_SessionStarted = 150
EVENT_SessionCanceled = 151
EVENT_SessionFinished = 152
EVENT_SessionFailed = 153
# 上行通用事件
# Upstream General Event
EVENT_TaskRequest = 200
# 下行TTS事件
# Downstream TTS Event
EVENT_TTSSentenceStart = 350
EVENT_TTSSentenceEnd = 351
@ -114,7 +114,7 @@ class Optional:
self.response_meta_json: str | None = None
self.sequence = sequence
# 转成 byte 序列
# Convert to byte sequence
def as_bytes(self) -> bytes:
option_bytes = bytearray()
if self.event != EVENT_NONE:
@ -144,7 +144,7 @@ class TTSProvider(TTSProviderBase):
super().__init__(config, delete_audio_file)
self.ws = None
self.interface_type = InterfaceType.DUAL_STREAM
self._monitor_task = None # 监听任务引用
self._monitor_task = None # Monitoring task reference
self.appId = config.get("appid")
self.access_token = config.get("access_token")
self.cluster = config.get("cluster")
@ -160,7 +160,7 @@ class TTSProvider(TTSProviderBase):
self.speech_rate = int(speech_rate) if speech_rate else 0
self.loudness_rate = int(loudness_rate) if loudness_rate else 0
self.pitch = int(pitch) if pitch else 0
# 多情感音色参数
# Multi-emotion voice parameters
self.emotion = config.get("emotion", "neutral")
emotion_scale = config.get("emotion_scale", "4")
self.emotion_scale = int(emotion_scale) if emotion_scale else 4
@ -187,18 +187,18 @@ class TTSProvider(TTSProviderBase):
raise
async def _ensure_connection(self):
"""建立新的WebSocket连接,并启动监听任务(仅第一次)"""
"""Establish new WebSocket connection and start monitoring task (first time only)"""
try:
if self.ws:
if self.enable_ws_reuse:
logger.bind(tag=TAG).info(f"使用已有链接...")
logger.bind(tag=TAG).info(f"Using existing connection...")
return self.ws
else:
try:
await self.finish_connection()
except:
pass
logger.bind(tag=TAG).debug("开始建立新连接...")
logger.bind(tag=TAG).debug("Starting to establish new connection...")
ws_header = {
"X-Api-App-Key": self.appId,
"X-Api-Access-Key": self.access_token,
@ -210,9 +210,9 @@ class TTSProvider(TTSProviderBase):
)
logger.bind(tag=TAG).debug("WebSocket连接建立成功")
# 连接建立成功后,启动监听任务
# After connection established, start monitoring task
if self._monitor_task is None or self._monitor_task.done():
logger.bind(tag=TAG).debug("启动监听任务...")
logger.bind(tag=TAG).debug("Starting monitoring task...")
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
return self.ws
@ -222,7 +222,7 @@ class TTSProvider(TTSProviderBase):
raise
async def finish_connection(self):
"""发送 FinishConnection 事件,等待服务端返回 EVENT_ConnectionFinished"""
"""Send FinishConnection event, wait for server to return EVENT_ConnectionFinished"""
try:
if self.ws:
logger.bind(tag=TAG).debug("开始关闭连接...")
@ -238,12 +238,12 @@ class TTSProvider(TTSProviderBase):
pass
def tts_text_priority_thread(self):
"""火山引擎双流式TTS的文本处理线程"""
"""Volcengine dual-stream TTS text processing thread"""
while not self.conn.stop_event.is_set():
try:
message = self.tts_text_queue.get(timeout=1)
logger.bind(tag=TAG).debug(
f"收到TTS任务|{message.sentence_type.name} | {message.content_type.name} | 会话ID: {self.conn.sentence_id}"
f"Received TTS task | {message.sentence_type.name} | {message.content_type.name} | Session ID: {self.conn.sentence_id}"
)
if message.sentence_type == SentenceType.FIRST:
@ -251,7 +251,7 @@ class TTSProvider(TTSProviderBase):
if self.conn.client_abort:
try:
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
logger.bind(tag=TAG).info("Received interrupt info, terminating TTS text processing thread")
if self.enable_ws_reuse:
asyncio.run_coroutine_threadsafe(
self.cancel_session(self.conn.sentence_id),
@ -264,88 +264,88 @@ class TTSProvider(TTSProviderBase):
)
continue
except Exception as e:
logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to cancel TTS session: {str(e)}")
continue
if message.sentence_type == SentenceType.FIRST:
# 初始化参数
# Initialize parameters
try:
if not getattr(self.conn, "sentence_id", None):
self.conn.sentence_id = uuid.uuid4().hex
logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
logger.bind(tag=TAG).debug(f"Automatically generated new Session ID: {self.conn.sentence_id}")
logger.bind(tag=TAG).debug("开始启动TTS会话...")
logger.bind(tag=TAG).debug("Starting TTS session...")
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).debug("TTS会话启动成功")
logger.bind(tag=TAG).debug("TTS session started successfully")
except Exception as e:
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to start TTS session: {str(e)}")
continue
elif ContentType.TEXT == message.content_type:
if message.content_detail:
try:
logger.bind(tag=TAG).debug(
f"开始发送TTS文本: {message.content_detail}"
f"Starting to send TTS text: {message.content_detail}"
)
future = asyncio.run_coroutine_threadsafe(
self.text_to_speak(message.content_detail, None),
loop=self.conn.loop,
)
future.result()
logger.bind(tag=TAG).debug("TTS文本发送成功")
logger.bind(tag=TAG).debug("TTS text sent successfully")
except Exception as e:
logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to send TTS text: {str(e)}")
continue
elif ContentType.FILE == message.content_type:
logger.bind(tag=TAG).info(
f"添加音频文件到待播放列表: {message.content_file}"
f"Adding audio file to playlist: {message.content_file}"
)
if message.content_file and os.path.exists(message.content_file):
# 先处理文件音频数据
# Process file audio data first
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).debug("开始结束TTS会话...")
logger.bind(tag=TAG).debug("Starting to end TTS session...")
future = asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
future.result()
except Exception as e:
logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to end TTS session: {str(e)}")
continue
except queue.Empty:
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
f"Failed to process TTS text: {str(e)}, Type: {type(e).__name__}, Stack: {traceback.format_exc()}"
)
continue
async def text_to_speak(self, text, _):
"""发送文本到TTS服务"""
"""Send text to TTS service"""
try:
# 建立新连接
# Establish new connection
if self.ws is None:
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
logger.bind(tag=TAG).warning(f"WebSocket connection does not exist, stop sending text")
return
# 过滤Markdown
# Filter Markdown
filtered_text = MarkdownCleaner.clean_markdown(text)
if filtered_text:
# 发送文本
# Send text
await self.send_text(self.voice, filtered_text, self.conn.sentence_id)
return
except Exception as e:
logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to send TTS text: {str(e)}")
if self.ws:
try:
await self.ws.close()
@ -355,23 +355,23 @@ class TTSProvider(TTSProviderBase):
raise
async def start_session(self, session_id):
logger.bind(tag=TAG).debug(f"开始会话~~{session_id}")
logger.bind(tag=TAG).debug(f"Starting session~~{session_id}")
try:
# 等待上一个会话结束,最多等待3次
# Wait for previous session to end, max 3 times
for _ in range(3):
if not self.activate_session:
break
logger.bind(tag=TAG).debug(f"等待上一个会话结束...")
logger.bind(tag=TAG).debug(f"Waiting for previous session to end...")
await asyncio.sleep(0.1)
else:
# 等待超时,强制清除连接状态
logger.bind(tag=TAG).debug("等待上一个会话超时,清除连接状态...")
# Wait timeout, force clear connection state
logger.bind(tag=TAG).debug("Wait for previous session timeout, clearing connection state...")
await self.close()
# 设置会话激活标志
# Set session activation flag
self.activate_session = True
# 确保连接建立
# Ensure connection established
await self._ensure_connection()
header = Header(
@ -386,15 +386,15 @@ class TTSProvider(TTSProviderBase):
event=EVENT_StartSession, speaker=self.voice
)
await self.send_event(self.ws, header, optional, payload)
logger.bind(tag=TAG).debug("会话启动请求已发送")
logger.bind(tag=TAG).debug("Session start request sent")
except Exception as e:
logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to start session: {str(e)}")
# 确保清理资源
await self.close()
raise
async def finish_session(self, session_id):
logger.bind(tag=TAG).debug(f"关闭会话~~{session_id}")
logger.bind(tag=TAG).debug(f"Closing session~~{session_id}")
try:
if self.ws:
header = Header(
@ -407,16 +407,16 @@ class TTSProvider(TTSProviderBase):
).as_bytes()
payload = str.encode("{}")
await self.send_event(self.ws, header, optional, payload)
logger.bind(tag=TAG).debug("会话结束请求已发送")
logger.bind(tag=TAG).debug("Session end request sent")
except Exception as e:
logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}")
# 确保清理资源
logger.bind(tag=TAG).error(f"Failed to close session: {str(e)}")
# Ensure resources are cleaned up
await self.close()
raise
async def cancel_session(self,session_id):
logger.bind(tag=TAG).debug(f"取消会话,释放服务端资源~~{session_id}")
logger.bind(tag=TAG).debug(f"Cancelling session, releasing server resources~~{session_id}")
try:
if self.ws:
header = Header(
@ -429,15 +429,15 @@ class TTSProvider(TTSProviderBase):
).as_bytes()
payload = str.encode("{}")
await self.send_event(self.ws, header, optional, payload)
logger.bind(tag=TAG).debug("会话取消请求已发送")
logger.bind(tag=TAG).debug("Session cancel request sent")
except Exception as e:
logger.bind(tag=TAG).error(f"取消会话失败: {str(e)}")
# 确保清理资源
logger.bind(tag=TAG).error(f"Failed to cancel session: {str(e)}")
# Ensure resources are cleaned up
await self.close()
raise
async def close(self):
"""资源清理方法"""
"""Resource cleanup method"""
self.activate_session = False
# 取消监听任务
if self._monitor_task:
@ -447,7 +447,7 @@ class TTSProvider(TTSProviderBase):
except asyncio.CancelledError:
pass
except Exception as e:
logger.bind(tag=TAG).warning(f"关闭时取消监听任务错误: {e}")
logger.bind(tag=TAG).warning(f"Error cancelling monitoring task during close: {e}")
self._monitor_task = None
if self.ws:
@ -458,35 +458,35 @@ class TTSProvider(TTSProviderBase):
self.ws = None
async def _start_monitor_tts_response(self):
"""监听TTS响应 - 长期运行"""
"""Monitor TTS response - Long running"""
try:
while not self.conn.stop_event.is_set():
try:
# 确保 `recv()` 运行在同一个 event loop
# Ensure recv() runs in same event loop
msg = await self.ws.recv()
res = self.parser_response(msg)
self.print_response(res, "send_text res:")
# 优先处理连接级别事件
# prioritize connection level events
if res.optional.event == EVENT_ConnectionFinished:
logger.bind(tag=TAG).debug(f"链接关闭成功~~")
logger.bind(tag=TAG).debug(f"Connection closed successfully~~")
break
# 只处理当前活跃会话的响应
# Only process response for current active session
if res.optional.sessionId and self.conn.sentence_id != res.optional.sessionId:
# 如果是会话结束相关事件,即使会话ID不匹配也要重置状态
# If session end related event, reset state even if session ID mismatch
if res.optional.event in [EVENT_SessionCanceled, EVENT_SessionFailed, EVENT_SessionFinished]:
logger.bind(tag=TAG).debug(f"收到残余下行结束响应重置会话状态~~")
logger.bind(tag=TAG).debug(f"Received residual downstream end response, resetting session state~~")
self.activate_session = False
continue
if res.optional.event == EVENT_SessionCanceled:
logger.bind(tag=TAG).debug(f"释放服务端资源成功~~")
logger.bind(tag=TAG).debug(f"Released server resources successfully~~")
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", "")
logger.bind(tag=TAG).debug(f"句子语音生成开始: {self.tts_text}")
logger.bind(tag=TAG).debug(f"Sentence voice generation start: {self.tts_text}")
self.tts_audio_queue.put(
(SentenceType.FIRST, [], self.tts_text)
)
@ -496,16 +496,16 @@ class TTSProvider(TTSProviderBase):
):
self.wav_to_opus_data_audio_raw_stream(res.payload, callback=self.handle_opus)
elif res.optional.event == EVENT_TTSSentenceEnd:
logger.bind(tag=TAG).info(f"句子语音生成成功:{self.tts_text}")
logger.bind(tag=TAG).info(f"Sentence voice generation successful: {self.tts_text}")
elif res.optional.event == EVENT_SessionFinished:
logger.bind(tag=TAG).debug(f"会话结束~~")
logger.bind(tag=TAG).debug(f"Session ended~~")
self.activate_session = False
self._process_before_stop_play_files()
# 非复用模式下,会话结束后发送 FinishConnection
# In non-reuse mode, send FinishConnection after session ends
if not self.enable_ws_reuse:
await self.finish_connection()
except websockets.ConnectionClosed:
logger.bind(tag=TAG).warning("WebSocket连接已关闭")
logger.bind(tag=TAG).warning("WebSocket connection closed")
break
except Exception as e:
logger.bind(tag=TAG).error(
@ -513,14 +513,14 @@ class TTSProvider(TTSProviderBase):
)
traceback.print_exc()
break
# 连接异常时关闭WebSocket
# Close WebSocket on connection exception
if self.ws:
try:
await self.ws.close()
except:
pass
self.ws = None
# 监听任务退出时清理引用
# Clean up reference when monitoring task exits
finally:
self.activate_session = False
self._monitor_task = None
@ -557,7 +557,7 @@ class TTSProvider(TTSProviderBase):
)
return await self.send_event(self.ws, header, optional, payload)
# 读取 res 数组某段 字符串内容
# Read string content from res array segment
def read_res_content(self, res: bytes, offset: int):
content_size = int.from_bytes(res[offset : offset + 4], "big", signed=True)
offset += 4
@ -565,7 +565,7 @@ class TTSProvider(TTSProviderBase):
offset += content_size
return content, offset
# 读取 payload
# Read payload
def read_res_payload(self, res: bytes, offset: int):
payload_size = int.from_bytes(res[offset : offset + 4], "big", signed=True)
offset += 4
@ -577,7 +577,7 @@ class TTSProvider(TTSProviderBase):
if isinstance(res, str):
raise RuntimeError(res)
response = Response(Header(), Optional())
# 解析结果
# Parse result
# header
header = response.header
num = 0b00001111
@ -655,7 +655,7 @@ class TTSProvider(TTSProviderBase):
"loudness_rate": self.loudness_rate
}
# 如果是多情感音色,添加情感参数
# If multi-emotion voice, add emotion parameters
if '_emo_' in self.voice:
if self.emotion:
audio_params["emotion"] = self.emotion
@ -686,25 +686,25 @@ class TTSProvider(TTSProviderBase):
return self.opus_encoder.encode_pcm_to_opus_stream(raw_data_var, is_end, callback=callback)
def to_tts(self, text: str) -> list:
"""非流式生成音频数据,用于生成音频及测试场景
"""Non-streaming audio generation, used for generating audio and testing scenarios
Args:
text: 要转换的文本
text: Text to convert
Returns:
list: 音频数据列表
list: Audio data list
"""
try:
# 创建事件循环
# Create event loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# 生成会话ID
# Generate Session ID
session_id = uuid.uuid4().__str__().replace("-", "")
# 存储音频数据
# Store audio data
audio_data = []
async def _generate_audio():
# 创建新的WebSocket连接
# Create new WebSocket connection
ws_header = {
"X-Api-App-Key": self.appId,
"X-Api-Access-Key": self.access_token,
@ -716,7 +716,7 @@ class TTSProvider(TTSProviderBase):
)
try:
# 启动会话
# Start session
header = Header(
message_type=FULL_CLIENT_REQUEST,
message_type_specific_flags=MsgTypeFlagWithEvent,
@ -730,7 +730,7 @@ class TTSProvider(TTSProviderBase):
)
await self.send_event(ws, header, optional, payload)
# 发送文本
# Send text
header = Header(
message_type=FULL_CLIENT_REQUEST,
message_type_specific_flags=MsgTypeFlagWithEvent,
@ -744,7 +744,7 @@ class TTSProvider(TTSProviderBase):
)
await self.send_event(ws, header, optional, payload)
# 发送结束会话请求
# Send end session request
header = Header(
message_type=FULL_CLIENT_REQUEST,
message_type_specific_flags=MsgTypeFlagWithEvent,
@ -756,7 +756,7 @@ class TTSProvider(TTSProviderBase):
payload = str.encode("{}")
await self.send_event(ws, header, optional, payload)
# 接收音频数据
# Receive audio data
while True:
msg = await ws.recv()
res = self.parser_response(msg)
@ -770,18 +770,18 @@ class TTSProvider(TTSProviderBase):
break
finally:
# 清理资源
# Clean up resources
try:
await ws.close()
except:
pass
# 运行异步任务
# Run async task
loop.run_until_complete(_generate_audio())
loop.close()
return audio_data
except Exception as e:
logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to generate audio data: {str(e)}")
return []

View file

@ -51,17 +51,19 @@ class TTSProvider(TTSProviderBase):
else:
self.save_path = None
async def pcm_to_wav(self, pcm_data: bytes, sample_rate: int = 24000, num_channels: int = 1,
bits_per_sample: int = 16) -> bytes:
async def pcm_to_wav(self, pcm_data: bytes, sample_rate: int = 24000, num_channels: int = 1,
bits_per_sample: int = 16) -> bytes:
"""
将 PCM 数据转换为 WAV 文件并返回字节数据
:param pcm_data: PCM 数据(原始字节流)
:param sample_rate: 音频采样率,默认为24000
:param num_channels: 声道数,默认为单声道
:param bits_per_sample: 每个样本的位数,默认为16
:return: WAV 格式的字节数据
Convert PCM data to WAV file and return byte data
:param pcm_data: PCM data (raw byte stream)
:param sample_rate: Audio sampling rate, default is 24000
:param num_channels: Number of channels, default is mono
:param bits_per_sample: Bits per sample, default is 16
:return: WAV format byte data
"""
byte_data = np.frombuffer(pcm_data, dtype=np.int16) # 16位PCM
byte_data = np.frombuffer(pcm_data, dtype=np.int16) # 16-bit PCM
wav_io = io.BytesIO()
with wave.open(wav_io, "wb") as wav_file:
@ -80,24 +82,24 @@ class TTSProvider(TTSProviderBase):
async def text_streaming(self, text, output_file):
try:
# 使用 websockets 异步连接到 WebSocket 服务器
# Connect to WebSocket server asynchronously using websockets
async with websockets.connect(self.url) as ws:
# 发送开始请求
# Send start request
start_request = {
"task": "tts",
"signal": "start"
}
await ws.send(json.dumps(start_request))
# 接收开始响应并提取 session_id
# Receive start response and extract session_id
start_response = await ws.recv()
start_response = json.loads(start_response) # 解析 JSON 响应
start_response = json.loads(start_response) # Parse JSON response
if start_response.get("status") != 0:
raise Exception(f"连接失败: {start_response.get('signal')}")
raise Exception(f"Connection failed: {start_response.get('signal')}")
session_id = start_response.get("session")
# 发送待合成的文本数据
# Send text data to be synthesized
data_request = {
"text": text,
"spk_id": self.spk_id,
@ -105,42 +107,42 @@ class TTSProvider(TTSProviderBase):
await ws.send(json.dumps(data_request))
audio_chunks = b""
timeout_seconds = 60 # 设置超时
timeout_seconds = 60 # Set timeout
try:
while True:
response = await asyncio.wait_for(ws.recv(), timeout=timeout_seconds)
response = json.loads(response) # 解析 JSON 响应
response = json.loads(response) # Parse JSON response
status = response.get("status")
if status == 2: # 最后一个数据包
if status == 2: # Last packet
break
else:
# 拼接音频数据(base64 编码的 PCM 数据)
# Concatenate audio data (base64 encoded PCM data)
audio_chunks += base64.b64decode(response.get("audio"))
except asyncio.TimeoutError:
raise Exception(f"WebSocket 超时:等待音频数据超过 {timeout_seconds} 秒")
raise Exception(f"WebSocket timeout: waiting for audio data exceeded {timeout_seconds} seconds")
# 将拼接后的 PCM 数据转换为 WAV 格式
# Convert concatenated PCM data to WAV format
wav_data = await self.pcm_to_wav(audio_chunks)
# 结束请求
# End request
end_request = {
"task": "tts",
"signal": "end",
"session": session_id # 会话 ID 必须与开始请求中的一致
"session": session_id # Session ID must match start request
}
await ws.send(json.dumps(end_request))
# 接收结束响应避免服务抛出异常
# Receive end response to avoid exception
await ws.recv()
# 根据配置决定是否保存文件
# Decide whether to save file based on config
if not self.delete_audio_file and self.save_path:
with open(self.save_path, "wb") as f:
f.write(wav_data)
logger.bind(tag=TAG).info(f"音频文件已保存到: {self.save_path}")
logger.bind(tag=TAG).info(f"Audio file saved to: {self.save_path}")
# 返回或保存音频数据
# Return or save audio data
if output_file:
with open(output_file, "wb") as file_to_save:
file_to_save.write(wav_data)

View file

@ -24,19 +24,19 @@ logger = setup_logging()
class XunfeiWSAuth:
@staticmethod
def create_auth_url(api_key, api_secret, api_url):
"""生成讯飞WebSocket认证URL"""
"""Generate Xunfei WebSocket Auth URL"""
parsed_url = urlparse(api_url)
host = parsed_url.netloc
path = parsed_url.path
# 获取UTC时间,讯飞要求使用RFC1123格式
# Get UTC time, Xunfei requires RFC1123 format
now = time.gmtime()
date = time.strftime('%a, %d %b %Y %H:%M:%S GMT', now)
# 构造签名字符串
# Construct signature string
signature_origin = f"host: {host}\ndate: {date}\nGET {path} HTTP/1.1"
# 计算签名
# Calculate signature
signature_sha = hmac.new(
api_secret.encode('utf-8'),
signature_origin.encode('utf-8'),
@ -44,11 +44,11 @@ class XunfeiWSAuth:
).digest()
signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')
# 构造authorization
# Construct authorization
authorization_origin = f'api_key="{api_key}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'
authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
# 构造最终的WebSocket URL
# Construct final WebSocket URL
v = {
"authorization": authorization,
"date": date,
@ -62,23 +62,23 @@ class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
# 设置为流式接口类型
# Set to stream interface type
self.interface_type = InterfaceType.DUAL_STREAM
# 基础配置
# Basic config
self.app_id = config.get("app_id")
self.api_key = config.get("api_key")
self.api_secret = config.get("api_secret")
# 接口地址
# Interface address
self.api_url = config.get("api_url", "wss://cbm01.cn-huabei-1.xf-yun.com/v1/private/mcd9m97e6")
# 音色配置
# Voice config
self.voice = config.get("voice", "x5_lingxiaoxuan_flow")
if config.get("private_voice"):
self.voice = config.get("private_voice")
# 音频参数配置
# Audio parameter config
speed = config.get("speed", "50")
self.speed = int(speed) if speed else 50
@ -88,13 +88,13 @@ class TTSProvider(TTSProviderBase):
pitch = config.get("pitch", "50")
self.pitch = int(pitch) if pitch else 50
# 音频编码配置
# Audio encoding config
self.format = config.get("format", "raw")
sample_rate = config.get("sample_rate", "24000")
self.sample_rate = int(sample_rate) if sample_rate else 24000
# 口语化配置
# Colloquial config
self.oral_level = config.get("oral_level", "mid")
spark_assist = config.get("spark_assist", "1")
@ -106,28 +106,28 @@ class TTSProvider(TTSProviderBase):
remain = config.get("remain", "0")
self.remain = int(remain) if remain else 0
# WebSocket配置
# WebSocket config
self.ws = None
self._monitor_task = None
# 序列号管理
# Sequence number management
self.text_seq = 0
# 创建Opus编码器
# Create Opus encoder
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
sample_rate=self.sample_rate, channels=1, frame_size_ms=60
)
# 验证必需参数
# Verify required parameters
if not all([self.app_id, self.api_key, self.api_secret]):
raise ValueError("讯飞TTS需要配置app_id、api_key和api_secret")
raise ValueError("Xunfei TTS requires app_id, api_key and api_secret")
async def _ensure_connection(self):
"""确保WebSocket连接可用"""
"""Ensure WebSocket connection is available"""
try:
logger.bind(tag=TAG).info("开始建立新连接...")
logger.bind(tag=TAG).info("Starting to establish new connection...")
# 生成认证URL
# Generate Auth URL
auth_url = XunfeiWSAuth.create_auth_url(
self.api_key, self.api_secret, self.api_url
)
@ -138,113 +138,113 @@ class TTSProvider(TTSProviderBase):
ping_timeout=10,
close_timeout=10,
)
logger.bind(tag=TAG).info("WebSocket连接建立成功")
logger.bind(tag=TAG).info("WebSocket connection established successfully")
return self.ws
except Exception as e:
logger.bind(tag=TAG).error(f"建立连接失败: {str(e)}")
logger.bind(tag=TAG).error(f"Connection failed: {str(e)}")
self.ws = None
raise
def tts_text_priority_thread(self):
"""流式文本处理线程"""
"""Streaming text processing thread"""
while not self.conn.stop_event.is_set():
try:
message = self.tts_text_queue.get(timeout=1)
logger.bind(tag=TAG).debug(
f"收到TTS任务|{message.sentence_type.name} | {message.content_type.name} | 会话ID: {self.conn.sentence_id}"
f"Received TTS task | {message.sentence_type.name} | {message.content_type.name} | Session ID: {self.conn.sentence_id}"
)
if message.sentence_type == SentenceType.FIRST:
# 重置序列号
# Reset sequence number
self.text_seq = 0
self.conn.client_abort = False
# 增加序列号
# Increment sequence number
self.text_seq += 1
if self.conn.client_abort:
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
logger.bind(tag=TAG).info("Received interrupt info, terminating TTS text processing thread")
continue
if message.sentence_type == SentenceType.FIRST:
# 初始化参数
# Initialize parameters
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).info(f"Automatically generated new Session ID: {self.conn.sentence_id}")
logger.bind(tag=TAG).info("开始启动TTS会话...")
logger.bind(tag=TAG).info("Starting TTS session...")
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).info("TTS session started successfully")
except Exception as e:
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to start TTS session: {str(e)}")
continue
# 处理文本内容
# Process text content
if ContentType.TEXT == message.content_type:
if message.content_detail:
try:
logger.bind(tag=TAG).debug(
f"开始发送TTS文本: {message.content_detail}"
f"Starting to send TTS text: {message.content_detail}"
)
future = asyncio.run_coroutine_threadsafe(
self.text_to_speak(message.content_detail, None),
loop=self.conn.loop,
)
future.result()
logger.bind(tag=TAG).debug("TTS文本发送成功")
logger.bind(tag=TAG).debug("TTS text sent successfully")
except Exception as e:
logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
# 不使用continue,确保后续处理不被中断
logger.bind(tag=TAG).error(f"Failed to send TTS text: {str(e)}")
# Do not use continue, ensure subsequent processing is not interrupted
# 处理文件内容
# Process file content
if ContentType.FILE == message.content_type:
logger.bind(tag=TAG).info(
f"添加音频文件到待播放列表: {message.content_file}"
f"Adding audio file to playlist: {message.content_file}"
)
if message.content_file and os.path.exists(message.content_file):
# 先处理文件音频数据
# Process file audio data first
self._process_audio_file_stream(message.content_file, callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail))
# 处理会话结束
# Process session end
if message.sentence_type == SentenceType.LAST:
try:
logger.bind(tag=TAG).info("开始结束TTS会话...")
logger.bind(tag=TAG).info("Starting to end TTS session...")
asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
except Exception as e:
logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to end TTS session: {str(e)}")
continue
except queue.Empty:
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
f"Failed to process TTS text: {str(e)}, Type: {type(e).__name__}, Stack: {traceback.format_exc()}"
)
async def text_to_speak(self, text, _):
"""发送文本到TTS服务进行合成"""
"""Send text to TTS service for synthesis"""
try:
if self.ws is None:
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
logger.bind(tag=TAG).warning(f"WebSocket connection does not exist, stop sending text")
return
filtered_text = MarkdownCleaner.clean_markdown(text)
if filtered_text:
# 发送文本合成请求
# Send text synthesis request
run_request = self._build_base_request(status=1,text=filtered_text)
await self.ws.send(json.dumps(run_request))
return
except Exception as e:
logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to send TTS text: {str(e)}")
if self.ws:
try:
await self.ws.close()
@ -254,59 +254,59 @@ class TTSProvider(TTSProviderBase):
raise
async def start_session(self, session_id):
logger.bind(tag=TAG).info(f"开始会话~~{session_id}")
logger.bind(tag=TAG).info(f"Starting session~~{session_id}")
try:
# 会话开始时检测上个会话的监听状态
# Check listening status of previous session when session starts
if (
self._monitor_task is not None
and isinstance(self._monitor_task, Task)
and not self._monitor_task.done()
):
logger.bind(tag=TAG).info(
"检测到未完成的上个会话,关闭监听任务和连接..."
"Detected incomplete previous session, closing monitoring task and connection..."
)
await self.close()
# 建立新连接
# Establish new connection
await self._ensure_connection()
# 启动监听任务
# Start monitoring task
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
# 发送会话启动请求
# Send session start request
start_request = self._build_base_request(status=0)
await self.ws.send(json.dumps(start_request))
logger.bind(tag=TAG).info("会话启动请求已发送")
logger.bind(tag=TAG).info("Session start request sent")
except Exception as e:
logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
# 确保清理资源
logger.bind(tag=TAG).error(f"Failed to start session: {str(e)}")
# Ensure resources are cleaned up
await self.close()
raise
async def finish_session(self, session_id):
logger.bind(tag=TAG).info(f"关闭会话~~{session_id}")
logger.bind(tag=TAG).info(f"Closing session~~{session_id}")
try:
if self.ws:
# 发送会话结束请求
# Send session end request
stop_request = self._build_base_request(status=2)
await self.ws.send(json.dumps(stop_request))
logger.bind(tag=TAG).info("会话结束请求已发送")
logger.bind(tag=TAG).info("Session end request sent")
if self._monitor_task:
try:
await self._monitor_task
except Exception as e:
logger.bind(tag=TAG).error(f"等待监听任务完成时发生错误: {str(e)}")
logger.bind(tag=TAG).error(f"Error waiting for monitoring task to complete: {str(e)}")
finally:
self._monitor_task = None
except Exception as e:
logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to close session: {str(e)}")
await self.close()
raise
async def close(self):
"""资源清理"""
"""Resource cleanup"""
if self._monitor_task:
try:
self._monitor_task.cancel()
@ -314,7 +314,7 @@ class TTSProvider(TTSProviderBase):
except asyncio.CancelledError:
pass
except Exception as e:
logger.bind(tag=TAG).warning(f"关闭时取消监听任务错误: {e}")
logger.bind(tag=TAG).warning(f"Error cancelling monitoring task during close: {e}")
self._monitor_task = None
if self.ws:
@ -325,15 +325,15 @@ class TTSProvider(TTSProviderBase):
self.ws = None
async def _start_monitor_tts_response(self):
"""监听TTS响应"""
"""Monitor TTS response"""
try:
while not self.conn.stop_event.is_set():
try:
msg = await self.ws.recv()
# 检查客户端是否中止
# Check if client aborted
if self.conn.client_abort:
logger.bind(tag=TAG).info("收到打断信息,终止监听TTS响应")
logger.bind(tag=TAG).info("Received interrupt info, stop monitoring TTS response")
break
try:
@ -349,18 +349,18 @@ class TTSProvider(TTSProviderBase):
status = audio_payload.get("status", 0)
audio_data = audio_payload.get("audio", "")
if status == 0:
logger.bind(tag=TAG).debug("TTS合成已启动")
logger.bind(tag=TAG).debug("TTS synthesis started")
self.tts_audio_queue.put(
(SentenceType.FIRST, [], None)
)
elif status == 2:
logger.bind(tag=TAG).debug("收到结束状态的音频数据,TTS合成完成")
logger.bind(tag=TAG).debug("Received end status audio data, TTS synthesis completed")
self._process_before_stop_play_files()
break
else:
if self.conn.tts_MessageText:
logger.bind(tag=TAG).info(
f"句子语音生成成功: {self.conn.tts_MessageText}"
f"Sentence voice generation successful: {self.conn.tts_MessageText}"
)
self.tts_audio_queue.put(
(SentenceType.FIRST, [], self.conn.tts_MessageText)
@ -373,54 +373,54 @@ class TTSProvider(TTSProviderBase):
)
except Exception as e:
logger.bind(tag=TAG).error(f"处理音频数据失败: {e}")
logger.bind(tag=TAG).error(f"Failed to process audio data: {e}")
else:
message = header.get("message", "未知错误")
logger.bind(tag=TAG).error(f"TTS合成错误: {code} - {message}")
message = header.get("message", "Unknown error")
logger.bind(tag=TAG).error(f"TTS synthesis error: {code} - {message}")
break
except json.JSONDecodeError:
logger.bind(tag=TAG).warning("收到无效的JSON消息")
logger.bind(tag=TAG).warning("Received invalid JSON message")
except websockets.ConnectionClosed:
logger.bind(tag=TAG).warning("WebSocket连接已关闭")
logger.bind(tag=TAG).warning("WebSocket connection closed")
break
except Exception as e:
logger.bind(tag=TAG).error(
f"处理TTS响应时出错: {e}\n{traceback.format_exc()}"
f"Error processing TTS response: {e}\n{traceback.format_exc()}"
)
break
# 链接不可复用
# Connection not reusable
if self.ws:
try:
await self.ws.close()
except:
pass
self.ws = None
# 监听任务退出时清理引用
# Clean up reference when monitoring task exits
finally:
self._monitor_task = None
def to_tts(self, text: str) -> list:
"""非流式TTS处理,用于测试及保存音频文件的场景"""
"""Non-streaming TTS processing, used for testing and saving audio files"""
try:
# 创建新的事件循环
# Create new event loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# 存储音频数据
# Store audio data
audio_data = []
async def _generate_audio():
# 生成认证URL
# Generate Auth URL
auth_url = XunfeiWSAuth.create_auth_url(
self.api_key, self.api_secret, self.api_url
)
# 建立WebSocket连接
# Establish WebSocket connection
ws = await websockets.connect(
auth_url,
ping_interval=30,
@ -458,17 +458,17 @@ class TTSProvider(TTSProviderBase):
callback=lambda opus: audio_data.append(opus)
)
except Exception as e:
logger.bind(tag=TAG).error(f"处理音频数据失败: {e}")
logger.bind(tag=TAG).error(f"Failed to process audio data: {e}")
elif status == 2:
task_finished = True
logger.bind(tag=TAG).debug("TTS任务完成")
logger.bind(tag=TAG).debug("TTS task completed")
else:
message = header.get("message", "未知错误")
raise Exception(f"合成失败: {code} - {message}")
message = header.get("message", "Unknown error")
raise Exception(f"Synthesis failed: {code} - {message}")
finally:
# 清理资源
# Clean up resources
try:
await ws.close()
except:
@ -479,11 +479,11 @@ class TTSProvider(TTSProviderBase):
return audio_data
except Exception as e:
logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to generate audio data: {str(e)}")
return []
def _build_base_request(self, status,text=" "):
"""构建基础请求结构"""
"""Build base request structure"""
return {
"header": {
"app_id": self.app_id,

View file

@ -5,5 +5,5 @@ from typing import Optional
class VADProviderBase(ABC):
@abstractmethod
def is_vad(self, conn, data) -> bool:
"""检测音频数据中的语音活动"""
"""Detect voice activity in audio data"""
pass

View file

@ -21,7 +21,7 @@ class VADProvider(VADProviderBase):
self.decoder = opuslib_next.Decoder(16000, 1)
# 处理空字符串的情况
# Handle empty string case
threshold = config.get("threshold", "0.5")
threshold_low = config.get("threshold_low", "0.2")
min_silence_duration_ms = config.get("min_silence_duration_ms", "1000")
@ -33,7 +33,7 @@ class VADProvider(VADProviderBase):
int(min_silence_duration_ms) if min_silence_duration_ms else 1000
)
# 至少要多少帧才算有语音
# Minimum frames to count as voice
self.frame_window_threshold = 3
def __del__(self):
@ -44,31 +44,31 @@ class VADProvider(VADProviderBase):
pass
def is_vad(self, conn, opus_packet):
# 手动模式:直接返回True,不进行实时VAD检测,所有音频都缓存
# Manual mode: return True directly, no real-time VAD detection, buffer all audio
if conn.client_listen_mode == "manual":
return True
try:
pcm_frame = self.decoder.decode(opus_packet, 960)
conn.client_audio_buffer.extend(pcm_frame) # 将新数据加入缓冲区
conn.client_audio_buffer.extend(pcm_frame) # Add new data to buffer
# 处理缓冲区中的完整帧(每次处理512采样点)
# Process complete frames in buffer (512 samples each)
client_have_voice = False
while len(conn.client_audio_buffer) >= 512 * 2:
# 提取前512个采样点(1024字节)
# Extract first 512 samples (1024 bytes)
chunk = conn.client_audio_buffer[: 512 * 2]
conn.client_audio_buffer = conn.client_audio_buffer[512 * 2 :]
# 转换为模型需要的张量格式
# Convert to tensor format required by model
audio_int16 = np.frombuffer(chunk, dtype=np.int16)
audio_float32 = audio_int16.astype(np.float32) / 32768.0
audio_tensor = torch.from_numpy(audio_float32)
# 检测语音活动
# Detect voice activity
with torch.no_grad():
speech_prob = self.model(audio_tensor, 16000).item()
# 双阈值判断
# Dual threshold judgment
if speech_prob >= self.vad_threshold:
is_voice = True
elif speech_prob <= self.vad_threshold_low:
@ -76,16 +76,16 @@ class VADProvider(VADProviderBase):
else:
is_voice = conn.last_is_voice
# 声音没低于最低值则延续前一个状态,判断为有声音
# If sound not below min threshold, continue previous state, judge as voice present
conn.last_is_voice = is_voice
# 更新滑动窗口
# Update sliding window
conn.client_voice_window.append(is_voice)
client_have_voice = (
conn.client_voice_window.count(True) >= self.frame_window_threshold
)
# 如果之前有声音,但本次没有声音,且与上次有声音的时间差已经超过了静默阈值,则认为已经说完一句话
# If previously voice present, but now silent, and time since last voice exceeds silence threshold, sentence is finished
if conn.client_have_voice and not client_have_voice:
stop_duration = time.time() * 1000 - conn.last_activity_time
if stop_duration >= self.silence_threshold_ms:
@ -96,6 +96,6 @@ class VADProvider(VADProviderBase):
return client_have_voice
except opuslib_next.OpusError as e:
logger.bind(tag=TAG).info(f"解码错误: {e}")
logger.bind(tag=TAG).info(f"Decoding error: {e}")
except Exception as e:
logger.bind(tag=TAG).error(f"Error processing audio packet: {e}")

View file

@ -40,7 +40,7 @@ class VLLMProvider(VLLMProviderBase):
self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url)
def response(self, question, base64_image):
question = question + "(请使用中文回复)"
question = question + "(Please reply in English)"
try:
messages = [
{

View file

@ -14,11 +14,11 @@ TAG = __name__
logger = setup_logging()
def create_instance(class_name: str, *args, **kwargs) -> ASRProviderBase:
"""工厂方法创建ASR实例"""
"""Factory method for creating ASR instance"""
if os.path.exists(os.path.join('core', 'providers', 'asr', f'{class_name}.py')):
lib_name = f'core.providers.asr.{class_name}'
if lib_name not in sys.modules:
sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
return sys.modules[lib_name].ASRProvider(*args, **kwargs)
raise ValueError(f"不支持的ASR类型: {class_name},请检查该配置的type是否设置正确")
raise ValueError(f"Unsupported ASR type: {class_name}, please check if the type in config is set correctly")

View file

@ -9,82 +9,82 @@ logger = setup_logging()
class AudioRateController:
"""
音频速率控制器 - 按照60ms帧时长精确控制音频发送
解决高并发下的时间累积误差问题
Audio Rate Controller - Precisely controls audio sending based on 60ms frame duration
Solves time accumulation error in high concurrency
"""
def __init__(self, frame_duration=60):
"""
Args:
frame_duration: 单个音频帧时长(毫秒),默认60ms
frame_duration: Duration of a single audio frame (ms), default 60ms
"""
self.frame_duration = frame_duration
self.queue = deque()
self.play_position = 0 # 虚拟播放位置(毫秒)
self.start_timestamp = None # 开始时间戳(只读,不修改)
self.play_position = 0 # Virtual playback position (ms)
self.start_timestamp = None # Start timestamp (read-only, not modified)
self.pending_send_task = None
self.logger = logger
self.queue_empty_event = asyncio.Event() # 队列清空事件
self.queue_empty_event.set() # 初始为空状态
self.queue_has_data_event = asyncio.Event() # 队列数据事件
self.queue_empty_event = asyncio.Event() # Queue empty event
self.queue_empty_event.set() # Initial state is empty
self.queue_has_data_event = asyncio.Event() # Queue has data event
def reset(self):
"""重置控制器状态"""
"""Reset controller state"""
if self.pending_send_task and not self.pending_send_task.done():
self.pending_send_task.cancel()
# 取消任务后,任务会在下次事件循环时清理,无需阻塞等待
# After cancelling task, it will be cleaned up in next event loop, no need to block wait
self.queue.clear()
self.play_position = 0
self.start_timestamp = None # 由首个音频包设置
# 相关事件处理
self.start_timestamp = None # Set by the first audio packet
# Event handling
self.queue_empty_event.set()
self.queue_has_data_event.clear()
def add_audio(self, opus_packet):
"""添加音频包到队列"""
"""Add audio packet to queue"""
self.queue.append(("audio", opus_packet))
# 相关事件处理
# Event handling
self.queue_empty_event.clear()
self.queue_has_data_event.set()
def add_message(self, message_callback):
"""
添加消息到队列(立即发送,不占用播放时间)
Add message to queue (send immediately, does not consume playback time)
Args:
message_callback: 消息发送回调函数 async def()
message_callback: Message sending callback function async def()
"""
self.queue.append(("message", message_callback))
# 相关事件处理
# Event handling
self.queue_empty_event.clear()
self.queue_has_data_event.set()
def _get_elapsed_ms(self):
"""获取已经过的时间(毫秒)"""
"""Get elapsed time (ms)"""
if self.start_timestamp is None:
return 0
return (time.monotonic() - self.start_timestamp) * 1000
async def check_queue(self, send_audio_callback):
"""
检查队列并按时发送音频/消息
Check queue and send audio/message on time
Args:
send_audio_callback: 发送音频的回调函数 async def(opus_packet)
send_audio_callback: Audio sending callback function async def(opus_packet)
"""
while self.queue:
item = self.queue[0]
item_type = item[0]
if item_type == "message":
# 消息类型:立即发送,不占用播放时间
# Message type: send immediately, does not consume playback time
_, message_callback = item
self.queue.popleft()
try:
await message_callback()
except Exception as e:
self.logger.bind(tag=TAG).error(f"发送消息失败: {e}")
self.logger.bind(tag=TAG).error(f"Failed to send message: {e}")
raise
elif item_type == "audio":
@ -93,68 +93,73 @@ class AudioRateController:
_, opus_packet = item
# 循环等待直到时间到达
# Loop wait until time is up
while True:
# 计算时间差
# Calculate time difference
elapsed_ms = self._get_elapsed_ms()
output_ms = self.play_position
if elapsed_ms < output_ms:
# 还不到发送时间,计算等待时长
# Not time to send yet, calculate wait duration
wait_ms = output_ms - elapsed_ms
# 等待后继续检查(允许被中断)
# Continue check after wait (allow interruption)
try:
await asyncio.sleep(wait_ms / 1000)
except asyncio.CancelledError:
self.logger.bind(tag=TAG).debug("音频发送任务被取消")
self.logger.bind(tag=TAG).debug("Audio sending task cancelled")
raise
# 等待结束后重新检查时间(循环回到 while True)
# Re-check time after wait (loop back to while True)
else:
# 时间已到,跳出等待循环
# Time is up, break wait loop
break
# 时间已到,从队列移除并发送
# Time is up, remove from queue and send
self.queue.popleft()
self.play_position += self.frame_duration
try:
await send_audio_callback(opus_packet)
except Exception as e:
self.logger.bind(tag=TAG).error(f"发送音频失败: {e}")
raise
self.logger.bind(tag=TAG).error(f"Failed to send audio: {e}")
# Do not re-raise to prevent killing the loop
# raise
# 队列处理完后清除事件
# Clear events after processing queue
self.queue_empty_event.set()
self.queue_has_data_event.clear()
def start_sending(self, send_audio_callback):
"""
启动异步发送任务
Start asynchronous sending task
Args:
send_audio_callback: 发送音频的回调函数
send_audio_callback: Audio sending callback function
Returns:
asyncio.Task: 发送任务
asyncio.Task: Sending task
"""
async def _send_loop():
try:
while True:
# 等待队列数据事件,不轮询等待占用CPU
# Wait for queue data event, do not poll to save CPU
await self.queue_has_data_event.wait()
await self.check_queue(send_audio_callback)
except asyncio.CancelledError:
self.logger.bind(tag=TAG).debug("音频发送循环已停止")
self.logger.bind(tag=TAG).debug("Audio sending loop stopped")
except Exception as e:
self.logger.bind(tag=TAG).error(f"音频发送循环异常: {e}")
self.logger.bind(tag=TAG).error(f"Audio send loop exception: {e}")
finally:
# Ensure event is set so waiters don't hang
self.queue_empty_event.set()
self.logger.bind(tag=TAG).debug("Audio send loop exited, queue_empty_event set")
self.pending_send_task = asyncio.create_task(_send_loop())
return self.pending_send_task
def stop_sending(self):
"""停止发送任务"""
"""Stop sending task"""
if self.pending_send_task and not self.pending_send_task.done():
self.pending_send_task.cancel()
self.logger.bind(tag=TAG).debug("已取消音频发送任务")
self.logger.bind(tag=TAG).debug("Audio sending task cancelled")

View file

@ -1,5 +1,5 @@
"""
全局缓存管理器
Global Cache Manager
"""
import time
@ -11,7 +11,7 @@ from .config import CacheConfig, CacheType
class GlobalCacheManager:
"""全局缓存管理器"""
"""Global Cache Manager"""
def __init__(self):
self._logger = None
@ -24,7 +24,7 @@ class GlobalCacheManager:
@property
def logger(self):
"""延迟初始化 logger 以避免循环导入"""
"""Delay logger initialization to avoid circular import"""
if self._logger is None:
from config.logger import setup_logging
@ -32,7 +32,7 @@ class GlobalCacheManager:
return self._logger
def _get_cache_name(self, cache_type: CacheType, namespace: str = "") -> str:
"""生成缓存名称"""
"""Generate cache name"""
if namespace:
return f"{cache_type.value}:{namespace}"
return cache_type.value
@ -40,7 +40,7 @@ class GlobalCacheManager:
def _get_or_create_cache(
self, cache_name: str, config: CacheConfig
) -> Dict[str, CacheEntry]:
"""获取或创建缓存空间"""
"""Get or create cache space"""
with self._global_lock:
if cache_name not in self._caches:
self._caches[cache_name] = (
@ -60,28 +60,28 @@ class GlobalCacheManager:
ttl: Optional[float] = None,
namespace: str = "",
) -> None:
"""设置缓存值"""
"""Set cache value"""
cache_name = self._get_cache_name(cache_type, namespace)
config = self._configs.get(cache_name) or CacheConfig.for_type(cache_type)
cache = self._get_or_create_cache(cache_name, config)
# 使用配置的TTL或传入的TTL
# Use configured TTL or passed TTL
effective_ttl = ttl if ttl is not None else config.ttl
with self._locks[cache_name]:
# 创建缓存条目
# Create cache entry
entry = CacheEntry(value=value, timestamp=time.time(), ttl=effective_ttl)
# 处理不同策略
if config.strategy in [CacheStrategy.LRU, CacheStrategy.TTL_LRU]:
# LRU策略:如果已存在则移动到末尾
# LRU strategy: if exists, move to end
if key in cache:
del cache[key]
cache[key] = entry
# 检查大小限制
# Check size limit
if config.max_size and len(cache) > config.max_size:
# 移除最旧的条目
# Remove oldest entry
oldest_key = next(iter(cache))
del cache[oldest_key]
self._stats["evictions"] += 1
@ -89,20 +89,20 @@ class GlobalCacheManager:
else:
cache[key] = entry
# 检查大小限制
# Check size limit
if config.max_size and len(cache) > config.max_size:
# 简单策略:随机移除一个条目
# Simple strategy: randomly remove one entry
victim_key = next(iter(cache))
del cache[victim_key]
self._stats["evictions"] += 1
# 定期清理过期条目
# Periodically clean up expired entries
self._maybe_cleanup(cache_name)
def get(
self, cache_type: CacheType, key: str, namespace: str = ""
) -> Optional[Any]:
"""获取缓存值"""
"""Get cache value"""
cache_name = self._get_cache_name(cache_type, namespace)
if cache_name not in self._caches:
@ -119,16 +119,16 @@ class GlobalCacheManager:
entry = cache[key]
# 检查过期
# Check expiration
if entry.is_expired():
del cache[key]
self._stats["misses"] += 1
return None
# 更新访问信息
# Update access info
entry.touch()
# LRU策略:移动到末尾
# LRU strategy: move to end
if config.strategy in [CacheStrategy.LRU, CacheStrategy.TTL_LRU]:
del cache[key]
cache[key] = entry
@ -137,7 +137,7 @@ class GlobalCacheManager:
return entry.value
def delete(self, cache_type: CacheType, key: str, namespace: str = "") -> bool:
"""删除缓存条目"""
"""Delete cache entry"""
cache_name = self._get_cache_name(cache_type, namespace)
if cache_name not in self._caches:
@ -152,7 +152,7 @@ class GlobalCacheManager:
return False
def clear(self, cache_type: CacheType, namespace: str = "") -> None:
"""清空指定缓存"""
"""Clear specified cache"""
cache_name = self._get_cache_name(cache_type, namespace)
if cache_name not in self._caches:
@ -164,7 +164,7 @@ class GlobalCacheManager:
def invalidate_pattern(
self, cache_type: CacheType, pattern: str, namespace: str = ""
) -> int:
"""按模式失效缓存条目"""
"""Invalidate cache entries by pattern"""
cache_name = self._get_cache_name(cache_type, namespace)
if cache_name not in self._caches:
@ -182,7 +182,7 @@ class GlobalCacheManager:
return deleted_count
def _cleanup_expired(self, cache_name: str) -> int:
"""清理过期条目"""
"""Clean up expired entries"""
if cache_name not in self._caches:
return 0
@ -198,7 +198,7 @@ class GlobalCacheManager:
return deleted_count
def _maybe_cleanup(self, cache_name: str):
"""定期清理检查"""
"""Periodic cleanup check"""
config = self._configs.get(cache_name)
if not config:
return
@ -209,8 +209,8 @@ class GlobalCacheManager:
deleted = self._cleanup_expired(cache_name)
if deleted > 0:
self._stats["cleanups"] += 1
self.logger.debug(f"清理缓存 {cache_name}: 删除 {deleted} 个过期条目")
self.logger.debug(f"Cleaning cache {cache_name}: deleted {deleted} expired entries")
# 创建全局缓存管理器实例
# Create global cache manager instance
cache_manager = GlobalCacheManager()

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