mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge branch 'xinnan-tech:main' into main
This commit is contained in:
commit
bfd2827dd6
161 changed files with 26081 additions and 1448 deletions
2
.github/workflows/build-base-image.yml
vendored
2
.github/workflows/build-base-image.yml
vendored
|
|
@ -37,7 +37,7 @@ jobs:
|
||||||
file: Dockerfile-server-base
|
file: Dockerfile-server-base
|
||||||
push: true
|
push: true
|
||||||
tags: ghcr.io/${{ github.repository }}:server-base
|
tags: ghcr.io/${{ github.repository }}:server-base
|
||||||
platforms: linux/amd64
|
platforms: linux/amd64,linux/arm64
|
||||||
cache-from: type=gha,scope=server-base
|
cache-from: type=gha,scope=server-base
|
||||||
cache-to: type=gha,mode=max,scope=server-base
|
cache-to: type=gha,mode=max,scope=server-base
|
||||||
build-args: |
|
build-args: |
|
||||||
|
|
|
||||||
4
.github/workflows/docker-image.yml
vendored
4
.github/workflows/docker-image.yml
vendored
|
|
@ -66,7 +66,7 @@ jobs:
|
||||||
push: true
|
push: true
|
||||||
tags: |
|
tags: |
|
||||||
${{ env.IS_VERSION == 'true' && format('ghcr.io/{0}:server_{1},ghcr.io/{0}:server_latest', github.repository, env.VERSION) || format('ghcr.io/{0}:server_latest', github.repository) }}
|
${{ env.IS_VERSION == 'true' && format('ghcr.io/{0}:server_{1},ghcr.io/{0}:server_latest', github.repository, env.VERSION) || format('ghcr.io/{0}:server_latest', github.repository) }}
|
||||||
platforms: linux/amd64
|
platforms: linux/amd64,linux/arm64
|
||||||
cache-from: type=gha
|
cache-from: type=gha
|
||||||
cache-to: type=gha,mode=max
|
cache-to: type=gha,mode=max
|
||||||
build-args: |
|
build-args: |
|
||||||
|
|
@ -81,7 +81,7 @@ jobs:
|
||||||
push: true
|
push: true
|
||||||
tags: |
|
tags: |
|
||||||
${{ env.IS_VERSION == 'true' && format('ghcr.io/{0}:web_{1},ghcr.io/{0}:web_latest', github.repository, env.VERSION) || format('ghcr.io/{0}:web_latest', github.repository) }}
|
${{ env.IS_VERSION == 'true' && format('ghcr.io/{0}:web_{1},ghcr.io/{0}:web_latest', github.repository, env.VERSION) || format('ghcr.io/{0}:web_latest', github.repository) }}
|
||||||
platforms: linux/amd64
|
platforms: linux/amd64,linux/arm64
|
||||||
cache-from: type=gha
|
cache-from: type=gha
|
||||||
cache-to: type=gha,mode=max
|
cache-to: type=gha,mode=max
|
||||||
build-args: |
|
build-args: |
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
# 第一阶段:构建Vue前端
|
# 第一阶段:构建Vue前端
|
||||||
FROM node:18 as web-builder
|
FROM node:18 AS web-builder
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY main/manager-web/package*.json ./
|
COPY main/manager-web/package*.json ./
|
||||||
RUN npm install
|
RUN npm install
|
||||||
|
|
@ -7,7 +7,7 @@ COPY main/manager-web .
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
# 第二阶段:构建Java后端
|
# 第二阶段:构建Java后端
|
||||||
FROM maven:3.9.4-eclipse-temurin-21 as api-builder
|
FROM maven:3.9.4-eclipse-temurin-21 AS api-builder
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY main/manager-api/pom.xml .
|
COPY main/manager-api/pom.xml .
|
||||||
COPY main/manager-api/src ./src
|
COPY main/manager-api/src ./src
|
||||||
|
|
@ -18,18 +18,19 @@ FROM bellsoft/liberica-runtime-container:jre-21-glibc
|
||||||
|
|
||||||
# 安装Nginx和字体库
|
# 安装Nginx和字体库
|
||||||
RUN apk update && \
|
RUN apk update && \
|
||||||
apk add --no-cache --repository=http://dl-cdn.alpinelinux.org/alpine/edge/testing/ \
|
apk add --no-cache --no-scripts \
|
||||||
nginx \
|
nginx \
|
||||||
bash \
|
bash \
|
||||||
fontconfig \
|
fontconfig \
|
||||||
ttf-dejavu \
|
ttf-dejavu \
|
||||||
msttcorefonts-installer \
|
&& rm -rf /var/cache/apk/* \
|
||||||
&& ACCEPT_EULA=Y apk add --no-cache msttcorefonts-installer \
|
&& mkdir -p /run/nginx /var/log/nginx /var/tmp/nginx /etc/nginx/conf.d
|
||||||
&& fc-cache -f -v \
|
|
||||||
&& rm -rf /var/cache/apk/*
|
# 复制项目自带的中文字体
|
||||||
|
COPY main/manager-web/public/generator/static/fonts/*.ttf /usr/share/fonts/
|
||||||
|
|
||||||
# 更新字体缓存
|
# 更新字体缓存
|
||||||
RUN (printf 'YES\n' | update-ms-fonts || true) && fc-cache -f -v
|
RUN fc-cache -f -v
|
||||||
|
|
||||||
# 配置Nginx
|
# 配置Nginx
|
||||||
COPY docs/docker/nginx.conf /etc/nginx/nginx.conf
|
COPY docs/docker/nginx.conf /etc/nginx/nginx.conf
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@
|
||||||
<a href="./README_en.md"><img alt="README in English" src="https://img.shields.io/badge/English-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_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||||
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||||
|
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
<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" />
|
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||||
</a>
|
</a>
|
||||||
|
|
@ -242,7 +243,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
||||||
| 智能对话 | 支持多种LLM(大语言模型),实现智能对话 |
|
| 智能对话 | 支持多种LLM(大语言模型),实现智能对话 |
|
||||||
| 视觉感知 | 支持多种VLLM(视觉大模型),实现多模态交互 |
|
| 视觉感知 | 支持多种VLLM(视觉大模型),实现多模态交互 |
|
||||||
| 意图识别 | 支持外挂的大模型意图识别、大模型自主函数调用,提供插件化意图处理机制 |
|
| 意图识别 | 支持外挂的大模型意图识别、大模型自主函数调用,提供插件化意图处理机制 |
|
||||||
| 记忆系统 | 支持本地短期记忆、mem0ai接口记忆,具备记忆总结功能 |
|
| 记忆系统 | 支持本地短期记忆、mem0ai接口记忆、PowerMem智能记忆,具备记忆总结功能 |
|
||||||
| 知识库 | 支持RAGFlow知识库,让大模型判断需要调度知识库后再回答 |
|
| 知识库 | 支持RAGFlow知识库,让大模型判断需要调度知识库后再回答 |
|
||||||
| 工具调用 | 支持客户端IOT协议、客户MCP协议、服务端MCP协议、MCP接入点协议、自定义工具函数 |
|
| 工具调用 | 支持客户端IOT协议、客户MCP协议、服务端MCP协议、MCP接入点协议、自定义工具函数 |
|
||||||
| 指令下发 | 依托MQTT协议,支持从智控台将MCP指令下发到ESP32设备 |
|
| 指令下发 | 依托MQTT协议,支持从智控台将MCP指令下发到ESP32设备 |
|
||||||
|
|
@ -330,6 +331,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
||||||
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
| 类型 | 平台名称 | 使用方式 | 收费模式 | 备注 |
|
||||||
|:------:|:---------------:|:----:|:---------:|:--:|
|
|:------:|:---------------:|:----:|:---------:|:--:|
|
||||||
| Memory | mem0ai | 接口调用 | 1000次/月额度 | |
|
| Memory | mem0ai | 接口调用 | 1000次/月额度 | |
|
||||||
|
| Memory | [powermem](./docs/powermem-integration.md) | 本地总结 | 取决于LLM和DB | OceanBase开源,支持智能检索 |
|
||||||
| Memory | mem_local_short | 本地总结 | 免费 | |
|
| Memory | mem_local_short | 本地总结 | 免费 | |
|
||||||
| Memory | nomem | 无记忆模式 | 免费 | |
|
| Memory | nomem | 无记忆模式 | 免费 | |
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@ Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Endpunkte und Stimmabd
|
||||||
<a href="./README_en.md"><img alt="README in English" src="https://img.shields.io/badge/English-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_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||||
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DBEDFA"></a>
|
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DBEDFA"></a>
|
||||||
|
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
<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" />
|
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||||
</a>
|
</a>
|
||||||
|
|
@ -240,7 +241,7 @@ Dieses Projekt bietet die folgenden Testwerkzeuge, um Ihnen bei der Überprüfun
|
||||||
| Intelligenter Dialog | Unterstützt mehrere LLM (große Sprachmodelle), implementiert intelligenten Dialog |
|
| Intelligenter Dialog | Unterstützt mehrere LLM (große Sprachmodelle), implementiert intelligenten Dialog |
|
||||||
| Visuelle Wahrnehmung | Unterstützt mehrere VLLM (Vision Large Models), implementiert multimodale Interaktion |
|
| Visuelle Wahrnehmung | Unterstützt mehrere VLLM (Vision Large Models), implementiert multimodale Interaktion |
|
||||||
| Absichtserkennung | Unterstützt LLM-Absichtserkennung, Function Call-Funktionsaufruf, bietet plugin-basierten Absichtsverarbeitungsmechanismus |
|
| Absichtserkennung | Unterstützt LLM-Absichtserkennung, Function Call-Funktionsaufruf, bietet plugin-basierten Absichtsverarbeitungsmechanismus |
|
||||||
| Gedächtnissystem | Unterstützt lokales Kurzzeitgedächtnis, mem0ai-Schnittstellengedächtnis, mit Gedächtniszusammenfassungsfunktion |
|
| Gedächtnissystem | Unterstützt lokales Kurzzeitgedächtnis, mem0ai-Schnittstellengedächtnis, PowerMem intelligentes Gedächtnis, mit Gedächtniszusammenfassungsfunktion |
|
||||||
| Wissensdatenbank | Unterstützt RAGFlow-Wissensdatenbank, ermöglicht großem Modell die Bewertung, ob Wissensdatenbank benötigt wird, bevor geantwortet wird |
|
| Wissensdatenbank | Unterstützt RAGFlow-Wissensdatenbank, ermöglicht großem Modell die Bewertung, ob Wissensdatenbank benötigt wird, bevor geantwortet wird |
|
||||||
| Werkzeugaufruf | Unterstützt Client-IOT-Protokoll, Client-MCP-Protokoll, Server-MCP-Protokoll, MCP-Endpunktprotokoll, benutzerdefinierte Werkzeugfunktionen |
|
| Werkzeugaufruf | Unterstützt Client-IOT-Protokoll, Client-MCP-Protokoll, Server-MCP-Protokoll, MCP-Endpunktprotokoll, benutzerdefinierte Werkzeugfunktionen |
|
||||||
| Befehlsübermittlung | Basierend auf MQTT-Protokoll, unterstützt die Übermittlung von MCP-Befehlen von der intelligenten Steuerkonsole an ESP32-Geräte |
|
| Befehlsübermittlung | Basierend auf MQTT-Protokoll, unterstützt die Übermittlung von MCP-Befehlen von der intelligenten Steuerkonsole an ESP32-Geräte |
|
||||||
|
|
@ -258,7 +259,7 @@ Wenn Sie ein Softwareentwickler sind, finden Sie hier einen [Offenen Brief an En
|
||||||
---
|
---
|
||||||
|
|
||||||
## Produktökosystem 👬
|
## 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
|
Xiaozhi ist ein Ökosystem. Wenn Sie dieses Produkt verwenden, können Sie sich auch andere [hervorragende Projekte](https://github.com/78/xiaozhi-esp32/blob/main/README_zh.md#%E7%9B%B8%E5%85%B3%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE) in diesem Ökosystem ansehen
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -328,6 +329,7 @@ Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, int
|
||||||
| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
|
| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
|
||||||
|:------:|:---------------:|:----:|:---------:|:--:|
|
|:------:|:---------------:|:----:|:---------:|:--:|
|
||||||
| Memory | mem0ai | Schnittstellenaufrufe | 1000 Mal/Monat Kontingent | |
|
| Memory | mem0ai | Schnittstellenaufrufe | 1000 Mal/Monat Kontingent | |
|
||||||
|
| Memory | [powermem](./docs/powermem-integration.md) | Lokale Zusammenfassung | Abhängig von LLM und DB | OceanBase Open Source, unterstützt intelligente Abfrage |
|
||||||
| Memory | mem_local_short | Lokale Zusammenfassung | Kostenlos | |
|
| Memory | mem_local_short | Lokale Zusammenfassung | Kostenlos | |
|
||||||
| Memory | nomem | Kein Gedächtnismodus | Kostenlos | |
|
| Memory | nomem | Kein Gedächtnismodus | Kostenlos | |
|
||||||
|
|
||||||
|
|
|
||||||
32
README_en.md
32
README_en.md
|
|
@ -21,6 +21,7 @@ Support for MQTT+UDP protocol, Websocket protocol, MCP access point, voiceprint
|
||||||
<a href="./README_en.md"><img alt="README in English" src="https://img.shields.io/badge/English-DBEDFA"></a>
|
<a href="./README_en.md"><img alt="README in English" src="https://img.shields.io/badge/English-DBEDFA"></a>
|
||||||
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||||
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||||
|
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
<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" />
|
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||||
</a>
|
</a>
|
||||||
|
|
@ -182,8 +183,9 @@ This project provides two deployment methods. Please choose based on your specif
|
||||||
| Deployment Method | Features | Applicable Scenarios | Deployment Docs | Configuration Requirements | Video Tutorials |
|
| Deployment Method | Features | Applicable Scenarios | Deployment Docs | Configuration Requirements | Video Tutorials |
|
||||||
|---------|------|---------|---------|---------|---------|
|
|---------|------|---------|---------|---------|---------|
|
||||||
| **Simplified Installation** | Intelligent dialogue, single agent management | Low-configuration environments, data stored in config files, no database required | [①Docker Version](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Source Code 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 cores 4GB if using `FunASR`, 2 cores 2GB if all APIs | - |
|
| **Simplified Installation** | Intelligent dialogue, single agent management | Low-configuration environments, data stored in config files, no database required | [①Docker Version](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Source Code 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 cores 4GB if using `FunASR`, 2 cores 2GB if all APIs | - |
|
||||||
| **Full Module Installation** | Intelligent dialogue, multi-user management, multi-agent management, intelligent console interface operation | Complete functionality experience, data stored in database |[①Docker Version](./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) / [②Source Code 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) / [③Source Code Deployment Auto-Update Tutorial](./docs/dev-ops-integration.md) | 4 cores 8GB if using `FunASR`, 2 cores 4GB if all APIs| [Local Source Code Startup Video Tutorial](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
| **Full Module Installation** | Intelligent dialogue, multi-user management, multi-agent management, intelligent console interface operation | Complete functionality experience, data stored in database |[①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) / [②Source Code 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) / [③Source Code Deployment Auto-Update Tutorial](./docs/dev-ops-integration.md) | 4 cores 8GB if using `FunASR`, 2 cores 4GB if all APIs| [Local Source Code Startup Video Tutorial](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||||
|
|
||||||
|
For frequently asked questions and related tutorials, please refer to [this link](./docs/FAQ.md)
|
||||||
|
|
||||||
> 💡 Note: Below is a test platform deployed with the latest code. You can burn and test if needed. Concurrent users: 6, data will be cleared daily.
|
> 💡 Note: Below is a test platform deployed with the latest code. You can burn and test if needed. Concurrent users: 6, data will be cleared daily.
|
||||||
|
|
||||||
|
|
@ -215,14 +217,15 @@ Websocket Interface Address: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
||||||
| Intent(Intent Recognition) | function_call(Function calling) | function_call(Function calling) |
|
| Intent(Intent Recognition) | function_call(Function calling) | function_call(Function calling) |
|
||||||
| Memory(Memory function) | mem_local_short(Local short-term memory) | mem_local_short(Local short-term memory) |
|
| Memory(Memory function) | mem_local_short(Local short-term memory) | mem_local_short(Local short-term memory) |
|
||||||
|
|
||||||
|
If you are concerned about the latency of each component, please refer to the [Xiaozhi Component Performance Test Report](https://github.com/xinnan-tech/xiaozhi-performance-research), and test in your own environment following the test methods in the report.
|
||||||
|
|
||||||
#### 🔧 Testing Tools
|
#### 🔧 Testing Tools
|
||||||
This project provides the following testing tools to help you verify the system and choose suitable models:
|
This project provides the following testing tools to help you verify the system and choose suitable models:
|
||||||
|
|
||||||
| Tool Name | Location | Usage Method | Function Description |
|
| Tool Name | Location | Usage Method | Function Description |
|
||||||
|:---:|:---|:---:|:---:|
|
|:---:|:---|:---:|:---:|
|
||||||
| Audio Interaction Test Tool | main》xiaozhi-server》test》test_page.html | Open directly with Google Chrome | Tests audio playback and reception functions, verifies if Python-side audio processing is normal |
|
| Audio Interaction Test Tool | main》xiaozhi-server》test》test_page.html | Open directly with Google Chrome | Tests audio playback and reception functions, verifies if Python-side audio processing is normal |
|
||||||
| Model Response Test Tool 1 | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Tests response speed of three core modules: ASR(speech recognition), LLM(large model), TTS(speech synthesis) |
|
| Model Response Test Tool | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Tests response speed of three core modules: ASR(speech recognition), LLM(large model), VLLM(vision model), TTS(speech synthesis) |
|
||||||
| Model Response Test Tool 2 | main》xiaozhi-server》performance_tester_vllm.py | Execute `python performance_tester_vllm.py` | Tests VLLM(vision model) response speed |
|
|
||||||
|
|
||||||
> 💡 Note: When testing model speed, only models with configured keys will be tested.
|
> 💡 Note: When testing model speed, only models with configured keys will be tested.
|
||||||
|
|
||||||
|
|
@ -238,10 +241,10 @@ This project provides the following testing tools to help you verify the system
|
||||||
| Intelligent Dialogue | Supports multiple LLM(large language models), implements intelligent dialogue |
|
| Intelligent Dialogue | Supports multiple LLM(large language models), implements intelligent dialogue |
|
||||||
| Visual Perception | Supports multiple VLLM(vision large models), implements multimodal interaction |
|
| Visual Perception | Supports multiple VLLM(vision large models), implements multimodal interaction |
|
||||||
| Intent Recognition | Supports LLM intent recognition, Function Call function calling, provides plugin-based intent processing mechanism |
|
| Intent Recognition | Supports LLM intent recognition, Function Call function calling, provides plugin-based intent processing mechanism |
|
||||||
| Memory System | Supports local short-term memory, mem0ai interface memory, with memory summarization functionality |
|
| Memory System | Supports local short-term memory, mem0ai interface memory, PowerMem intelligent memory, with memory summarization functionality |
|
||||||
| Knowledge Base | Supports RAGFlow knowledge base, enabling LLM to judge whether to schedule the knowledge base after receiving the user's question, and then answer the question |
|
| Knowledge Base | Supports RAGFlow knowledge base, enabling LLM to judge whether to schedule the knowledge base after receiving the user's question, and then answer the question |
|
||||||
| Command Delivery | Supports MCP command delivery to ESP32 devices via MQTT protocol from Smart Console |
|
|
||||||
| Tool Calling | Supports client IOT protocol, client MCP protocol, server MCP protocol, MCP endpoint protocol, custom tool functions |
|
| Tool Calling | Supports client IOT protocol, client MCP protocol, server MCP protocol, MCP endpoint protocol, custom tool functions |
|
||||||
|
| Command Delivery | Supports MCP command delivery to ESP32 devices via MQTT protocol from Smart Console |
|
||||||
| Management Backend | Provides Web management interface, supports user management, system configuration and device management; Supports Simplified Chinese, Traditional Chinese and English display |
|
| Management Backend | Provides Web management interface, supports user management, system configuration and device management; Supports Simplified Chinese, Traditional Chinese and English display |
|
||||||
| Testing Tools | Provides performance testing tools, vision model testing tools, and audio interaction testing tools |
|
| Testing Tools | Provides performance testing tools, vision model testing tools, and audio interaction testing tools |
|
||||||
| Deployment Support | Supports Docker deployment and local deployment, provides complete configuration file management |
|
| Deployment Support | Supports Docker deployment and local deployment, provides complete configuration file management |
|
||||||
|
|
@ -249,20 +252,14 @@ This project provides the following testing tools to help you verify the system
|
||||||
|
|
||||||
### Under Development 🚧
|
### Under Development 🚧
|
||||||
|
|
||||||
To learn about specific development plan progress, [click here](https://github.com/users/xinnan-tech/projects/3)
|
To learn about specific development plan progress, [click here](https://github.com/users/xinnan-tech/projects/3). For frequently asked questions and related tutorials, please refer to [this link](./docs/FAQ.md)
|
||||||
|
|
||||||
If you are a software developer, here is an [Open Letter to Developers](docs/contributor_open_letter.md). Welcome to join!
|
If you are a software developer, here is an [Open Letter to Developers](docs/contributor_open_letter.md). Welcome to join!
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Product Ecosystem 👬
|
## Product Ecosystem 👬
|
||||||
Xiaozhi is an ecosystem. When using this product, you can also check out other [excellent projects](https://github.com/78/xiaozhi-esp32?tab=readme-ov-file#related-open-source-projects) in this ecosystem
|
Xiaozhi is an ecosystem. When using this product, you can also check out other [excellent projects](https://github.com/78/xiaozhi-esp32/blob/main/README_zh.md#%E7%9B%B8%E5%85%B3%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE) in this ecosystem
|
||||||
|
|
||||||
| Project Name | Project Address | Project Description |
|
|
||||||
|:---------------------|:--------|:--------|
|
|
||||||
| Xiaozhi Android Client | [xiaozhi-android-client](https://github.com/TOM88812/xiaozhi-android-client) | An Android and iOS voice dialogue application based on xiaozhi-server, supporting real-time voice interaction and text dialogue.<br/>Currently a Flutter version, connecting iOS and Android platforms. |
|
|
||||||
| Xiaozhi Desktop Client | [py-xiaozhi](https://github.com/Huang-junsen/py-xiaozhi) | This project provides a Python-based AI client for beginners, allowing users to experience Xiaozhi AI functionality through code even without physical hardware conditions. |
|
|
||||||
| Xiaozhi Java Server | [xiaozhi-esp32-server-java](https://github.com/joey-zhou/xiaozhi-esp32-server-java) | Xiaozhi open-source backend service Java version is a Java-based open-source project.<br/>It includes frontend and backend services, aiming to provide users with a complete backend service solution. |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -276,8 +273,10 @@ Xiaozhi is an ecosystem. When using this product, you can also check out other [
|
||||||
| Dify interface calls | Dify | - |
|
| Dify interface calls | Dify | - |
|
||||||
| FastGPT interface calls | FastGPT | - |
|
| FastGPT interface calls | FastGPT | - |
|
||||||
| Coze interface calls | Coze | - |
|
| Coze interface calls | Coze | - |
|
||||||
|
| Xinference interface calls | Xinference | - |
|
||||||
|
| HomeAssistant interface calls | HomeAssistant | - |
|
||||||
|
|
||||||
In fact, any LLM that supports OpenAI interface calls can be integrated and used, including Xinference and HomeAssistant interfaces.
|
In fact, any LLM that supports OpenAI interface calls can be integrated and used.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -296,7 +295,7 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
|
||||||
| Usage Method | Supported Platforms | Free Platforms |
|
| Usage Method | Supported Platforms | Free Platforms |
|
||||||
|:---:|:---:|:---:|
|
|:---:|:---:|:---:|
|
||||||
| Interface calls | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud and Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow(partial) |
|
| Interface calls | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud and Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow(partial) |
|
||||||
| Local services | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, MinimaxTTS | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, MinimaxTTS |
|
| Local services | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -330,7 +329,9 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
|
||||||
| Type | Platform Name | Usage Method | Pricing Model | Notes |
|
| Type | Platform Name | Usage Method | Pricing Model | Notes |
|
||||||
|:------:|:---------------:|:----:|:---------:|:--:|
|
|:------:|:---------------:|:----:|:---------:|:--:|
|
||||||
| Memory | mem0ai | Interface calls | 1000 times/month quota | |
|
| Memory | mem0ai | Interface calls | 1000 times/month quota | |
|
||||||
|
| Memory | [powermem](./docs/powermem-integration.md) | Local summarization | Depends on LLM and DB | OceanBase open source, supports intelligent retrieval |
|
||||||
| Memory | mem_local_short | Local summarization | Free | |
|
| Memory | mem_local_short | Local summarization | Free | |
|
||||||
|
| Memory | nomem | No memory mode | Free | |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -340,6 +341,7 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use
|
||||||
|:------:|:-------------:|:----:|:-------:|:---------------------:|
|
|:------:|:-------------:|:----:|:-------:|:---------------------:|
|
||||||
| Intent | intent_llm | Interface calls | Based on LLM pricing | Recognizes intent through large models, strong generalization |
|
| Intent | intent_llm | Interface calls | Based on LLM pricing | Recognizes intent through large models, strong generalization |
|
||||||
| Intent | function_call | Interface calls | Based on LLM pricing | Completes intent through large model function calling, fast speed, good effect |
|
| Intent | function_call | Interface calls | Based on LLM pricing | Completes intent through large model function calling, fast speed, good effect |
|
||||||
|
| Intent | nointent | No intent mode | Free | Does not perform intent recognition, directly returns dialogue result |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
376
README_pt_BR.md
Normal file
376
README_pt_BR.md
Normal file
|
|
@ -0,0 +1,376 @@
|
||||||
|
[](https://github.com/xinnan-tech/xiaozhi-esp32-server)
|
||||||
|
|
||||||
|
<h1 align="center">Serviço Backend Xiaozhi xiaozhi-esp32-server</h1>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
Este projeto é baseado na teoria e tecnologia de inteligência simbiótica humano-máquina para desenvolver sistemas inteligentes de hardware e software para terminais<br/>fornecendo serviços de backend para o projeto de hardware inteligente de código aberto
|
||||||
|
<a href="https://github.com/78/xiaozhi-esp32">xiaozhi-esp32</a><br/>
|
||||||
|
Implementado usando Python, Java e Vue de acordo com o <a href="https://ccnphfhqs21z.feishu.cn/wiki/M0XiwldO9iJwHikpXD5cEx71nKh">Protocolo de Comunicação Xiaozhi</a><br/>
|
||||||
|
Suporte ao protocolo MQTT+UDP, protocolo WebSocket, ponto de acesso MCP, reconhecimento de impressão vocal e base de conhecimento
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="./docs/FAQ.md">Perguntas Frequentes</a>
|
||||||
|
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/issues">Reportar Problemas</a>
|
||||||
|
· <a href="./README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3">Documentação de Implantação</a>
|
||||||
|
· <a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">Notas de Lançamento</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="./README.md"><img alt="简体中文版自述文件" src="https://img.shields.io/badge/简体中文-DFE0E5"></a>
|
||||||
|
<a href="./README_en.md"><img alt="README in English" src="https://img.shields.io/badge/English-DFE0E5"></a>
|
||||||
|
<a href="./README_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DFE0E5"></a>
|
||||||
|
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||||
|
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DBEDFA"></a>
|
||||||
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
||||||
|
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/LICENSE">
|
||||||
|
<img alt="GitHub pull requests" src="https://img.shields.io/badge/license-MIT-white?labelColor=black" />
|
||||||
|
</a>
|
||||||
|
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server">
|
||||||
|
<img alt="stars" src="https://img.shields.io/github/stars/xinnan-tech/xiaozhi-esp32-server?color=ffcb47&labelColor=black" />
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
Liderado pela Equipe do Professor Siyuan Liu (Universidade de Tecnologia do Sul da China)
|
||||||
|
</br>
|
||||||
|
刘思源教授团队主导研发(华南理工大学)
|
||||||
|
</br>
|
||||||
|
<img src="./docs/images/hnlg.jpg" alt="Universidade de Tecnologia do Sul da China (华南理工大学)" width="50%">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Público-Alvo 👥
|
||||||
|
|
||||||
|
Este projeto requer dispositivos de hardware ESP32 para funcionar. Se você adquiriu hardware relacionado ao ESP32, conectou-se com sucesso ao serviço backend implantado pelo Brother Xia e deseja construir seu próprio serviço backend `xiaozhi-esp32` de forma independente, então este projeto é perfeito para você.
|
||||||
|
|
||||||
|
Quer ver os efeitos de uso? Clique nos vídeos abaixo 🎥
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1FMFyejExX" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Experiência de velocidade de resposta" src="docs/images/demo9.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1vchQzaEse" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Segredo da otimização de velocidade" src="docs/images/demo6.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1C1tCzUEZh" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Cenário médico complexo" src="docs/images/demo1.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1zUW5zJEkq" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Envio de comandos MQTT" src="docs/images/demo4.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1Exu3zqEDe" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Reconhecimento de impressão vocal" src="docs/images/demo14.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1pNXWYGEx1" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Controle de interruptores de eletrodomésticos" src="docs/images/demo5.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1ZQKUzYExM" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Ponto de acesso MCP" src="docs/images/demo13.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1TJ7WzzEo6" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Tarefas com múltiplos comandos" src="docs/images/demo11.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1VC96Y5EMH" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Reproduzir música" src="docs/images/demo7.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1Z8XuYZEAS" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Plugin de clima" src="docs/images/demo8.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV12J7WzBEaH" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Interrupção em tempo real" src="docs/images/demo10.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1Co76z7EvK" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Fotografar e identificar objetos" src="docs/images/demo12.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV1CDKWemEU6" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Timbre de voz personalizado" src="docs/images/demo2.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV12yA2egEaC" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Comunicação em cantonês" src="docs/images/demo3.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href="https://www.bilibili.com/video/BV17LXWYvENb" target="_blank">
|
||||||
|
<picture>
|
||||||
|
<img alt="Transmissão de notícias" src="docs/images/demo0.png" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Avisos ⚠️
|
||||||
|
|
||||||
|
1. Este projeto é um software de código aberto. Este software não possui parceria comercial com nenhum provedor de serviços de API de terceiros (incluindo, mas não se limitando a reconhecimento de fala, modelos de linguagem, síntese de voz e outras plataformas) com os quais se conecta, e não fornece nenhuma forma de garantia quanto à qualidade de serviço ou segurança financeira desses provedores. Recomenda-se que os usuários priorizem provedores de serviço com licenças comerciais relevantes e leiam cuidadosamente seus termos de serviço e políticas de privacidade. Este software não armazena nenhuma chave de conta, não participa de fluxos de fundos e não assume o risco de perda de fundos recarregados.
|
||||||
|
|
||||||
|
2. A funcionalidade deste projeto não está completa e não passou por avaliação de segurança de rede. Por favor, não o utilize em ambientes de produção. Se você implantar este projeto para fins de aprendizado em um ambiente de rede pública, certifique-se de que as medidas de proteção necessárias estejam em vigor.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Documentação de Implantação
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Este projeto oferece dois métodos de implantação. Por favor, escolha de acordo com suas necessidades específicas:
|
||||||
|
|
||||||
|
#### 🚀 Seleção do Método de Implantação
|
||||||
|
| Método de Implantação | Funcionalidades | Cenários Aplicáveis | Documentação de Implantação | Requisitos de Configuração | Tutoriais em Vídeo |
|
||||||
|
|---------|------|---------|---------|---------|---------|
|
||||||
|
| **Instalação Simplificada** | Diálogo inteligente, gerenciamento de agente único | Ambientes de baixa configuração, dados armazenados em arquivos de configuração, sem necessidade de banco de dados | [①Versão Docker](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Implantação via Código-Fonte](./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 núcleos 4GB se usar `FunASR`, 2 núcleos 2GB se todas APIs | - |
|
||||||
|
| **Instalação de Módulo Completo** | Diálogo inteligente, gerenciamento multiusuário, gerenciamento de múltiplos agentes, operação de interface do console inteligente | Experiência com funcionalidade completa, dados armazenados em banco de dados |[①Versão Docker](./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) / [②Implantação via Código-Fonte](./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) / [③Tutorial de Atualização Automática via Código-Fonte](./docs/dev-ops-integration.md) | 4 núcleos 8GB se usar `FunASR`, 2 núcleos 4GB se todas APIs| [Tutorial em Vídeo de Inicialização via Código-Fonte Local](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
|
||||||
|
|
||||||
|
Perguntas frequentes e tutoriais relacionados podem ser consultados [neste link](./docs/FAQ.md)
|
||||||
|
|
||||||
|
> 💡 Nota: Abaixo está uma plataforma de teste implantada com o código mais recente. Você pode gravar e testar se necessário. Usuários simultâneos: 6, os dados serão limpos diariamente.
|
||||||
|
|
||||||
|
```
|
||||||
|
Endereço do Console de Controle Inteligente: https://2662r3426b.vicp.fun
|
||||||
|
Endereço do Console de Controle Inteligente (H5): https://2662r3426b.vicp.fun/h5/index.html
|
||||||
|
|
||||||
|
Ferramenta de Teste de Serviço: https://2662r3426b.vicp.fun/test/
|
||||||
|
Endereço da Interface OTA: https://2662r3426b.vicp.fun/xiaozhi/ota/
|
||||||
|
Endereço da Interface WebSocket: wss://2662r3426b.vicp.fun/xiaozhi/v1/
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 🚩 Descrição e Recomendações de Configuração
|
||||||
|
> [!Note]
|
||||||
|
> Este projeto oferece dois esquemas de configuração:
|
||||||
|
>
|
||||||
|
> 1. `Configurações Gratuitas Nível Básico`: Adequado para uso pessoal e doméstico, todos os componentes utilizam soluções gratuitas, sem necessidade de pagamento adicional.
|
||||||
|
>
|
||||||
|
> 2. `Configuração de Streaming`: Adequado para demonstrações, treinamentos, cenários com mais de 2 usuários simultâneos, etc. Utiliza tecnologia de processamento em streaming para velocidade de resposta mais rápida e melhor experiência.
|
||||||
|
>
|
||||||
|
> A partir da versão `0.5.2`, o projeto suporta configuração de streaming. Em comparação com versões anteriores, a velocidade de resposta é melhorada em aproximadamente `2,5 segundos`, melhorando significativamente a experiência do usuário.
|
||||||
|
|
||||||
|
| Nome do Módulo | Configurações Gratuitas Nível Básico | Configuração de Streaming |
|
||||||
|
|:---:|:---:|:---:|
|
||||||
|
| ASR(Reconhecimento de Fala) | FunASR(Local) | 👍XunfeiStreamASR(Xunfei Streaming) |
|
||||||
|
| LLM(Modelo de Linguagem) | glm-4-flash(Zhipu) | 👍qwen-flash(Alibaba Bailian) |
|
||||||
|
| VLLM(Modelo de Visão) | glm-4v-flash(Zhipu) | 👍qwen2.5-vl-3b-instructh(Alibaba Bailian) |
|
||||||
|
| TTS(Síntese de Voz) | ✅LinkeraiTTS(Lingxi streaming) | 👍HuoshanDoubleStreamTTS(Volcano Streaming) |
|
||||||
|
| Intent(Reconhecimento de Intenção) | function_call(Chamada de função) | function_call(Chamada de função) |
|
||||||
|
| Memory(Função de Memória) | mem_local_short(Memória local de curto prazo) | mem_local_short(Memória local de curto prazo) |
|
||||||
|
|
||||||
|
Se você está preocupado com o tempo de resposta de cada componente, consulte o [Relatório de Teste de Desempenho dos Componentes Xiaozhi](https://github.com/xinnan-tech/xiaozhi-performance-research), e teste em seu próprio ambiente seguindo os métodos de teste do relatório.
|
||||||
|
|
||||||
|
#### 🔧 Ferramentas de Teste
|
||||||
|
Este projeto fornece as seguintes ferramentas de teste para ajudá-lo a verificar o sistema e escolher modelos adequados:
|
||||||
|
|
||||||
|
| Nome da Ferramenta | Localização | Método de Uso | Descrição da Função |
|
||||||
|
|:---:|:---|:---:|:---:|
|
||||||
|
| Ferramenta de Teste de Interação por Áudio | main》xiaozhi-server》test》test_page.html | Abrir diretamente com Google Chrome | Testa as funções de reprodução e recepção de áudio, verifica se o processamento de áudio no lado Python está normal |
|
||||||
|
| Ferramenta de Teste de Resposta de Modelo | main》xiaozhi-server》performance_tester.py | Execute `python performance_tester.py` | Testa a velocidade de resposta dos três módulos principais: ASR(reconhecimento de fala), LLM(modelo de linguagem), VLLM(modelo de visão), TTS(síntese de voz) |
|
||||||
|
|
||||||
|
> 💡 Nota: Ao testar a velocidade dos modelos, apenas os modelos com chaves configuradas serão testados.
|
||||||
|
|
||||||
|
---
|
||||||
|
## Lista de Funcionalidades ✨
|
||||||
|
### Implementado ✅
|
||||||
|

|
||||||
|
| Módulo de Funcionalidade | Descrição |
|
||||||
|
|:---:|:---|
|
||||||
|
| Arquitetura Principal | Baseado em [gateway MQTT+UDP](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), servidores WebSocket e HTTP, fornece sistema completo de gerenciamento de console e autenticação |
|
||||||
|
| Interação por Voz | Suporta ASR em streaming (reconhecimento de fala), TTS em streaming (síntese de voz), VAD (detecção de atividade vocal), suporta reconhecimento multilíngue e processamento de voz |
|
||||||
|
| Reconhecimento de Impressão Vocal | Suporta registro, gerenciamento e reconhecimento de impressão vocal de múltiplos usuários, processa em paralelo com o ASR, reconhecimento de identidade do falante em tempo real e repassa ao LLM para respostas personalizadas |
|
||||||
|
| Diálogo Inteligente | Suporta múltiplos LLM (modelos de linguagem de grande porte), implementa diálogo inteligente |
|
||||||
|
| Percepção Visual | Suporta múltiplos VLLM (modelos de visão de grande porte), implementa interação multimodal |
|
||||||
|
| Reconhecimento de Intenção | Suporta reconhecimento de intenção por LLM, Function Call (chamada de função), fornece mecanismo de processamento de intenção baseado em plugins |
|
||||||
|
| Sistema de Memória | Suporta memória local de curto prazo, memória via interface mem0ai, memória inteligente PowerMem, com funcionalidade de resumo de memória |
|
||||||
|
| Base de Conhecimento | Suporta base de conhecimento RAGFlow, permitindo que o LLM julgue se deve acionar a base de conhecimento após receber a pergunta do usuário, e então responda à pergunta |
|
||||||
|
| Chamada de Ferramentas | Suporta protocolo IOT do cliente, protocolo MCP do cliente, protocolo MCP do servidor, protocolo de endpoint MCP, funções de ferramentas personalizadas |
|
||||||
|
| Envio de Comandos | Suporta envio de comandos MCP para dispositivos ESP32 via protocolo MQTT a partir do Console Inteligente |
|
||||||
|
| Backend de Gerenciamento | Fornece interface de gerenciamento Web, suporta gerenciamento de usuários, configuração do sistema e gerenciamento de dispositivos; Suporta exibição em Chinês Simplificado, Chinês Tradicional e Inglês |
|
||||||
|
| Ferramentas de Teste | Fornece ferramentas de teste de desempenho, ferramentas de teste de modelo de visão e ferramentas de teste de interação por áudio |
|
||||||
|
| Suporte à Implantação | Suporta implantação via Docker e implantação local, fornece gerenciamento completo de arquivos de configuração |
|
||||||
|
| Sistema de Plugins | Suporta extensões de plugins funcionais, desenvolvimento de plugins personalizados e carregamento dinâmico de plugins |
|
||||||
|
|
||||||
|
### Em Desenvolvimento 🚧
|
||||||
|
|
||||||
|
Para conhecer o progresso específico do plano de desenvolvimento, [clique aqui](https://github.com/users/xinnan-tech/projects/3). Perguntas frequentes e tutoriais relacionados podem ser consultados [neste link](./docs/FAQ.md)
|
||||||
|
|
||||||
|
Se você é um desenvolvedor de software, aqui está uma [Carta Aberta aos Desenvolvedores](docs/contributor_open_letter.md). Seja bem-vindo a participar!
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ecossistema do Produto 👬
|
||||||
|
Xiaozhi é um ecossistema. Ao utilizar este produto, você também pode conferir outros [projetos excelentes](https://github.com/78/xiaozhi-esp32/blob/main/README_zh.md#%E7%9B%B8%E5%85%B3%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE) neste ecossistema
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Lista de Plataformas/Componentes Suportados 📋
|
||||||
|
### LLM Modelos de Linguagem
|
||||||
|
|
||||||
|
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||||
|
|:---:|:---:|:---:|
|
||||||
|
| Chamadas via interface OpenAI | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFLYTEK | Zhipu, Gemini |
|
||||||
|
| Chamadas via interface Ollama | Ollama | - |
|
||||||
|
| Chamadas via interface Dify | Dify | - |
|
||||||
|
| Chamadas via interface FastGPT | FastGPT | - |
|
||||||
|
| Chamadas via interface Coze | Coze | - |
|
||||||
|
| Chamadas via interface Xinference | Xinference | - |
|
||||||
|
| Chamadas via interface HomeAssistant | HomeAssistant | - |
|
||||||
|
|
||||||
|
Na verdade, qualquer LLM que suporte chamadas via interface openai pode ser integrado e utilizado.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### VLLM Modelos de Visão
|
||||||
|
|
||||||
|
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||||
|
|:---:|:---:|:---:|
|
||||||
|
| Chamadas via interface OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
|
||||||
|
|
||||||
|
Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser integrado e utilizado.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### TTS Síntese de Voz
|
||||||
|
|
||||||
|
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||||
|
|:---:|:---:|:---:|
|
||||||
|
| Chamadas via interface | EdgeTTS, iFLYTEK, Volcano Engine, Tencent Cloud, Alibaba Cloud e Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow(parcial) |
|
||||||
|
| Serviços locais | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### VAD Detecção de Atividade Vocal
|
||||||
|
|
||||||
|
| Tipo | Nome da Plataforma | Método de Uso | Modelo de Preço | Observações |
|
||||||
|
|:---:|:---------:|:----:|:----:|:--:|
|
||||||
|
| VAD | SileroVAD | Uso local | Gratuito | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### ASR Reconhecimento de Fala
|
||||||
|
|
||||||
|
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||||
|
|:---:|:---:|:---:|
|
||||||
|
| Uso local | FunASR, SherpaASR | FunASR, SherpaASR |
|
||||||
|
| Chamadas via interface | FunASRServer, Volcano Engine, iFLYTEK, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Reconhecimento de Impressão Vocal
|
||||||
|
|
||||||
|
| Método de Uso | Plataformas Suportadas | Plataformas Gratuitas |
|
||||||
|
|:---:|:---:|:---:|
|
||||||
|
| Uso local | 3D-Speaker | 3D-Speaker |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Armazenamento de Memória
|
||||||
|
|
||||||
|
| Tipo | Nome da Plataforma | Método de Uso | Modelo de Preço | Observações |
|
||||||
|
|:------:|:---------------:|:----:|:---------:|:--:|
|
||||||
|
| Memória | mem0ai | Chamadas via interface | Cota de 1000 vezes/mês | |
|
||||||
|
| Memória | [powermem](./docs/powermem-integration.md) | Resumo local | Depende do LLM e BD | OceanBase de código aberto, suporta busca inteligente |
|
||||||
|
| Memória | mem_local_short | Resumo local | Gratuito | |
|
||||||
|
| Memória | nomem | Modo sem memória | Gratuito | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Reconhecimento de Intenção
|
||||||
|
|
||||||
|
| Tipo | Nome da Plataforma | Método de Uso | Modelo de Preço | Observações |
|
||||||
|
|:------:|:-------------:|:----:|:-------:|:---------------------:|
|
||||||
|
| Intenção | intent_llm | Chamadas via interface | Baseado no preço do LLM | Reconhece intenção através de modelos de linguagem, forte generalização |
|
||||||
|
| Intenção | function_call | Chamadas via interface | Baseado no preço do LLM | Completa a intenção através de chamada de função do modelo de linguagem, velocidade rápida, bom resultado |
|
||||||
|
| Intenção | nointent | Modo sem intenção | Gratuito | Não realiza reconhecimento de intenção, retorna diretamente o resultado do diálogo |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### RAG Geração Aumentada por Recuperação
|
||||||
|
|
||||||
|
| Tipo | Nome da Plataforma | Método de Uso | Modelo de Preço | Observações |
|
||||||
|
|:------:|:-------------:|:----:|:-------:|:---------------------:|
|
||||||
|
| RAG | ragflow | Chamadas via interface | Cobrado com base nos tokens consumidos para fatiamento e segmentação de palavras | Utiliza o recurso de geração aumentada por recuperação do RagFlow para fornecer respostas de diálogo mais precisas |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Agradecimentos 🙏
|
||||||
|
|
||||||
|
| Logo | Projeto/Empresa | Descrição |
|
||||||
|
|:---:|:---:|:---|
|
||||||
|
| <img src="./docs/images/logo_bailing.png" width="160"> | [Robô de Diálogo por Voz Bailing](https://github.com/wwbin2017/bailing) | Este projeto foi inspirado pelo [Robô de Diálogo por Voz Bailing](https://github.com/wwbin2017/bailing) e implementado com base nele |
|
||||||
|
| <img src="./docs/images/logo_tenclass.png" width="160"> | [Tenclass](https://www.tenclass.com/) | Agradecimentos à [Tenclass](https://www.tenclass.com/) por formular protocolos de comunicação padrão, soluções de compatibilidade multidispositivo e demonstrações práticas de cenários de alta concorrência para o ecossistema Xiaozhi; fornecendo suporte completo de documentação técnica para este projeto |
|
||||||
|
| <img src="./docs/images/logo_xuanfeng.png" width="160"> | [Xuanfeng Technology (玄凤科技)](https://github.com/Eric0308) | Agradecimentos à [Xuanfeng Technology](https://github.com/Eric0308) por contribuir com o framework de chamada de função, protocolo de comunicação MCP e implementação do mecanismo de chamada baseado em plugins. Através de um sistema padronizado de agendamento de instruções e capacidades de expansão dinâmica, melhora significativamente a eficiência de interação e extensibilidade funcional dos dispositivos de frontend (IoT) |
|
||||||
|
| <img src="./docs/images/logo_junsen.png" width="160"> | [huangjunsen](https://github.com/huangjunsen0406) | Agradecimentos a [huangjunsen](https://github.com/huangjunsen0406) por contribuir com o módulo `Console de Controle Inteligente Mobile`, que permite controle eficiente e interação em tempo real em dispositivos móveis, melhorando significativamente a conveniência operacional e a eficiência de gerenciamento do sistema em cenários móveis. |
|
||||||
|
| <img src="./docs/images/logo_huiyuan.png" width="160"> | [Huiyuan Design (汇远设计)](http://ui.kwd988.net/) | Agradecimentos à [Huiyuan Design](http://ui.kwd988.net/) por fornecer soluções visuais profissionais para este projeto, utilizando sua experiência prática de design atendendo mais de mil empresas para potencializar a experiência do usuário deste produto |
|
||||||
|
| <img src="./docs/images/logo_qinren.png" width="160"> | [Xi'an Qinren Information Technology (西安勤人信息科技)](https://www.029app.com/) | Agradecimentos à [Xi'an Qinren Information Technology](https://www.029app.com/) por aprofundar o sistema visual deste projeto, garantindo consistência e extensibilidade do estilo de design geral em aplicações de múltiplos cenários |
|
||||||
|
| <img src="./docs/images/logo_contributors.png" width="160"> | [Contribuidores de Código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Agradecimentos a [todos os contribuidores de código](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), seus esforços tornaram o projeto mais robusto e poderoso. |
|
||||||
|
|
||||||
|
|
||||||
|
<a href="https://star-history.com/#xinnan-tech/xiaozhi-esp32-server&Date">
|
||||||
|
|
||||||
|
<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>
|
||||||
|
|
@ -21,6 +21,7 @@ Hỗ trợ giao thức MQTT+UDP, giao thức Websocket, điểm truy cập MCP,
|
||||||
<a href="./README_en.md"><img alt="README in English" src="https://img.shields.io/badge/English-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_vi.md"><img alt="Tiếng Việt" src="https://img.shields.io/badge/Tiếng Việt-DBEDFA"></a>
|
||||||
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
<a href="./README_de.md"><img alt="Deutsch" src="https://img.shields.io/badge/Deutsch-DFE0E5"></a>
|
||||||
|
<a href="./README_pt_BR.md"><img alt="Português (Brasil)" src="https://img.shields.io/badge/Português (Brasil)-DFE0E5"></a>
|
||||||
<a href="https://github.com/xinnan-tech/xiaozhi-esp32-server/releases">
|
<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" />
|
<img alt="GitHub Contributors" src="https://img.shields.io/github/v/release/xinnan-tech/xiaozhi-esp32-server?logo=docker" />
|
||||||
</a>
|
</a>
|
||||||
|
|
@ -241,7 +242,7 @@ Dự án này cung cấp các công cụ kiểm tra sau để giúp bạn xác m
|
||||||
| Đố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 |
|
| Đố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 |
|
| 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 |
|
| 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ớ |
|
| Hệ thống bộ nhớ | Hỗ trợ bộ nhớ ngắn hạn cục bộ, bộ nhớ giao diện mem0ai, bộ nhớ thông minh PowerMem, 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 |
|
| 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 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 |
|
| 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 |
|
||||||
|
|
@ -259,7 +260,7 @@ Nếu bạn là một nhà phát triển phần mềm, đây có một [Lá thư
|
||||||
---
|
---
|
||||||
|
|
||||||
## Hệ sinh thái sản phẩm 👬
|
## 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
|
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/blob/main/README_zh.md#%E7%9B%B8%E5%85%B3%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE) khác trong hệ sinh thái này
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -329,6 +330,7 @@ Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đ
|
||||||
| Loại | Tên nền tảng | Phương pháp sử dụng | Mô hình thu phí | Ghi chú |
|
| 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 | mem0ai | Gọi giao diện | Hạn mức 1000 lần/tháng | |
|
||||||
|
| Memory | [powermem](./docs/powermem-integration.md) | Tóm tắt cục bộ | Phụ thuộc vào LLM và DB | OceanBase mã nguồn mở, hỗ trợ tìm kiếm thông minh |
|
||||||
| Memory | mem_local_short | Tóm tắt cục bộ | Miễn phí | |
|
| Memory | mem_local_short | Tóm tắt cục bộ | Miễn phí | |
|
||||||
| Memory | nomem | Chế độ không có bộ nhớ | Miễn phí | |
|
| Memory | nomem | Chế độ không có bộ nhớ | Miễn phí | |
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -82,6 +82,7 @@ VAD:
|
||||||
8、[新闻插件源配置指南](./newsnow_plugin_config.md)<br/>
|
8、[新闻插件源配置指南](./newsnow_plugin_config.md)<br/>
|
||||||
9、[知识库ragflow集成指南](./ragflow-integration.md)<br/>
|
9、[知识库ragflow集成指南](./ragflow-integration.md)<br/>
|
||||||
10、[如何部署上下文源](./context-provider-integration.md)<br/>
|
10、[如何部署上下文源](./context-provider-integration.md)<br/>
|
||||||
|
11、[如何集成PowerMem智能记忆](./powermem-integration.md)<br/>
|
||||||
|
|
||||||
### 11、语音克隆、本地语音部署相关教程
|
### 11、语音克隆、本地语音部署相关教程
|
||||||
1、[如何在智控台克隆音色](./huoshan-streamTTS-voice-cloning.md)<br/>
|
1、[如何在智控台克隆音色](./huoshan-streamTTS-voice-cloning.md)<br/>
|
||||||
|
|
|
||||||
345
docs/powermem-integration.md
Normal file
345
docs/powermem-integration.md
Normal file
|
|
@ -0,0 +1,345 @@
|
||||||
|
# PowerMem 记忆组件集成指南
|
||||||
|
|
||||||
|
## 简介
|
||||||
|
|
||||||
|
[PowerMem](https://www.powermem.ai/) 是由 OceanBase 开源的 Agent 记忆组件,通过本地 LLM 进行记忆总结和智能检索,为 AI 代理提供高效的记忆管理功能。
|
||||||
|
|
||||||
|
费用说明:PowerMem 本身开源免费,实际费用取决于您选择的 LLM 和数据库:
|
||||||
|
- 使用 SQLite + 免费 LLM(如智谱 glm-4-flash)= **完全免费**
|
||||||
|
- 使用云端 LLM 或云端数据库 = 按对应服务收费
|
||||||
|
|
||||||
|
> 💡 **最佳性能提示**:PowerMem 配合 OceanBase 使用可实现最大性能释放,SQLite 仅建议在资源不足的情况下使用。
|
||||||
|
|
||||||
|
- **GitHub**: https://github.com/oceanbase/powermem
|
||||||
|
- **官网**: https://www.powermem.ai/
|
||||||
|
- **使用示例**: https://github.com/oceanbase/powermem/tree/main/examples
|
||||||
|
|
||||||
|
## 功能特性
|
||||||
|
|
||||||
|
- **本地总结**:通过 LLM 在本地进行记忆总结和提取
|
||||||
|
- **用户画像**:通过 `UserMemory` 自动提取用户信息(姓名、职业、兴趣等),持续更新用户画像
|
||||||
|
- **智能遗忘**:基于艾宾浩斯遗忘曲线,自动"遗忘"过时噪声信息
|
||||||
|
- **多种存储后端**:支持 OceanBase(推荐,最佳性能)、SeekDB(推荐,AI应用存储一体)、PostgreSQL、SQLite(轻量备选)
|
||||||
|
- **多种 LLM 支持**:通义千问、智谱(glm-4-flash 免费)、OpenAI 等
|
||||||
|
- **智能检索**:基于向量搜索的语义检索能力
|
||||||
|
- **私有部署**:完全支持本地私有化部署
|
||||||
|
- **异步操作**:高效的异步记忆管理
|
||||||
|
|
||||||
|
## 安装
|
||||||
|
|
||||||
|
PowerMem 已添加到项目依赖中,如果需要手动安装:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install powermem
|
||||||
|
```
|
||||||
|
|
||||||
|
## 配置说明
|
||||||
|
|
||||||
|
### 基础配置
|
||||||
|
|
||||||
|
在 `config.yaml` 中配置 PowerMem:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
selected_module:
|
||||||
|
Memory: powermem
|
||||||
|
|
||||||
|
Memory:
|
||||||
|
powermem:
|
||||||
|
type: powermem
|
||||||
|
# 是否启用用户画像功能
|
||||||
|
# 用户画像支持: oceanbase、seekdb、sqlite (powermem 0.3.0+)
|
||||||
|
enable_user_profile: true
|
||||||
|
|
||||||
|
# ========== LLM 配置 ==========
|
||||||
|
llm:
|
||||||
|
provider: openai # 可选: qwen, openai, zhipu 等
|
||||||
|
config:
|
||||||
|
api_key: 你的LLM API密钥
|
||||||
|
model: qwen-plus
|
||||||
|
# openai_base_url: https://api.openai.com/v1 # 可选,自定义服务地址
|
||||||
|
|
||||||
|
# ========== Embedding 配置 ==========
|
||||||
|
embedder:
|
||||||
|
provider: openai # 可选: qwen, openai 等
|
||||||
|
config:
|
||||||
|
api_key: 你的嵌入模型API密钥
|
||||||
|
model: text-embedding-v4
|
||||||
|
openai_base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
|
||||||
|
# embedding_dims: 1024 # 向量维度,非1536时需配置
|
||||||
|
|
||||||
|
# ========== Database 配置 ==========
|
||||||
|
vector_store:
|
||||||
|
provider: sqlite # 可选: oceanbase(推荐), seekdb(推荐), postgres, sqlite(轻量)
|
||||||
|
config: {} # SQLite 无需额外配置
|
||||||
|
```
|
||||||
|
|
||||||
|
### 配置参数详解
|
||||||
|
|
||||||
|
#### LLM 配置
|
||||||
|
|
||||||
|
| 参数 | 说明 | 可选值 |
|
||||||
|
|------|------|--------|
|
||||||
|
| `llm.provider` | LLM 提供商 | `qwen`, `openai`, `zhipu` 等 |
|
||||||
|
| `llm.config.api_key` | API 密钥 | - |
|
||||||
|
| `llm.config.model` | 模型名称 | 根据提供商选择 |
|
||||||
|
| `llm.config.openai_base_url` | 自定义服务地址(可选) | - |
|
||||||
|
|
||||||
|
#### Embedding 配置
|
||||||
|
|
||||||
|
| 参数 | 说明 | 可选值 |
|
||||||
|
|------|------|--------|
|
||||||
|
| `embedder.provider` | 嵌入模型提供商 | `qwen`, `openai` 等 |
|
||||||
|
| `embedder.config.api_key` | API 密钥 | - |
|
||||||
|
| `embedder.config.model` | 模型名称 | 根据提供商选择 |
|
||||||
|
| `embedder.config.openai_base_url` | 自定义服务地址(可选) | - |
|
||||||
|
|
||||||
|
#### Database 配置
|
||||||
|
|
||||||
|
| 参数 | 说明 | 可选值 |
|
||||||
|
|------|------|--------|
|
||||||
|
| `vector_store.provider` | 存储后端类型 | `oceanbase`(推荐), `seekdb`(推荐), `postgres`, `sqlite`(轻量) |
|
||||||
|
| `vector_store.config` | 数据库连接配置 | 根据 provider 设置 |
|
||||||
|
|
||||||
|
### 记忆模式说明
|
||||||
|
|
||||||
|
PowerMem 支持两种记忆模式:
|
||||||
|
|
||||||
|
| 模式 | 配置 | 功能 | 存储要求 |
|
||||||
|
|------|------|------|----------|
|
||||||
|
| **普通记忆** | `enable_user_profile: false` | 对话记忆存储与检索 | 支持所有数据库 |
|
||||||
|
| **用户画像** | `enable_user_profile: true` | 记忆 + 自动提取用户画像 | oceanbase、seekdb、sqlite |
|
||||||
|
|
||||||
|
> 📌 **版本说明**:PowerMem 0.3.0+ 版本,用户画像功能支持 OceanBase、SeekDB、SQLite 三种存储后端。
|
||||||
|
|
||||||
|
### 使用通义千问(推荐)
|
||||||
|
|
||||||
|
1. 访问 [阿里云百炼平台](https://bailian.console.aliyun.com/) 注册账号
|
||||||
|
2. 在 [API Key 管理](https://bailian.console.aliyun.com/?apiKey=1#/api-key) 页面获取 API 密钥
|
||||||
|
3. 配置如下:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
Memory:
|
||||||
|
powermem:
|
||||||
|
type: powermem
|
||||||
|
enable_user_profile: true
|
||||||
|
llm:
|
||||||
|
provider: qwen
|
||||||
|
config:
|
||||||
|
api_key: sk-xxxxxxxxxxxxxxxx
|
||||||
|
model: qwen-plus
|
||||||
|
embedder:
|
||||||
|
provider: openai
|
||||||
|
config:
|
||||||
|
api_key: sk-xxxxxxxxxxxxxxxx
|
||||||
|
model: text-embedding-v4
|
||||||
|
openai_base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
|
||||||
|
vector_store:
|
||||||
|
provider: sqlite
|
||||||
|
config: {}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 使用智谱免费 LLM(完全免费方案)
|
||||||
|
|
||||||
|
智谱提供免费的 glm-4-flash 模型,配合 SQLite 可实现完全免费使用:
|
||||||
|
|
||||||
|
1. 访问 [智谱AI开放平台](https://bigmodel.cn/) 注册账号
|
||||||
|
2. 在 [API Keys](https://bigmodel.cn/usercenter/proj-mgmt/apikeys) 页面获取 API 密钥
|
||||||
|
3. 配置如下:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
Memory:
|
||||||
|
powermem:
|
||||||
|
type: powermem
|
||||||
|
enable_user_profile: true
|
||||||
|
llm:
|
||||||
|
provider: openai # 使用 openai 兼容模式
|
||||||
|
config:
|
||||||
|
api_key: xxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxx
|
||||||
|
model: glm-4-flash
|
||||||
|
openai_base_url: https://open.bigmodel.cn/api/paas/v4/
|
||||||
|
embedder:
|
||||||
|
provider: openai
|
||||||
|
config:
|
||||||
|
api_key: xxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxx
|
||||||
|
model: embedding-3
|
||||||
|
openai_base_url: https://open.bigmodel.cn/api/paas/v4/
|
||||||
|
vector_store:
|
||||||
|
provider: sqlite
|
||||||
|
config: {}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 使用 OpenAI
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
Memory:
|
||||||
|
powermem:
|
||||||
|
type: powermem
|
||||||
|
enable_user_profile: true
|
||||||
|
llm:
|
||||||
|
provider: openai
|
||||||
|
config:
|
||||||
|
api_key: sk-xxxxxxxxxxxxxxxx
|
||||||
|
model: gpt-4o-mini
|
||||||
|
openai_base_url: https://api.openai.com/v1
|
||||||
|
embedder:
|
||||||
|
provider: openai
|
||||||
|
config:
|
||||||
|
api_key: sk-xxxxxxxxxxxxxxxx
|
||||||
|
model: text-embedding-3-small
|
||||||
|
openai_base_url: https://api.openai.com/v1
|
||||||
|
vector_store:
|
||||||
|
provider: sqlite
|
||||||
|
config: {}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 使用 OceanBase(最佳性能方案)
|
||||||
|
|
||||||
|
OceanBase 是 PowerMem 的最佳搭档,可实现最大性能释放:
|
||||||
|
|
||||||
|
1. 部署 OceanBase 数据库(支持开源本地部署或使用云服务)
|
||||||
|
- 开源部署:https://github.com/oceanbase/oceanbase
|
||||||
|
- 云服务:https://www.oceanbase.com/
|
||||||
|
2. 配置如下:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
Memory:
|
||||||
|
powermem:
|
||||||
|
type: powermem
|
||||||
|
enable_user_profile: true
|
||||||
|
llm:
|
||||||
|
provider: qwen
|
||||||
|
config:
|
||||||
|
api_key: sk-xxxxxxxxxxxxxxxx
|
||||||
|
model: qwen-plus
|
||||||
|
embedder:
|
||||||
|
provider: openai
|
||||||
|
config:
|
||||||
|
api_key: sk-xxxxxxxxxxxxxxxx
|
||||||
|
model: text-embedding-v4
|
||||||
|
openai_base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
|
||||||
|
vector_store:
|
||||||
|
provider: oceanbase
|
||||||
|
config:
|
||||||
|
host: 127.0.0.1
|
||||||
|
port: 2881
|
||||||
|
user: root@test
|
||||||
|
password: your_password
|
||||||
|
db_name: powermem
|
||||||
|
collection_name: memories # 默认值
|
||||||
|
embedding_model_dims: 1536 # 嵌入向量维度,必需参数
|
||||||
|
```
|
||||||
|
|
||||||
|
## 设备记忆隔离
|
||||||
|
|
||||||
|
PowerMem 会自动使用设备 ID(`device_id`)作为 `user_id` 进行记忆隔离。这意味着:
|
||||||
|
|
||||||
|
- 每个设备拥有独立的记忆空间
|
||||||
|
- 不同设备之间的记忆完全隔离
|
||||||
|
- 同一设备的多次对话可以共享记忆上下文
|
||||||
|
|
||||||
|
## 用户画像(UserMemory)
|
||||||
|
|
||||||
|
PowerMem 提供 `UserMemory` 类,可自动从对话中提取用户画像信息。
|
||||||
|
|
||||||
|
> 📌 **版本说明**:PowerMem 0.3.0+ 版本,用户画像功能支持 OceanBase、SeekDB、SQLite 三种存储后端。
|
||||||
|
|
||||||
|
### 启用用户画像
|
||||||
|
|
||||||
|
在配置中设置 `enable_user_profile: true` 即可启用:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
Memory:
|
||||||
|
powermem:
|
||||||
|
type: powermem
|
||||||
|
enable_user_profile: true # 启用用户画像
|
||||||
|
llm:
|
||||||
|
provider: qwen
|
||||||
|
config:
|
||||||
|
api_key: sk-xxxxxxxxxxxxxxxx
|
||||||
|
model: qwen-plus
|
||||||
|
embedder:
|
||||||
|
provider: openai
|
||||||
|
config:
|
||||||
|
api_key: sk-xxxxxxxxxxxxxxxx
|
||||||
|
model: text-embedding-v4
|
||||||
|
openai_base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
|
||||||
|
vector_store:
|
||||||
|
provider: sqlite # 用户画像支持: oceanbase、seekdb、sqlite
|
||||||
|
config: {}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 用户画像能力
|
||||||
|
|
||||||
|
| 能力 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| **信息提取** | 自动从对话中提取姓名、年龄、职业、兴趣等 |
|
||||||
|
| **持续更新** | 随着对话进行,不断完善用户画像 |
|
||||||
|
| **画像检索** | 将用户画像与记忆搜索结合,提升检索相关性 |
|
||||||
|
| **智能遗忘** | 基于艾宾浩斯遗忘曲线,淡化过时信息 |
|
||||||
|
|
||||||
|
### 工作原理
|
||||||
|
|
||||||
|
启用用户画像后,小智在查询记忆时会自动返回:
|
||||||
|
1. **用户画像**:用户的基本信息、兴趣爱好等
|
||||||
|
2. **相关记忆**:与当前对话相关的历史记忆
|
||||||
|
|
||||||
|
> ✅ **版本说明**:PowerMem 0.3.0+ 版本,用户画像功能支持 OceanBase、SeekDB、SQLite 三种存储后端。
|
||||||
|
|
||||||
|
## 与其他记忆组件的对比
|
||||||
|
|
||||||
|
| 特性 | PowerMem | mem0ai | mem_local_short |
|
||||||
|
|------|----------|--------|-----------------|
|
||||||
|
| 工作方式 | 本地总结 | 云端接口 | 本地总结 |
|
||||||
|
| 存储位置 | 本地/云端DB | 云端 | 本地YAML |
|
||||||
|
| 费用 | 取决于LLM和DB | 1000次/月免费 | 完全免费 |
|
||||||
|
| 智能检索 | ✅ 向量搜索 | ✅ 向量搜索 | ❌ 全量返回 |
|
||||||
|
| 用户画像 | ✅ UserMemory | ❌ | ❌ |
|
||||||
|
| 智能遗忘 | ✅ 遗忘曲线 | ❌ | ❌ |
|
||||||
|
| 私有部署 | ✅ 支持 | ❌ 仅云端 | ✅ 支持 |
|
||||||
|
| 数据库支持 | OceanBase(推荐)/SeekDB/PostgreSQL/SQLite | - | YAML 文件 |
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### 1. API 密钥错误
|
||||||
|
|
||||||
|
如果出现 `API key is required` 错误,请检查:
|
||||||
|
- `llm_api_key` 和 `embedding_api_key` 是否正确填写
|
||||||
|
- API 密钥是否有效
|
||||||
|
|
||||||
|
### 2. 模型不存在
|
||||||
|
|
||||||
|
如果出现模型不存在的错误,请确认:
|
||||||
|
- `llm_model` 和 `embedding_model` 名称是否正确
|
||||||
|
- 对应的模型服务是否已开通
|
||||||
|
|
||||||
|
### 3. 连接超时
|
||||||
|
|
||||||
|
如果出现连接超时,可以尝试:
|
||||||
|
- 检查网络连接
|
||||||
|
- 如果使用代理,配置 `llm_base_url` 和 `embedding_base_url`
|
||||||
|
|
||||||
|
## 测试验证
|
||||||
|
|
||||||
|
可以在虚拟环境中测试 PowerMem 是否正常工作:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 激活虚拟环境
|
||||||
|
source .venv/bin/activate
|
||||||
|
|
||||||
|
# 测试 PowerMem 导入
|
||||||
|
python -c "from powermem import AsyncMemory; print('PowerMem 导入成功')"
|
||||||
|
|
||||||
|
# 测试 UserMemory 导入(用户画像功能)
|
||||||
|
python -c "from powermem import UserMemory; print('UserMemory 导入成功')"
|
||||||
|
```
|
||||||
|
|
||||||
|
## 更多资源
|
||||||
|
|
||||||
|
- [PowerMem 官方文档](https://www.powermem.ai/)
|
||||||
|
- [PowerMem GitHub 仓库](https://github.com/oceanbase/powermem)
|
||||||
|
- [PowerMem 使用示例](https://github.com/oceanbase/powermem/tree/main/examples)
|
||||||
|
- [OceanBase 官网](https://www.oceanbase.com/)
|
||||||
|
- [OceanBase GitHub](https://github.com/oceanbase/oceanbase)
|
||||||
|
- [SeekDB GitHub](https://github.com/oceanbase/seekdb)(AI原生搜索数据库)
|
||||||
|
- [阿里云百炼平台](https://bailian.console.aliyun.com/)
|
||||||
|
|
||||||
|
|
@ -304,7 +304,7 @@ public interface Constant {
|
||||||
/**
|
/**
|
||||||
* 版本号
|
* 版本号
|
||||||
*/
|
*/
|
||||||
public static final String VERSION = "0.8.11";
|
public static final String VERSION = "0.9.1";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 无效固件URL
|
* 无效固件URL
|
||||||
|
|
|
||||||
|
|
@ -129,6 +129,10 @@ public class ModelController {
|
||||||
if (entity == null) {
|
if (entity == null) {
|
||||||
return new Result<Void>().error("模型配置不存在");
|
return new Result<Void>().error("模型配置不存在");
|
||||||
}
|
}
|
||||||
|
// 不能关闭默认模型
|
||||||
|
if (status == 0 && entity.getIsDefault() > 0) {
|
||||||
|
return new Result<Void>().error("默认模型配置不允许关闭");
|
||||||
|
}
|
||||||
// 不更新ConfigJson字段
|
// 不更新ConfigJson字段
|
||||||
entity.setConfigJson(null);
|
entity.setConfigJson(null);
|
||||||
entity.setIsEnabled(status);
|
entity.setIsEnabled(status);
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (502, 'system_error_response', '主人,小智现在有点忙,我们稍后再试吧。', 'string', 1, '系统错误时的回复');
|
||||||
|
|
@ -0,0 +1,115 @@
|
||||||
|
-- 新增powermem记忆模型供应器
|
||||||
|
INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`)
|
||||||
|
VALUES ('SYSTEM_Memory_powermem', 'Memory', 'powermem', 'PowerMem记忆', '[
|
||||||
|
{"key":"enable_user_profile","label":"启用用户画像","type":"boolean"},
|
||||||
|
{"key":"llm_provider","label":"LLM提供商","type":"string"},
|
||||||
|
{"key":"llm_api_key","label":"LLM API密钥","type":"string"},
|
||||||
|
{"key":"llm_model","label":"LLM模型","type":"string"},
|
||||||
|
{"key":"openai_base_url","label":"OpenAI基础URL","type":"string"},
|
||||||
|
{"key":"embedding_provider","label":"Embedding提供商","type":"string"},
|
||||||
|
{"key":"embedding_api_key","label":"Embedding API密钥","type":"string"},
|
||||||
|
{"key":"embedding_model","label":"Embedding模型","type":"string"},
|
||||||
|
{"key":"embedding_openai_base_url","label":"Embedding OpenAI基础URL","type":"string"},
|
||||||
|
{"key":"embedding_dims","label":"Embedding维度","type":"integer"},
|
||||||
|
{"key":"vector_store","label":"向量存储配置(JSON)","type":"dict"}
|
||||||
|
]', 4, 1, NOW(), 1, NOW());
|
||||||
|
|
||||||
|
-- 新增PowerMem记忆模型配置
|
||||||
|
INSERT INTO `ai_model_config` VALUES (
|
||||||
|
'Memory_powermem',
|
||||||
|
'Memory',
|
||||||
|
'powermem',
|
||||||
|
'PowerMem记忆',
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
'{\"type\": \"powermem\", \"enable_user_profile\": true, \"llm_provider\": \"openai\", \"llm_api_key\": \"你的LLM API密钥\", \"llm_model\": \"qwen-plus\", \"openai_base_url\": \"\", \"embedding_provider\": \"openai\", \"embedding_api_key\": \"你的嵌入模型API密钥\", \"embedding_model\": \"text-embedding-v4\", \"embedding_openai_base_url\": \"https://api.openai.com/v1\", \"embedding_dims\": \"\", \"vector_store\": {\"provider\": \"sqlite\", \"config\": {}}}',
|
||||||
|
NULL,
|
||||||
|
NULL,
|
||||||
|
4,
|
||||||
|
NULL,
|
||||||
|
NULL,
|
||||||
|
NULL,
|
||||||
|
NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
-- PowerMem记忆配置说明
|
||||||
|
UPDATE `ai_model_config` SET
|
||||||
|
`doc_link` = 'https://github.com/oceanbase/powermem',
|
||||||
|
`remark` = 'PowerMem是OceanBase开源的agent记忆组件,通过本地LLM进行记忆总结
|
||||||
|
GitHub: https://github.com/oceanbase/powermem
|
||||||
|
官网: https://www.powermem.ai/
|
||||||
|
使用示例: https://github.com/oceanbase/powermem/tree/main/examples
|
||||||
|
|
||||||
|
【费用说明】
|
||||||
|
PowerMem本身免费,实际费用取决于所选LLM和数据库:
|
||||||
|
- 使用sqlite + 免费LLM(如glm-4-flash) = 完全免费
|
||||||
|
- 使用云端LLM或云端数据库 = 按对应服务收费
|
||||||
|
|
||||||
|
【enable_user_profile】用户画像功能
|
||||||
|
- false: 使用普通记忆模式(AsyncMemory)
|
||||||
|
- true: 使用用户画像模式(UserMemory),自动提取用户信息
|
||||||
|
- 用户画像功能支持: oceanbase、seekdb、sqlite (powermem 0.3.0+)
|
||||||
|
|
||||||
|
【llm】LLM配置 - 用于记忆总结和用户画像提取
|
||||||
|
provider: LLM提供商,可选值:
|
||||||
|
- qwen: 通义千问 (https://bailian.console.aliyun.com/?apiKey=1#/api-key)
|
||||||
|
- openai: OpenAI兼容接口
|
||||||
|
- zhipu: 智谱AI (https://bigmodel.cn/usercenter/proj-mgmt/apikeys) - 推荐使用免费的glm-4-flash
|
||||||
|
config: LLM配置参数
|
||||||
|
- api_key: API密钥 (必填)
|
||||||
|
- model: 模型名称,如 qwen-plus、glm-4-flash 等
|
||||||
|
- openai_base_url: 自定义服务地址 (可选),如 https://api.openai.com/v1
|
||||||
|
示例:
|
||||||
|
{"provider": "zhipu", "config": {"api_key": "your_key", "model": "glm-4-flash"}}
|
||||||
|
{"provider": "qwen", "config": {"api_key": "your_key", "model": "qwen-plus"}}
|
||||||
|
|
||||||
|
【embedder】Embedding配置 - 用于向量化记忆内容
|
||||||
|
provider: 嵌入模型提供商,可选值:
|
||||||
|
- qwen: 通义千问
|
||||||
|
- openai: OpenAI兼容接口
|
||||||
|
config: Embedding配置参数
|
||||||
|
- api_key: API密钥 (必填)
|
||||||
|
- model: 模型名称,如 text-embedding-v4、text-embedding-3-small 等
|
||||||
|
- openai_base_url: 自定义服务地址 (可选)
|
||||||
|
- embedding_dims: 向量维度 (可选),非1536时需配置
|
||||||
|
示例:
|
||||||
|
{"provider": "openai", "config": {"api_key": "your_key", "model": "text-embedding-v4", "openai_base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1"}}
|
||||||
|
|
||||||
|
【vector_store】数据库存储配置 - 用于存储向量化的记忆
|
||||||
|
provider: 数据库类型,可选值:
|
||||||
|
- sqlite: 轻量级本地数据库 (推荐入门使用,无需额外配置)
|
||||||
|
- oceanbase: OceanBase数据库 (推荐生产使用,最佳性能)
|
||||||
|
- seekdb: SeekDB (推荐,AI应用存储一体)
|
||||||
|
- postgres: PostgreSQL数据库
|
||||||
|
|
||||||
|
SQLite配置 (无需额外配置):
|
||||||
|
{"provider": "sqlite", "config": {}}
|
||||||
|
|
||||||
|
OceanBase配置示例:
|
||||||
|
{"provider": "oceanbase", "config": {
|
||||||
|
"host": "127.0.0.1",
|
||||||
|
"port": 2881,
|
||||||
|
"user": "root@test",
|
||||||
|
"password": "your_password",
|
||||||
|
"db_name": "powermem",
|
||||||
|
"collection_name": "memories",
|
||||||
|
"embedding_model_dims": 1024
|
||||||
|
}}
|
||||||
|
注意:
|
||||||
|
- collection_name: 默认表名,如创建维度错误请删除此表或更改名称
|
||||||
|
- embedding_model_dims: 嵌入向量维度,需与embedder的模型维度匹配
|
||||||
|
例如智谱:embedding-2维度是1024,embedding-3维度是2048
|
||||||
|
|
||||||
|
【推荐配置组合】
|
||||||
|
1. 完全免费方案:
|
||||||
|
- LLM: zhipu + glm-4-flash (免费)
|
||||||
|
- Embedder: 通义千问 text-embedding-v4
|
||||||
|
- Database: sqlite
|
||||||
|
|
||||||
|
2. 生产环境方案:
|
||||||
|
- LLM: qwen-plus 或其他商业模型
|
||||||
|
- Embedder: text-embedding-v4
|
||||||
|
- Database: oceanbase 或 seekdb
|
||||||
|
'
|
||||||
|
WHERE `id` = 'Memory_powermem';
|
||||||
|
|
@ -0,0 +1,2 @@
|
||||||
|
-- 删除无用业务表ai_voiceprint
|
||||||
|
DROP TABLE IF EXISTS ai_voiceprint;
|
||||||
|
|
@ -508,3 +508,24 @@ databaseChangeLog:
|
||||||
- sqlFile:
|
- sqlFile:
|
||||||
encoding: utf8
|
encoding: utf8
|
||||||
path: classpath:db/changelog/202601261730.sql
|
path: classpath:db/changelog/202601261730.sql
|
||||||
|
- changeSet:
|
||||||
|
id: 202602021555
|
||||||
|
author: shengzhou1216
|
||||||
|
changes:
|
||||||
|
- sqlFile:
|
||||||
|
encoding: utf8
|
||||||
|
path: classpath:db/changelog/202602021555.sql
|
||||||
|
- changeSet:
|
||||||
|
id: 202602051017
|
||||||
|
author: RanChen
|
||||||
|
changes:
|
||||||
|
- sqlFile:
|
||||||
|
encoding: utf8
|
||||||
|
path: classpath:db/changelog/202602051017.sql
|
||||||
|
- changeSet:
|
||||||
|
id: 202602051125
|
||||||
|
author: DaGou12138
|
||||||
|
changes:
|
||||||
|
- sqlFile:
|
||||||
|
encoding: utf8
|
||||||
|
path: classpath:db/changelog/202602051125.sql
|
||||||
|
|
|
||||||
|
|
@ -130,7 +130,7 @@ export default {
|
||||||
'chatHistory.loading': 'Loading...',
|
'chatHistory.loading': 'Loading...',
|
||||||
'chatHistory.noMoreData': 'No more data',
|
'chatHistory.noMoreData': 'No more data',
|
||||||
'chatHistory.noChatRecords': 'No chat records',
|
'chatHistory.noChatRecords': 'No chat records',
|
||||||
'chatRecordsDescription': 'Conversation records with agents will be displayed here',
|
'chatHistory.chatRecordsDescription': 'Conversation records with agents will be displayed here',
|
||||||
// Chat History Detail Page
|
// Chat History Detail Page
|
||||||
'chatHistory.pageTitle': 'Chat Detail',
|
'chatHistory.pageTitle': 'Chat Detail',
|
||||||
'chatHistory.assistantName': 'Intelligent Assistant',
|
'chatHistory.assistantName': 'Intelligent Assistant',
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import en from './en'
|
||||||
import zh_TW from './zh_TW'
|
import zh_TW from './zh_TW'
|
||||||
import de from './de'
|
import de from './de'
|
||||||
import vi from './vi'
|
import vi from './vi'
|
||||||
|
import pt_BR from './pt_BR'
|
||||||
|
|
||||||
// 语言包映射
|
// 语言包映射
|
||||||
const messages = {
|
const messages = {
|
||||||
|
|
@ -16,6 +17,7 @@ const messages = {
|
||||||
zh_TW: zh_TW,
|
zh_TW: zh_TW,
|
||||||
de,
|
de,
|
||||||
vi,
|
vi,
|
||||||
|
pt_BR: pt_BR,
|
||||||
}
|
}
|
||||||
|
|
||||||
// 当前使用的语言
|
// 当前使用的语言
|
||||||
|
|
@ -72,5 +74,6 @@ export function getSupportedLanguages(): { code: Language, name: string }[] {
|
||||||
{ code: 'zh_TW', name: '繁體中文' },
|
{ code: 'zh_TW', name: '繁體中文' },
|
||||||
{ code: 'de', name: 'Deutsch' },
|
{ code: 'de', name: 'Deutsch' },
|
||||||
{ code: 'vi', name: 'Tiếng Việt' },
|
{ code: 'vi', name: 'Tiếng Việt' },
|
||||||
|
{ code: 'pt_BR', name: 'Português (Brasil)' },
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
440
main/manager-mobile/src/i18n/pt_BR.ts
Normal file
440
main/manager-mobile/src/i18n/pt_BR.ts
Normal file
|
|
@ -0,0 +1,440 @@
|
||||||
|
// Pacote de idioma Português Brasileiro
|
||||||
|
export default {
|
||||||
|
// TabBar
|
||||||
|
'tabBar.home': 'Início',
|
||||||
|
'tabBar.deviceConfig': 'Config. de Rede',
|
||||||
|
'tabBar.settings': 'Sistema',
|
||||||
|
// Settings page title
|
||||||
|
'settings.title': 'Configurações',
|
||||||
|
// Login page
|
||||||
|
'login.pageTitle': 'Entrar',
|
||||||
|
'login.navigationTitle': 'Entrar',
|
||||||
|
'login.fetchConfigError': 'Falha ao buscar configuração:',
|
||||||
|
'login.selectLanguage': 'Selecionar Idioma',
|
||||||
|
'login.selectLanguageTip': '中文',
|
||||||
|
'login.welcomeBack': 'Bem-vindo de Volta',
|
||||||
|
'login.pleaseLogin': 'Por favor, entre na sua conta',
|
||||||
|
'login.enterUsername': 'Por favor, insira o nome de usuário',
|
||||||
|
'login.enterPassword': 'Por favor, insira a senha',
|
||||||
|
'login.enterCaptcha': 'Por favor, insira o código de verificação',
|
||||||
|
'login.loginButton': 'Entrar',
|
||||||
|
'login.loggingIn': 'Entrando...',
|
||||||
|
'login.noAccount': 'Cadastrar',
|
||||||
|
'login.enterPhone': 'Por favor, insira o número de telefone',
|
||||||
|
'login.selectCountry': 'Selecionar País/Região',
|
||||||
|
'login.confirm': 'Confirmar',
|
||||||
|
'login.serverSetting': 'Configurações do Servidor',
|
||||||
|
'login.requiredUsername': 'O nome de usuário não pode estar vazio',
|
||||||
|
'login.requiredPassword': 'A senha não pode estar vazia',
|
||||||
|
'login.requiredCaptcha': 'O código de verificação não pode estar vazio',
|
||||||
|
'login.requiredMobile': 'Por favor, insira um número de telefone válido',
|
||||||
|
'login.captchaError': 'Erro no código de verificação gráfico',
|
||||||
|
'login.forgotPassword': 'Esqueceu a Senha',
|
||||||
|
|
||||||
|
// Register page
|
||||||
|
'register.pageTitle': 'Cadastro',
|
||||||
|
'register.createAccount': 'Criar Conta',
|
||||||
|
'register.enterUsername': 'Por favor, insira o nome de usuário',
|
||||||
|
'register.enterPassword': 'Por favor, insira a senha',
|
||||||
|
'register.confirmPassword': 'Por favor, confirme a senha',
|
||||||
|
'register.enterPhone': 'Por favor, insira o número de telefone',
|
||||||
|
'register.enterCode': 'Por favor, insira o código de verificação',
|
||||||
|
'register.getCode': 'Obter Código',
|
||||||
|
'register.agreeTerms': 'Li e concordo com os',
|
||||||
|
'register.terms': 'Termos de Uso',
|
||||||
|
'register.privacy': 'Política de Privacidade',
|
||||||
|
'register.registerButton': 'Cadastrar',
|
||||||
|
'register.registering': 'Cadastrando...',
|
||||||
|
'register.haveAccount': 'Já tem uma conta?',
|
||||||
|
'register.loginNow': 'Entrar Agora',
|
||||||
|
'register.selectCountry': 'Selecionar País/Região',
|
||||||
|
'register.confirm': 'Confirmar',
|
||||||
|
'register.captchaSendSuccess': 'Código de verificação enviado com sucesso',
|
||||||
|
|
||||||
|
// Home page
|
||||||
|
'home.pageTitle': 'Início',
|
||||||
|
'home.createAgent': 'Criar Agente',
|
||||||
|
'home.agentName': 'Agente',
|
||||||
|
'home.modelInfo': 'Info do Modelo',
|
||||||
|
'home.lastActive': 'Última Atividade',
|
||||||
|
'home.greeting': 'Olá Jarvis',
|
||||||
|
'home.subtitle': 'Vamos ter',
|
||||||
|
'home.wonderfulDay': 'um dia maravilhoso!',
|
||||||
|
'home.emptyState': 'Nenhum agente disponível',
|
||||||
|
'home.deviceManagement': 'Gerenciamento de Dispositivos',
|
||||||
|
'home.lastConversation': 'Última Conversa:',
|
||||||
|
'home.delete': 'Excluir',
|
||||||
|
'home.createFirstAgent': 'Clique no botão + no canto inferior direito para criar seu primeiro agente',
|
||||||
|
'home.dialogTitle': 'Criar Agente',
|
||||||
|
'home.inputPlaceholder': 'ex: Assistente de Atendimento, Assistente de Voz, Perguntas e Respostas',
|
||||||
|
'home.createError': 'Por favor, insira o nome do agente',
|
||||||
|
'home.createNow': 'Criar Agora',
|
||||||
|
'home.justNow': 'Agora mesmo',
|
||||||
|
'home.minutesAgo': 'minutos atrás',
|
||||||
|
'home.hoursAgo': 'horas atrás',
|
||||||
|
'home.daysAgo': 'dias atrás',
|
||||||
|
|
||||||
|
// Agent page
|
||||||
|
'agent.pageTitle': 'Agente',
|
||||||
|
'agent.roleConfig': 'Configuração de Papel',
|
||||||
|
'agent.deviceManagement': 'Gerenciamento de Dispositivos',
|
||||||
|
'agent.chatHistory': 'Histórico de Conversas',
|
||||||
|
'agent.voiceprintManagement': 'Gerenciamento de Impressão Vocal',
|
||||||
|
'agent.editTitle': 'Editar Agente',
|
||||||
|
'agent.toolsTitle': 'Editar Funcionalidades',
|
||||||
|
'agent.voiceActivityDetection': 'Detecção de Atividade de Voz',
|
||||||
|
'agent.speechRecognition': 'Reconhecimento de Fala',
|
||||||
|
'agent.largeLanguageModel': 'Modelo de Linguagem Grande',
|
||||||
|
'agent.save': 'Salvar',
|
||||||
|
'agent.cancel': 'Cancelar',
|
||||||
|
// Agent Edit Page
|
||||||
|
'agent.basicInfo': 'Informações Básicas',
|
||||||
|
'agent.agentName': 'Nome do Agente',
|
||||||
|
'agent.inputAgentName': 'Por favor, insira o nome do agente',
|
||||||
|
'agent.roleMode': 'Modo de Papel',
|
||||||
|
'agent.roleDescription': 'Descrição do Papel',
|
||||||
|
'agent.inputRoleDescription': 'Por favor, insira a descrição do papel',
|
||||||
|
'agent.modelConfig': 'Configuração do Modelo',
|
||||||
|
'agent.vad': 'Detecção de Atividade de Voz',
|
||||||
|
'agent.asr': 'Reconhecimento de Fala',
|
||||||
|
'agent.llm': 'Modelo de Linguagem Grande',
|
||||||
|
'agent.vllm': 'Modelo de Linguagem Visual',
|
||||||
|
'agent.intent': 'Reconhecimento de Intenção',
|
||||||
|
'agent.memory': 'Memória',
|
||||||
|
'agent.voiceSettings': 'Configurações de Voz',
|
||||||
|
'agent.tts': 'Texto para Fala',
|
||||||
|
'agent.voiceprint': 'Voz do Agente',
|
||||||
|
'agent.plugins': 'Plugins',
|
||||||
|
'agent.editFunctions': 'Editar Funções',
|
||||||
|
'agent.historyMemory': 'Memória de Histórico',
|
||||||
|
'agent.memoryContent': 'Conteúdo da memória',
|
||||||
|
'agent.saving': 'Salvando...',
|
||||||
|
'agent.saveSuccess': 'Salvo com sucesso',
|
||||||
|
'agent.saveFail': 'Falha ao salvar',
|
||||||
|
'agent.loadFail': 'Falha ao carregar',
|
||||||
|
'agent.pleaseInputAgentName': 'Por favor, insira o nome do agente',
|
||||||
|
'agent.pleaseInputRoleDescription': 'Por favor, insira a descrição do papel',
|
||||||
|
'agent.pleaseSelect': 'Por favor, selecione',
|
||||||
|
|
||||||
|
// Chat History Page
|
||||||
|
'chatHistory.getChatSessions': 'Obter lista de sessões de conversa',
|
||||||
|
'chatHistory.noSelectedAgent': 'Nenhum agente selecionado',
|
||||||
|
'chatHistory.getChatSessionsFailed': 'Falha ao obter lista de sessões de conversa:',
|
||||||
|
'chatHistory.unknownTime': 'Hora desconhecida',
|
||||||
|
'chatHistory.justNow': 'Agora mesmo',
|
||||||
|
'chatHistory.minutesAgo': '{minutes} minutos atrás',
|
||||||
|
'chatHistory.hoursAgo': '{hours} horas atrás',
|
||||||
|
'chatHistory.daysAgo': '{days} dias atrás',
|
||||||
|
'chatHistory.conversationRecord': 'Registro de Conversas',
|
||||||
|
'chatHistory.totalChats': '{count} conversas no total',
|
||||||
|
'chatHistory.loading': 'Carregando...',
|
||||||
|
'chatHistory.noMoreData': 'Não há mais dados',
|
||||||
|
'chatHistory.noChatRecords': 'Nenhum registro de conversa',
|
||||||
|
'chatHistory.chatRecordsDescription': 'Os registros de conversas com agentes serão exibidos aqui',
|
||||||
|
// Chat History Detail Page
|
||||||
|
'chatHistory.pageTitle': 'Detalhe da Conversa',
|
||||||
|
'chatHistory.assistantName': 'Assistente Inteligente',
|
||||||
|
'chatHistory.userName': 'Usuário',
|
||||||
|
'chatHistory.aiAssistantName': 'Assistente IA',
|
||||||
|
'chatHistory.loadFailed': 'Falha ao carregar histórico de conversas',
|
||||||
|
'chatHistory.parameterError': 'Erro de parâmetro da página',
|
||||||
|
'chatHistory.invalidAudioId': 'ID de áudio inválido',
|
||||||
|
'chatHistory.audioPlayFailed': 'Falha na reprodução de áudio',
|
||||||
|
'chatHistory.playAudioFailed': 'Falha ao reproduzir áudio',
|
||||||
|
|
||||||
|
// Device management page
|
||||||
|
'device.pageTitle': 'Gerenciamento de Dispositivos',
|
||||||
|
'device.noDevices': 'Nenhum dispositivo disponível',
|
||||||
|
'device.macAddress': 'Endereço MAC',
|
||||||
|
'device.firmwareVersion': 'Versão do Firmware',
|
||||||
|
'device.lastConnected': 'Última Conversa',
|
||||||
|
'device.otaUpdate': 'Atualização OTA',
|
||||||
|
'device.unbind': 'Desvincular',
|
||||||
|
'device.confirmUnbind': 'Confirmar',
|
||||||
|
'device.bindDevice': 'Vincular Novo Dispositivo',
|
||||||
|
'device.deviceType': 'Tipo de Dispositivo',
|
||||||
|
'device.loading': 'Carregando...',
|
||||||
|
'device.neverConnected': 'Nunca conectado',
|
||||||
|
'device.justNow': 'Agora mesmo',
|
||||||
|
'device.minutesAgo': '{minutes} minutos atrás',
|
||||||
|
'device.hoursAgo': '{hours} horas atrás',
|
||||||
|
'device.daysAgo': '{days} dias atrás',
|
||||||
|
'device.otaAutoUpdateEnabled': 'Atualização automática OTA ativada',
|
||||||
|
'device.otaAutoUpdateDisabled': 'Atualização automática OTA desativada',
|
||||||
|
'device.operationFailed': 'Operação falhou, por favor tente novamente',
|
||||||
|
'device.deviceUnbound': 'Dispositivo desvinculado',
|
||||||
|
'device.unbindFailed': 'Falha ao desvincular, por favor tente novamente',
|
||||||
|
'device.unbindDevice': 'Desvincular Dispositivo',
|
||||||
|
'device.confirmUnbindDevice': 'Tem certeza que deseja desvincular o dispositivo "{macAddress}"?',
|
||||||
|
'device.cancel': 'Cancelar',
|
||||||
|
'device.noDevice': 'Nenhum Dispositivo',
|
||||||
|
'device.pleaseSelectAgent': 'Por favor, selecione um agente primeiro',
|
||||||
|
'device.deviceBindSuccess': 'Dispositivo vinculado com sucesso!',
|
||||||
|
'device.bindFailed': 'Falha ao vincular, por favor verifique se o código de verificação está correto',
|
||||||
|
'device.enterDeviceCode': 'Por favor, insira o código de verificação do dispositivo',
|
||||||
|
'device.bindNow': 'Vincular Agora',
|
||||||
|
'device.lastConnection': 'Última Conexão',
|
||||||
|
'device.clickToBindFirstDevice': 'Clique no botão + no canto inferior direito para vincular seu primeiro dispositivo',
|
||||||
|
|
||||||
|
// Common
|
||||||
|
'common.success': 'Sucesso',
|
||||||
|
'common.fail': 'Falhou',
|
||||||
|
'common.loading': 'Carregando...',
|
||||||
|
'common.confirm': 'Confirmar',
|
||||||
|
'common.cancel': 'Cancelar',
|
||||||
|
'common.delete': 'Excluir',
|
||||||
|
'common.edit': 'Editar',
|
||||||
|
'common.add': 'Adicionar',
|
||||||
|
'common.pleaseSelect': 'Por favor, selecione',
|
||||||
|
'common.unknownError': 'Erro desconhecido',
|
||||||
|
'common.networkError': 'Erro de rede',
|
||||||
|
|
||||||
|
// Retrieve Password page
|
||||||
|
'retrievePassword.title': 'Redefinir Senha',
|
||||||
|
'retrievePassword.subtitle': 'Recupere a senha da sua conta pelo número de celular',
|
||||||
|
'retrievePassword.mobileRequired': 'Por favor, insira o número de celular',
|
||||||
|
'retrievePassword.inputCorrectMobile': 'Por favor, insira um número de celular válido',
|
||||||
|
'retrievePassword.captchaRequired': 'Por favor, insira o código de verificação gráfico',
|
||||||
|
'retrievePassword.mobileCaptchaRequired': 'Por favor, insira o código de verificação por SMS',
|
||||||
|
'retrievePassword.newPasswordRequired': 'Por favor, insira a nova senha',
|
||||||
|
'retrievePassword.confirmNewPasswordRequired': 'Por favor, confirme a nova senha',
|
||||||
|
'retrievePassword.passwordsNotMatch': 'As senhas não coincidem',
|
||||||
|
'retrievePassword.mobilePlaceholder': 'Por favor, insira o número de celular',
|
||||||
|
'retrievePassword.captchaPlaceholder': 'Por favor, insira o código de verificação gráfico',
|
||||||
|
'retrievePassword.mobileCaptchaPlaceholder': 'Por favor, insira o código de verificação por SMS',
|
||||||
|
'retrievePassword.newPasswordPlaceholder': 'Por favor, insira a nova senha',
|
||||||
|
'retrievePassword.confirmNewPasswordPlaceholder': 'Por favor, confirme a nova senha',
|
||||||
|
'retrievePassword.getMobileCaptcha': 'Obter Código',
|
||||||
|
'retrievePassword.captchaSendSuccess': 'Código de verificação enviado com sucesso',
|
||||||
|
'retrievePassword.passwordUpdateSuccess': 'Senha redefinida com sucesso',
|
||||||
|
'retrievePassword.resetButton': 'Redefinir Senha',
|
||||||
|
'retrievePassword.goToLogin': 'Voltar ao Login',
|
||||||
|
|
||||||
|
// SM2 encryption related error messages
|
||||||
|
'sm2.publicKeyNotConfigured': 'Chave pública SM2 não configurada, por favor entre em contato com o administrador',
|
||||||
|
'sm2.encryptionFailed': 'Falha na criptografia da senha',
|
||||||
|
'sm2.keyGenerationFailed': 'Falha na geração do par de chaves',
|
||||||
|
'sm2.invalidPublicKey': 'Formato de chave pública inválido',
|
||||||
|
'sm2.encryptionError': 'Ocorreu um erro durante a criptografia',
|
||||||
|
'sm2.publicKeyRetry': 'Tentando obter a chave pública novamente...',
|
||||||
|
'sm2.publicKeyRetryFailed': 'Falha na nova tentativa de obter a chave pública',
|
||||||
|
|
||||||
|
// Voiceprint page
|
||||||
|
'voiceprint.noSelectedAgent': 'Nenhum agente selecionado',
|
||||||
|
'voiceprint.pleaseSelectAgent': 'Por favor, selecione um agente primeiro',
|
||||||
|
'voiceprint.fetchHistoryFailed': 'Falha ao buscar histórico de conversas',
|
||||||
|
'voiceprint.clickToSelectVector': 'Clique para selecionar vetor de impressão vocal',
|
||||||
|
'voiceprint.pleaseInputName': 'Por favor, insira o nome',
|
||||||
|
'voiceprint.pleaseSelectVector': 'Por favor, selecione o vetor de impressão vocal',
|
||||||
|
'voiceprint.addSuccess': 'Adicionado com sucesso',
|
||||||
|
'voiceprint.addFailed': 'Falha ao adicionar locutor',
|
||||||
|
'voiceprint.editSuccess': 'Editado com sucesso',
|
||||||
|
'voiceprint.editFailed': 'Falha ao editar locutor',
|
||||||
|
'voiceprint.deleteConfirmMsg': 'Tem certeza que deseja excluir este locutor?',
|
||||||
|
'voiceprint.deleteConfirmTitle': 'Confirmar Exclusão',
|
||||||
|
'voiceprint.deleteSuccess': 'Excluído com sucesso',
|
||||||
|
'voiceprint.loading': 'Carregando...',
|
||||||
|
'voiceprint.delete': 'Excluir',
|
||||||
|
'voiceprint.emptyTitle': 'Nenhum dado de impressão vocal',
|
||||||
|
'voiceprint.emptyDesc': 'Clique no botão + no canto inferior direito para adicionar seu primeiro locutor',
|
||||||
|
'voiceprint.addSpeaker': 'Adicionar Locutor',
|
||||||
|
'voiceprint.voiceVector': 'Vetor de Impressão Vocal',
|
||||||
|
'voiceprint.name': 'Nome',
|
||||||
|
'voiceprint.description': 'Descrição',
|
||||||
|
'voiceprint.pleaseInputDescription': 'Por favor, insira a descrição',
|
||||||
|
'voiceprint.cancel': 'Cancelar',
|
||||||
|
'voiceprint.save': 'Salvar',
|
||||||
|
'voiceprint.editSpeaker': 'Editar Locutor',
|
||||||
|
'voiceprint.selectVector': 'Selecionar Vetor de Impressão Vocal',
|
||||||
|
'voiceprint.voiceprintInterfaceNotConfigured': 'Interface de impressão vocal não configurada',
|
||||||
|
|
||||||
|
// Settings page
|
||||||
|
'settings.pageTitle': 'Configurações',
|
||||||
|
'settings.navigationTitle': 'Configurações',
|
||||||
|
'settings.networkSettings': 'Configurações de Rede',
|
||||||
|
'settings.serverApiUrl': 'URL da API do Servidor',
|
||||||
|
'settings.validServerUrl': 'Por favor, insira um endereço de servidor válido (começando com http ou https e terminando com /xiaozhi)',
|
||||||
|
'settings.saveSettings': 'Salvar Configurações',
|
||||||
|
'settings.resetDefault': 'Restaurar Padrão',
|
||||||
|
'settings.restartApp': 'Reiniciar App',
|
||||||
|
'settings.restartNow': 'Reiniciar Agora',
|
||||||
|
'settings.restartLater': 'Depois',
|
||||||
|
// About us
|
||||||
|
'settings.aboutApp': 'Sobre o Console XiaoZhi',
|
||||||
|
'settings.aboutContent': 'Console XiaoZhi\n\nUm aplicativo móvel de gerenciamento multiplataforma construído com Vue.js 3 + uni-app, oferecendo gerenciamento de dispositivos, configuração de agentes e outras funcionalidades para o hardware inteligente xiaozhi ESP32.\n\n© 2025 xiaozhi-esp32-server {version}',
|
||||||
|
'settings.restartSuccess': 'Salvo, você pode reiniciar o app manualmente depois',
|
||||||
|
'settings.serverUrlSavedAndCacheCleared': 'URL do servidor salva e cache limpo',
|
||||||
|
'settings.resetToDefaultAndCacheCleared': 'Restaurado ao padrão e cache limpo',
|
||||||
|
'settings.resetSuccess': 'Restauração bem-sucedida',
|
||||||
|
'settings.enterServerUrl': 'Por favor, insira a URL do servidor',
|
||||||
|
'settings.clearCacheFailed': 'Falha ao limpar o cache',
|
||||||
|
'settings.cacheManagement': 'Gerenciamento de Cache',
|
||||||
|
'settings.totalCacheSize': 'Tamanho Total do Cache',
|
||||||
|
'settings.appDataSize': 'Tamanho Total dos Dados do App',
|
||||||
|
'settings.cacheClear': 'Limpar Cache',
|
||||||
|
'settings.clearAllCache': 'Limpar todos os dados de cache',
|
||||||
|
'settings.clearCache': 'Limpar Cache',
|
||||||
|
'settings.modifyWillClearCache': 'Modificações irão limpar o cache',
|
||||||
|
'settings.appInfo': 'Informações do App',
|
||||||
|
'settings.aboutUs': 'Sobre Nós',
|
||||||
|
'settings.appVersion': 'Versão do App e Info da Equipe',
|
||||||
|
'settings.confirmClear': 'Confirmar Limpeza',
|
||||||
|
'settings.confirmClearMessage': 'Tem certeza que deseja limpar todo o cache? Isso excluirá todos os dados, incluindo o status de login, e exigirá novo login.',
|
||||||
|
'settings.cacheCleared': 'Cache limpo com sucesso, redirecionando para a página de login',
|
||||||
|
'settings.languageSettings': 'Configurações de Idioma',
|
||||||
|
'settings.language': 'Idioma',
|
||||||
|
'settings.selectLanguage': 'Selecionar Idioma',
|
||||||
|
'settings.languageChanged': 'Idioma alterado com sucesso',
|
||||||
|
|
||||||
|
// Messages
|
||||||
|
'message.loginSuccess': 'Login realizado com sucesso!',
|
||||||
|
'message.loginFail': 'Falha no login',
|
||||||
|
'message.registerSuccess': 'Cadastro realizado com sucesso',
|
||||||
|
'message.registerFail': 'Falha no cadastro',
|
||||||
|
'message.saveSuccess': 'Salvo com sucesso',
|
||||||
|
'message.saveFail': 'Falha ao salvar',
|
||||||
|
'message.deleteSuccess': 'Excluído com sucesso',
|
||||||
|
'message.deleteFail': 'Falha ao excluir',
|
||||||
|
'message.bindSuccess': 'Vinculação realizada com sucesso',
|
||||||
|
'message.bindFail': 'Falha na vinculação',
|
||||||
|
'message.unbindSuccess': 'Desvinculação realizada com sucesso',
|
||||||
|
'message.unbindFail': 'Falha na desvinculação',
|
||||||
|
'message.networkError': 'Erro de rede, por favor verifique sua conexão',
|
||||||
|
'message.serverError': 'Erro no servidor, por favor tente novamente mais tarde',
|
||||||
|
'message.invalidAddress': 'Endereço inválido, por favor verifique se o servidor está iniciado ou se a conexão de rede está normal',
|
||||||
|
'message.languageChanged': 'Idioma alterado',
|
||||||
|
'message.passwordError': 'Conta ou senha incorretos',
|
||||||
|
'message.phoneRegistered': 'Este número de telefone já está cadastrado',
|
||||||
|
|
||||||
|
// Agent Tools Page
|
||||||
|
'agent.tools.pageTitle': 'Ferramentas do Agente',
|
||||||
|
'agent.tools.unselected': 'Não selecionado',
|
||||||
|
'agent.tools.selected': 'Selecionado',
|
||||||
|
'agent.tools.noMorePlugins': 'Não há mais plugins',
|
||||||
|
'agent.tools.pleaseSelectPlugin': 'Por favor, selecione a função do plugin',
|
||||||
|
'agent.tools.builtInPlugins': 'Plugins Integrados',
|
||||||
|
'agent.tools.mcpAccessPoint': 'Ponto de Acesso MCP',
|
||||||
|
'agent.tools.copy': 'Copiar',
|
||||||
|
'agent.tools.noTools': 'Nenhuma ferramenta disponível',
|
||||||
|
'agent.tools.parameterConfig': 'Configuração de Parâmetros',
|
||||||
|
'agent.tools.noParamsNeeded': 'Nenhum parâmetro necessário',
|
||||||
|
'agent.tools.pleaseInput': 'Por favor, insira',
|
||||||
|
'agent.tools.inputOneItemPerLine': 'Insira um item por linha',
|
||||||
|
'agent.tools.pleaseInputValidJson': 'Por favor, insira um formato JSON válido',
|
||||||
|
'agent.tools.enableFunction': 'Ativar Função',
|
||||||
|
'agent.tools.toggleFunction': 'Ativar ou desativar esta função',
|
||||||
|
'agent.tools.jsonFormatError': 'Erro no formato JSON',
|
||||||
|
'agent.tools.noMcpAddressToCopy': 'Nenhum endereço MCP para copiar',
|
||||||
|
'agent.tools.mcpAddressCopied': 'Endereço MCP copiado para a área de transferência',
|
||||||
|
'agent.tools.copyFailed': 'Falha ao copiar, por favor tente novamente',
|
||||||
|
'agent.tools.defaultValue': 'Valor padrão',
|
||||||
|
'agent.tools.notSelected': 'Não selecionado',
|
||||||
|
'agent.tools.clickToConfigure': 'Clique para configurar',
|
||||||
|
'agent.tools.mcpEndpoint': 'Endpoint MCP',
|
||||||
|
'agent.tools.eachLineOneItem': 'Insira um item por linha',
|
||||||
|
|
||||||
|
// Device Config page
|
||||||
|
'deviceConfig.pageTitle': 'Configuração do Dispositivo',
|
||||||
|
'deviceConfig.wifiConfig': 'Configuração WiFi',
|
||||||
|
'deviceConfig.ultrasonicConfig': 'Configuração Ultrassônica',
|
||||||
|
'deviceConfig.selectConfigMethod': 'Selecionar Método de Configuração',
|
||||||
|
'deviceConfig.networkConfig': 'Configuração de Rede',
|
||||||
|
'deviceConfig.selectedNetwork': 'Rede Selecionada',
|
||||||
|
'deviceConfig.signal': 'Sinal',
|
||||||
|
'deviceConfig.openNetwork': 'Rede Aberta',
|
||||||
|
'deviceConfig.encryptedNetwork': 'Rede Criptografada',
|
||||||
|
'deviceConfig.password': 'Senha',
|
||||||
|
'deviceConfig.pleaseEnterPassword': 'Por favor, insira a senha do WiFi',
|
||||||
|
'deviceConfig.startConfig': 'Iniciar Configuração',
|
||||||
|
'deviceConfig.connectToXiaozhiHotspot': 'Por favor, conecte-se ao hotspot xiaozhi primeiro',
|
||||||
|
'deviceConfig.detecting': 'Detectando...',
|
||||||
|
'deviceConfig.reDetect': 'Detectar Novamente',
|
||||||
|
'deviceConfig.alreadyConnected': 'Conectado ao hotspot xiaozhi',
|
||||||
|
'deviceConfig.refreshStatus': 'Atualizar Status',
|
||||||
|
'deviceConfig.wifiNetworks': 'Redes WiFi',
|
||||||
|
'deviceConfig.selectWifiNetwork': 'Selecionar Rede WiFi',
|
||||||
|
'deviceConfig.refreshScan': 'Atualizar Busca',
|
||||||
|
'deviceConfig.noWifiNetworks': 'Nenhuma rede WiFi disponível',
|
||||||
|
'deviceConfig.clickToRefreshScan': 'Por favor, clique em Atualizar Busca',
|
||||||
|
'deviceConfig.signalStrong': 'Sinal Forte',
|
||||||
|
'deviceConfig.signalGood': 'Sinal Bom',
|
||||||
|
'deviceConfig.signalFair': 'Sinal Regular',
|
||||||
|
'deviceConfig.signalWeak': 'Sinal Fraco',
|
||||||
|
'deviceConfig.channel': 'Canal',
|
||||||
|
'deviceConfig.about': 'aproximadamente',
|
||||||
|
'deviceConfig.seconds': 'segundos',
|
||||||
|
'deviceConfig.generating': 'Gerando...',
|
||||||
|
'deviceConfig.playing': 'Reproduzindo...',
|
||||||
|
'deviceConfig.generateAndPlaySoundWave': 'Gerar e Reproduzir Onda Sonora',
|
||||||
|
'deviceConfig.playSoundWave': 'Reproduzir Onda Sonora',
|
||||||
|
'deviceConfig.stopPlaying': 'Parar Reprodução',
|
||||||
|
'deviceConfig.autoLoopPlaySoundWave': 'Reproduzir Onda Sonora em Loop Automático',
|
||||||
|
'deviceConfig.configAudioFile': 'Arquivo de Áudio de Configuração',
|
||||||
|
'deviceConfig.duration': 'Duração',
|
||||||
|
'deviceConfig.ultrasonicConfigInstructions': 'Instruções de Configuração Ultrassônica',
|
||||||
|
'deviceConfig.ensureWifiNetworkSelectedAndPasswordEntered': 'Certifique-se de que a rede WiFi foi selecionada e a senha foi inserida',
|
||||||
|
'deviceConfig.clickGenerateAndPlaySoundWave': 'Clique em Gerar e Reproduzir Onda Sonora, o sistema codificará as informações de configuração em áudio',
|
||||||
|
'deviceConfig.bringPhoneCloseToXiaozhiDevice': 'Aproxime o celular do dispositivo xiaozhi (distância de 1-2 metros)',
|
||||||
|
'deviceConfig.duringAudioPlaybackXiaozhiWillReceive': 'Durante a reprodução do áudio, o xiaozhi receberá e decodificará as informações de configuração',
|
||||||
|
'deviceConfig.afterConfigSuccessDeviceWillConnect': 'Após a configuração bem-sucedida, o dispositivo se conectará automaticamente à rede WiFi',
|
||||||
|
'deviceConfig.usesAfskModulation': 'Utiliza tecnologia de modulação AFSK, transmitindo dados pelas frequências de 1800Hz e 1500Hz',
|
||||||
|
'deviceConfig.ensureModeratePhoneVolume': 'Por favor, certifique-se de que o volume do celular está moderado para evitar interferência de ruídos ambientais',
|
||||||
|
'deviceConfig.generatingUltrasonicConfigAudio': 'Gerando áudio de configuração ultrassônica',
|
||||||
|
'deviceConfig.configData': 'Dados de configuração',
|
||||||
|
'deviceConfig.dataBytesLength': 'Comprimento dos bytes de dados',
|
||||||
|
'deviceConfig.bitStreamLength': 'Comprimento do fluxo de bits',
|
||||||
|
'deviceConfig.base64Length': 'Comprimento Base64',
|
||||||
|
'deviceConfig.audioFileTooLarge': 'Arquivo de áudio muito grande, por favor reduza o tamanho do SSID ou da senha',
|
||||||
|
'deviceConfig.audioGenerationSuccess': 'Áudio gerado com sucesso',
|
||||||
|
'deviceConfig.samplePoints': 'Pontos de amostra',
|
||||||
|
'deviceConfig.soundWaveGenerationSuccess': 'Onda sonora gerada com sucesso',
|
||||||
|
'deviceConfig.audioGenerationFailed': 'Falha na geração do áudio',
|
||||||
|
'deviceConfig.soundWaveGenerationFailed': 'Falha na geração da onda sonora',
|
||||||
|
'deviceConfig.pleaseGenerateAudioFirst': 'Por favor, gere o áudio primeiro',
|
||||||
|
'deviceConfig.startPlayingUltrasonicConfigAudio': 'Iniciando reprodução do áudio de configuração ultrassônica',
|
||||||
|
'deviceConfig.ultrasonicAudioStartedPlaying': 'Reprodução do áudio ultrassônico iniciada',
|
||||||
|
'deviceConfig.startPlayingConfigSoundWave': 'Reprodução da onda sonora de configuração iniciada',
|
||||||
|
'deviceConfig.ultrasonicAudioPlaybackEnded': 'Reprodução do áudio ultrassônico finalizada',
|
||||||
|
'deviceConfig.audioPlaybackFailed': 'Falha na reprodução do áudio',
|
||||||
|
'deviceConfig.audioResourceBusy': 'Recurso de áudio ocupado, por favor tente novamente mais tarde',
|
||||||
|
'deviceConfig.audioFormatNotSupported': 'Formato de áudio não suportado, pode ser um problema de URI de dados',
|
||||||
|
'deviceConfig.audioFileError': 'Erro no arquivo de áudio',
|
||||||
|
'deviceConfig.cleaningUpAudioContext': 'Limpando contexto de áudio',
|
||||||
|
'deviceConfig.cleaningUpAudioContextFailed': 'Falha ao limpar contexto de áudio',
|
||||||
|
'deviceConfig.stoppedPlayingUltrasonicAudio': 'Reprodução do áudio ultrassônico interrompida',
|
||||||
|
'deviceConfig.stoppedPlaying': 'Reprodução interrompida',
|
||||||
|
'deviceConfig.configMethod': 'Método de Configuração',
|
||||||
|
'deviceConfig.enterWifiPassword': 'Por favor, insira a senha do WiFi',
|
||||||
|
'deviceConfig.xiaozhi': 'xiaozhi',
|
||||||
|
'deviceConfig.connectXiaozhiHotspot': 'Por favor, conecte-se ao hotspot xiaozhi',
|
||||||
|
'deviceConfig.wifiScanResponse': 'Resposta da busca WiFi',
|
||||||
|
'deviceConfig.scanSuccess': 'Busca bem-sucedida',
|
||||||
|
'deviceConfig.networks': 'redes',
|
||||||
|
'deviceConfig.wifiScanFailed': 'Falha na busca WiFi',
|
||||||
|
'deviceConfig.scanFailedCheckConnection': 'Falha na busca, por favor verifique a conexão',
|
||||||
|
'deviceConfig.checking': 'Verificando',
|
||||||
|
'deviceConfig.reCheck': 'Verificar Novamente',
|
||||||
|
'deviceConfig.connectedXiaozhiHotspot': 'Conectado ao hotspot xiaozhi',
|
||||||
|
'deviceConfig.wifiNetwork': 'Rede WiFi',
|
||||||
|
'deviceConfig.scanning': 'Buscando',
|
||||||
|
'deviceConfig.cancel': 'Cancelar',
|
||||||
|
'deviceConfig.clickRefreshScan': 'Por favor, clique em Atualizar Busca',
|
||||||
|
'deviceConfig.esp32ConnectionCheckFailed': 'Falha na verificação de conexão ESP32',
|
||||||
|
'deviceConfig.startWifiConfig': 'Iniciando configuração WiFi',
|
||||||
|
'deviceConfig.configSuccess': 'Configuração bem-sucedida',
|
||||||
|
'deviceConfig.deviceWillConnectTo': 'O dispositivo se conectará a',
|
||||||
|
'deviceConfig.deviceWillRestart': 'O dispositivo será reiniciado',
|
||||||
|
'deviceConfig.pleaseDisconnectXiaozhiHotspot': 'Por favor, desconecte-se do hotspot xiaozhi',
|
||||||
|
'deviceConfig.configFailed': 'Falha na configuração',
|
||||||
|
'deviceConfig.wifiConfigFailed': 'Falha na configuração WiFi',
|
||||||
|
'deviceConfig.pleaseCheckNetworkConnection': 'Por favor, verifique a conexão de rede',
|
||||||
|
'deviceConfig.startWifiConfigButton': 'Iniciar Configuração',
|
||||||
|
'deviceConfig.wifiConfigInstructions': 'Instruções de Configuração WiFi',
|
||||||
|
'deviceConfig.phoneConnectXiaozhiHotspot': 'Conecte o celular ao hotspot xiaozhi',
|
||||||
|
'deviceConfig.selectTargetWifiNetwork': 'Selecione a rede WiFi de destino',
|
||||||
|
'deviceConfig.enterWifiPasswordIfNeeded': 'Insira a senha do WiFi se necessário',
|
||||||
|
'deviceConfig.clickStartConfigAndWait': 'Clique em Iniciar Configuração e aguarde',
|
||||||
|
'deviceConfig.afterConfigSuccessDeviceWillRestart': 'Após a configuração bem-sucedida, o dispositivo reiniciará automaticamente',
|
||||||
|
'deviceConfig.audioPlaybackError': 'Erro na reprodução de áudio',
|
||||||
|
'deviceConfig.playbackFailed': 'Falha na reprodução',
|
||||||
|
}
|
||||||
|
|
@ -235,7 +235,7 @@ function showAbout() {
|
||||||
title: t('settings.aboutApp', { appName: import.meta.env.VITE_APP_TITLE }),
|
title: t('settings.aboutApp', { appName: import.meta.env.VITE_APP_TITLE }),
|
||||||
content: t('settings.aboutContent', {
|
content: t('settings.aboutContent', {
|
||||||
appName: import.meta.env.VITE_APP_TITLE,
|
appName: import.meta.env.VITE_APP_TITLE,
|
||||||
version: '0.8.11'
|
version: '0.9.1'
|
||||||
}),
|
}),
|
||||||
showCancel: false,
|
showCancel: false,
|
||||||
confirmText: t('common.confirm'),
|
confirmText: t('common.confirm'),
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import { ref } from 'vue'
|
||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
|
|
||||||
// 支持的语言类型
|
// 支持的语言类型
|
||||||
export type Language = 'zh_CN' | 'en' | 'zh_TW' | 'de' | 'vi'
|
export type Language = 'zh_CN' | 'en' | 'zh_TW' | 'de' | 'vi' | 'pt_BR'
|
||||||
|
|
||||||
export interface LangStore {
|
export interface LangStore {
|
||||||
currentLang: Language
|
currentLang: Language
|
||||||
|
|
|
||||||
|
|
@ -210,6 +210,7 @@ export default {
|
||||||
paramDropdownVisible: false,
|
paramDropdownVisible: false,
|
||||||
voiceCloneDropdownVisible: false,
|
voiceCloneDropdownVisible: false,
|
||||||
userMenuVisible: false, // 添加用户菜单可见状态
|
userMenuVisible: false, // 添加用户菜单可见状态
|
||||||
|
menuVisibleTimer: null, // 菜单显示定时器,防止够快触发
|
||||||
isSmallScreen: false,
|
isSmallScreen: false,
|
||||||
// 搜索历史相关
|
// 搜索历史相关
|
||||||
searchHistory: [],
|
searchHistory: [],
|
||||||
|
|
@ -253,6 +254,8 @@ export default {
|
||||||
return this.$t("language.de");
|
return this.$t("language.de");
|
||||||
case "vi":
|
case "vi":
|
||||||
return this.$t("language.vi");
|
return this.$t("language.vi");
|
||||||
|
case "pt_BR":
|
||||||
|
return this.$t("language.ptBR");
|
||||||
default:
|
default:
|
||||||
return this.$t("language.zhCN");
|
return this.$t("language.zhCN");
|
||||||
}
|
}
|
||||||
|
|
@ -271,6 +274,8 @@ export default {
|
||||||
return require("@/assets/xiaozhi-ai_de.png");
|
return require("@/assets/xiaozhi-ai_de.png");
|
||||||
case "vi":
|
case "vi":
|
||||||
return require("@/assets/xiaozhi-ai_vi.png");
|
return require("@/assets/xiaozhi-ai_vi.png");
|
||||||
|
case "pt_BR":
|
||||||
|
return require("@/assets/xiaozhi-ai_en.png");
|
||||||
default:
|
default:
|
||||||
return require("@/assets/xiaozhi-ai.png");
|
return require("@/assets/xiaozhi-ai.png");
|
||||||
}
|
}
|
||||||
|
|
@ -302,6 +307,10 @@ export default {
|
||||||
label: this.$t("language.vi"),
|
label: this.$t("language.vi"),
|
||||||
value: "vi",
|
value: "vi",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
label: this.$t("language.ptBR"),
|
||||||
|
value: "pt_BR",
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
@ -631,7 +640,12 @@ export default {
|
||||||
|
|
||||||
// 处理用户菜单可见性变化
|
// 处理用户菜单可见性变化
|
||||||
handleUserMenuVisibleChange(visible) {
|
handleUserMenuVisibleChange(visible) {
|
||||||
this.userMenuVisible = visible;
|
if (this.menuVisibleTimer) return;
|
||||||
|
this.menuVisibleTimer = setTimeout(() => {
|
||||||
|
this.userMenuVisible = visible;
|
||||||
|
clearTimeout(this.menuVisibleTimer);
|
||||||
|
this.menuVisibleTimer = null;
|
||||||
|
}, 100);
|
||||||
|
|
||||||
// 如果菜单关闭了,也要清空选择值
|
// 如果菜单关闭了,也要清空选择值
|
||||||
if (!visible) {
|
if (!visible) {
|
||||||
|
|
|
||||||
|
|
@ -105,6 +105,7 @@ export default {
|
||||||
},
|
},
|
||||||
cancel() {
|
cancel() {
|
||||||
this.saving = false; // 取消时重置状态
|
this.saving = false; // 取消时重置状态
|
||||||
|
this.dialogKey = Date.now();
|
||||||
this.$emit('cancel');
|
this.$emit('cancel');
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
@ -115,9 +116,7 @@ export default {
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
visible(newVal) {
|
visible(newVal) {
|
||||||
if (newVal) {
|
if (!newVal) {
|
||||||
this.dialogKey = Date.now();
|
|
||||||
} else {
|
|
||||||
// 当对话框关闭时,重置saving状态
|
// 当对话框关闭时,重置saving状态
|
||||||
this.saving = false;
|
this.saving = false;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -153,13 +153,13 @@ export default {
|
||||||
},
|
},
|
||||||
cancel() {
|
cancel() {
|
||||||
this.saving = false; // 取消时重置状态
|
this.saving = false; // 取消时重置状态
|
||||||
|
this.dialogKey = Date.now();
|
||||||
this.$emit('cancel');
|
this.$emit('cancel');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
visible(newVal) {
|
visible(newVal) {
|
||||||
if (newVal) {
|
if (newVal) {
|
||||||
this.dialogKey = Date.now();
|
|
||||||
api.agent.getRecentlyFiftyByAgentId(this.agentId, ((data) => {
|
api.agent.getRecentlyFiftyByAgentId(this.agentId, ((data) => {
|
||||||
this.valueTypeOptions = data.data.data.map(item => ({
|
this.valueTypeOptions = data.data.data.map(item => ({
|
||||||
...item
|
...item
|
||||||
|
|
|
||||||
|
|
@ -663,6 +663,7 @@ export default {
|
||||||
'language.en': 'English',
|
'language.en': 'English',
|
||||||
'language.de': 'Deutsch',
|
'language.de': 'Deutsch',
|
||||||
'language.vi': 'Tiếng Việt',
|
'language.vi': 'Tiếng Việt',
|
||||||
|
'language.ptBR': 'Português (Brasil)',
|
||||||
|
|
||||||
// Home page text
|
// Home page text
|
||||||
'home.addAgent': 'Agent hinzufügen',
|
'home.addAgent': 'Agent hinzufügen',
|
||||||
|
|
@ -836,6 +837,7 @@ export default {
|
||||||
'modelConfig.unknown': 'Unbekannt',
|
'modelConfig.unknown': 'Unbekannt',
|
||||||
'modelConfig.isEnabled': 'Aktiviert',
|
'modelConfig.isEnabled': 'Aktiviert',
|
||||||
'modelConfig.isDefault': 'Standard',
|
'modelConfig.isDefault': 'Standard',
|
||||||
|
'modelConfig.defaultModelCannotDisable': 'Standardmodellkonfiguration kann nicht deaktiviert werden',
|
||||||
'modelConfig.action': 'Aktion',
|
'modelConfig.action': 'Aktion',
|
||||||
'modelConfig.voiceManagement': 'Stimmverwaltung',
|
'modelConfig.voiceManagement': 'Stimmverwaltung',
|
||||||
'modelConfig.edit': 'Bearbeiten',
|
'modelConfig.edit': 'Bearbeiten',
|
||||||
|
|
|
||||||
|
|
@ -663,6 +663,7 @@ export default {
|
||||||
'language.en': 'English',
|
'language.en': 'English',
|
||||||
'language.de': 'Deutsch',
|
'language.de': 'Deutsch',
|
||||||
'language.vi': 'Tiếng Việt',
|
'language.vi': 'Tiếng Việt',
|
||||||
|
'language.ptBR': 'Português (Brasil)',
|
||||||
|
|
||||||
// Home page text
|
// Home page text
|
||||||
'home.addAgent': 'Add Agent',
|
'home.addAgent': 'Add Agent',
|
||||||
|
|
@ -836,6 +837,7 @@ export default {
|
||||||
'modelConfig.unknown': 'Unknown',
|
'modelConfig.unknown': 'Unknown',
|
||||||
'modelConfig.isEnabled': 'Enabled',
|
'modelConfig.isEnabled': 'Enabled',
|
||||||
'modelConfig.isDefault': 'Default',
|
'modelConfig.isDefault': 'Default',
|
||||||
|
'modelConfig.defaultModelCannotDisable': 'Default model configuration cannot be disabled',
|
||||||
'modelConfig.action': 'Action',
|
'modelConfig.action': 'Action',
|
||||||
'modelConfig.voiceManagement': 'Voice Management',
|
'modelConfig.voiceManagement': 'Voice Management',
|
||||||
'modelConfig.edit': 'Edit',
|
'modelConfig.edit': 'Edit',
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import zhTW from './zh_TW';
|
||||||
import en from './en';
|
import en from './en';
|
||||||
import de from './de';
|
import de from './de';
|
||||||
import vi from './vi';
|
import vi from './vi';
|
||||||
|
import ptBR from './pt_BR';
|
||||||
|
|
||||||
Vue.use(VueI18n);
|
Vue.use(VueI18n);
|
||||||
|
|
||||||
|
|
@ -27,6 +28,9 @@ const getDefaultLanguage = () => {
|
||||||
if (browserLang.indexOf('vi') === 0) {
|
if (browserLang.indexOf('vi') === 0) {
|
||||||
return 'vi';
|
return 'vi';
|
||||||
}
|
}
|
||||||
|
if (browserLang === 'pt-BR' || browserLang === 'pt') {
|
||||||
|
return 'pt_BR';
|
||||||
|
}
|
||||||
return 'en';
|
return 'en';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -38,7 +42,8 @@ const i18n = new VueI18n({
|
||||||
'zh_TW': zhTW,
|
'zh_TW': zhTW,
|
||||||
'en': en,
|
'en': en,
|
||||||
'de': de,
|
'de': de,
|
||||||
'vi': vi
|
'vi': vi,
|
||||||
|
'pt_BR': ptBR
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
1334
main/manager-web/src/i18n/pt_BR.js
Normal file
1334
main/manager-web/src/i18n/pt_BR.js
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -663,6 +663,7 @@ export default {
|
||||||
'language.en': 'English',
|
'language.en': 'English',
|
||||||
'language.de': 'Deutsch',
|
'language.de': 'Deutsch',
|
||||||
'language.vi': 'Tiếng Việt',
|
'language.vi': 'Tiếng Việt',
|
||||||
|
'language.ptBR': 'Português (Brasil)',
|
||||||
|
|
||||||
// Home page text
|
// Home page text
|
||||||
'home.addAgent': 'Thêm tác nhân',
|
'home.addAgent': 'Thêm tác nhân',
|
||||||
|
|
@ -836,6 +837,7 @@ export default {
|
||||||
'modelConfig.unknown': 'Không xác định',
|
'modelConfig.unknown': 'Không xác định',
|
||||||
'modelConfig.isEnabled': 'Đã bật',
|
'modelConfig.isEnabled': 'Đã bật',
|
||||||
'modelConfig.isDefault': 'Mặc định',
|
'modelConfig.isDefault': 'Mặc định',
|
||||||
|
'modelConfig.defaultModelCannotDisable': 'Cấu hình mô hình mặc định không thể tắt',
|
||||||
'modelConfig.action': 'Hành động',
|
'modelConfig.action': 'Hành động',
|
||||||
'modelConfig.voiceManagement': 'Quản lý giọng nói',
|
'modelConfig.voiceManagement': 'Quản lý giọng nói',
|
||||||
'modelConfig.edit': 'Chỉnh sửa',
|
'modelConfig.edit': 'Chỉnh sửa',
|
||||||
|
|
|
||||||
|
|
@ -663,6 +663,7 @@ export default {
|
||||||
'language.en': 'English',
|
'language.en': 'English',
|
||||||
'language.de': 'Deutsch',
|
'language.de': 'Deutsch',
|
||||||
'language.vi': 'Tiếng Việt',
|
'language.vi': 'Tiếng Việt',
|
||||||
|
'language.ptBR': 'Português (Brasil)',
|
||||||
|
|
||||||
// 首页文本
|
// 首页文本
|
||||||
'home.addAgent': '添加智能体',
|
'home.addAgent': '添加智能体',
|
||||||
|
|
@ -836,6 +837,7 @@ export default {
|
||||||
'modelConfig.unknown': '未知',
|
'modelConfig.unknown': '未知',
|
||||||
'modelConfig.isEnabled': '是否启用',
|
'modelConfig.isEnabled': '是否启用',
|
||||||
'modelConfig.isDefault': '是否默认',
|
'modelConfig.isDefault': '是否默认',
|
||||||
|
'modelConfig.defaultModelCannotDisable': '默认模型配置不允许关闭',
|
||||||
'modelConfig.action': '操作',
|
'modelConfig.action': '操作',
|
||||||
'modelConfig.voiceManagement': '音色管理',
|
'modelConfig.voiceManagement': '音色管理',
|
||||||
'modelConfig.edit': '修改',
|
'modelConfig.edit': '修改',
|
||||||
|
|
|
||||||
|
|
@ -663,6 +663,7 @@ export default {
|
||||||
'language.en': 'English',
|
'language.en': 'English',
|
||||||
'language.de': 'Deutsch',
|
'language.de': 'Deutsch',
|
||||||
'language.vi': 'Tiếng Việt',
|
'language.vi': 'Tiếng Việt',
|
||||||
|
'language.ptBR': 'Português (Brasil)',
|
||||||
|
|
||||||
// 首頁文本
|
// 首頁文本
|
||||||
'home.addAgent': '添加智能體',
|
'home.addAgent': '添加智能體',
|
||||||
|
|
@ -836,6 +837,7 @@ export default {
|
||||||
'modelConfig.unknown': '未知',
|
'modelConfig.unknown': '未知',
|
||||||
'modelConfig.isEnabled': '是否啟用',
|
'modelConfig.isEnabled': '是否啟用',
|
||||||
'modelConfig.isDefault': '是否默認',
|
'modelConfig.isDefault': '是否默認',
|
||||||
|
'modelConfig.defaultModelCannotDisable': '預設模型配置不允許關閉',
|
||||||
'modelConfig.action': '操作',
|
'modelConfig.action': '操作',
|
||||||
'modelConfig.voiceManagement': '音色管理',
|
'modelConfig.voiceManagement': '音色管理',
|
||||||
'modelConfig.edit': '修改',
|
'modelConfig.edit': '修改',
|
||||||
|
|
|
||||||
|
|
@ -97,7 +97,23 @@
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
<el-table-column :label="$t('modelConfig.isEnabled')" align="center">
|
<el-table-column :label="$t('modelConfig.isEnabled')" align="center">
|
||||||
<template slot-scope="scope">
|
<template slot-scope="scope">
|
||||||
|
<el-tooltip
|
||||||
|
v-if="scope.row.isDefault === 1 && scope.row.isEnabled === 1"
|
||||||
|
:content="$t('modelConfig.defaultModelCannotDisable')"
|
||||||
|
placement="top"
|
||||||
|
effect="light"
|
||||||
|
>
|
||||||
|
<el-switch
|
||||||
|
v-model="scope.row.isEnabled"
|
||||||
|
class="custom-switch"
|
||||||
|
:active-value="1"
|
||||||
|
:inactive-value="0"
|
||||||
|
disabled
|
||||||
|
@change="handleStatusChange(scope.row)"
|
||||||
|
/>
|
||||||
|
</el-tooltip>
|
||||||
<el-switch
|
<el-switch
|
||||||
|
v-else
|
||||||
v-model="scope.row.isEnabled"
|
v-model="scope.row.isEnabled"
|
||||||
class="custom-switch"
|
class="custom-switch"
|
||||||
:active-value="1"
|
:active-value="1"
|
||||||
|
|
|
||||||
|
|
@ -55,6 +55,9 @@
|
||||||
<el-dropdown-item @click.native="changeLanguage('vi')">
|
<el-dropdown-item @click.native="changeLanguage('vi')">
|
||||||
{{ $t("language.vi") }}
|
{{ $t("language.vi") }}
|
||||||
</el-dropdown-item>
|
</el-dropdown-item>
|
||||||
|
<el-dropdown-item @click.native="changeLanguage('pt_BR')">
|
||||||
|
{{ $t("language.ptBR") }}
|
||||||
|
</el-dropdown-item>
|
||||||
</el-dropdown-menu>
|
</el-dropdown-menu>
|
||||||
</el-dropdown>
|
</el-dropdown>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -188,6 +191,8 @@ export default {
|
||||||
return this.$t("language.de");
|
return this.$t("language.de");
|
||||||
case "vi":
|
case "vi":
|
||||||
return this.$t("language.vi");
|
return this.$t("language.vi");
|
||||||
|
case "pt_BR":
|
||||||
|
return this.$t("language.ptBR");
|
||||||
default:
|
default:
|
||||||
return this.$t("language.zhCN");
|
return this.$t("language.zhCN");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -137,6 +137,8 @@ export default {
|
||||||
return require("@/assets/xiaozhi-ai_de.png");
|
return require("@/assets/xiaozhi-ai_de.png");
|
||||||
case "vi":
|
case "vi":
|
||||||
return require("@/assets/xiaozhi-ai_vi.png");
|
return require("@/assets/xiaozhi-ai_vi.png");
|
||||||
|
case "pt_BR":
|
||||||
|
return require("@/assets/xiaozhi-ai_en.png");
|
||||||
default:
|
default:
|
||||||
return require("@/assets/xiaozhi-ai.png");
|
return require("@/assets/xiaozhi-ai.png");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,8 @@
|
||||||
"permissions": {
|
"permissions": {
|
||||||
"allow": [
|
"allow": [
|
||||||
"Bash(tree:*)",
|
"Bash(tree:*)",
|
||||||
"Bash(find:*)"
|
"Bash(find:*)",
|
||||||
|
"Bash(python3:*)"
|
||||||
],
|
],
|
||||||
"deny": [],
|
"deny": [],
|
||||||
"ask": []
|
"ask": []
|
||||||
|
|
|
||||||
|
|
@ -203,6 +203,9 @@ prompt: |
|
||||||
# 默认系统提示词模板文件
|
# 默认系统提示词模板文件
|
||||||
prompt_template: agent-base-prompt.txt
|
prompt_template: agent-base-prompt.txt
|
||||||
|
|
||||||
|
# 系统错误时的回复
|
||||||
|
system_error_response: "主人,小智现在有点忙,我们稍后再试吧。"
|
||||||
|
|
||||||
# 结束语prompt
|
# 结束语prompt
|
||||||
end_prompt:
|
end_prompt:
|
||||||
enable: true # 是否开启结束语
|
enable: true # 是否开启结束语
|
||||||
|
|
@ -276,6 +279,54 @@ Memory:
|
||||||
# https://app.mem0.ai/dashboard/api-keys
|
# https://app.mem0.ai/dashboard/api-keys
|
||||||
# 每月有1000次免费调用
|
# 每月有1000次免费调用
|
||||||
api_key: 你的mem0ai api key
|
api_key: 你的mem0ai api key
|
||||||
|
powermem:
|
||||||
|
# PowerMem是OceanBase开源的agent记忆组件,通过本地LLM进行记忆总结
|
||||||
|
# 费用说明:PowerMem本身免费,实际费用取决于所选LLM和数据库
|
||||||
|
# - 使用sqlite + 免费LLM(如glm-4-flash) = 完全免费
|
||||||
|
# - 使用云端LLM或云端数据库 = 按对应服务收费
|
||||||
|
# GitHub: https://github.com/oceanbase/powermem
|
||||||
|
# 官网: https://www.powermem.ai/
|
||||||
|
# 使用示例: https://github.com/oceanbase/powermem/tree/main/examples
|
||||||
|
type: powermem
|
||||||
|
# 是否启用用户画像功能
|
||||||
|
# - false: 使用普通记忆模式(AsyncMemory)
|
||||||
|
# - true: 使用用户画像模式(UserMemory),自动提取用户信息
|
||||||
|
# 用户画像功能支持: oceanbase、seekdb、sqlite (powermem 0.3.0+)
|
||||||
|
enable_user_profile: true
|
||||||
|
# ========== LLM 配置 ==========
|
||||||
|
# 通义千问: https://bailian.console.aliyun.com/?apiKey=1#/api-key
|
||||||
|
# 智谱AI(免费): https://bigmodel.cn/usercenter/proj-mgmt/apikeys
|
||||||
|
llm:
|
||||||
|
provider: openai # 可选: qwen, openai, zhipu 等
|
||||||
|
config:
|
||||||
|
api_key: 你的LLM API密钥
|
||||||
|
model: qwen-plus
|
||||||
|
# openai_base_url: https://api.openai.com/v1 # 可选,自定义服务地址
|
||||||
|
# ========== Embedding 配置 ==========
|
||||||
|
embedder:
|
||||||
|
provider: openai # 可选: qwen, openai 等
|
||||||
|
config:
|
||||||
|
api_key: 你的嵌入模型API密钥
|
||||||
|
model: text-embedding-v4
|
||||||
|
openai_base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
|
||||||
|
# embedding_dims: 1024 # 向量维度,非1536时需配置
|
||||||
|
|
||||||
|
# ========== Database 配置 ==========
|
||||||
|
# oceanbase(推荐,最佳性能), seekdb(推荐,AI应用存储一体), postgres, sqlite(轻量备选)
|
||||||
|
# 用户画像功能支持: oceanbase、seekdb、sqlite
|
||||||
|
vector_store:
|
||||||
|
provider: sqlite
|
||||||
|
config: {} # SQLite 无需额外配置
|
||||||
|
# OceanBase 配置示例:
|
||||||
|
# provider: oceanbase
|
||||||
|
# config:
|
||||||
|
# host: 127.0.0.1
|
||||||
|
# port: 2881
|
||||||
|
# user: root@test
|
||||||
|
# password: your_password
|
||||||
|
# db_name: powermem
|
||||||
|
# collection_name: memories # 默认表名,如创建维度错误请删除此表或更改名称
|
||||||
|
# embedding_model_dims: 1024 # 嵌入向量维度,注意跟使用模型适配,以智普为例:embedding-2的维度是1024,embedding-3的维度是2048
|
||||||
nomem:
|
nomem:
|
||||||
# 不想使用记忆功能,可以使用nomem
|
# 不想使用记忆功能,可以使用nomem
|
||||||
type: nomem
|
type: nomem
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ from config.config_loader import load_config
|
||||||
from config.settings import check_config_file
|
from config.settings import check_config_file
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
SERVER_VERSION = "0.8.11"
|
SERVER_VERSION = "0.9.1"
|
||||||
_logger_initialized = False
|
_logger_initialized = False
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,15 @@ class VisionHandler(BaseHandler):
|
||||||
|
|
||||||
def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]:
|
def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]:
|
||||||
"""验证认证token"""
|
"""验证认证token"""
|
||||||
|
# 测试模式:允许特定测试令牌或跳过验证
|
||||||
auth_header = request.headers.get("Authorization", "")
|
auth_header = request.headers.get("Authorization", "")
|
||||||
|
client_id = request.headers.get("Client-Id", "")
|
||||||
|
|
||||||
|
# 允许测试客户端跳过认证
|
||||||
|
if client_id == "web_test_client":
|
||||||
|
device_id = request.headers.get("Device-Id", "test_device")
|
||||||
|
return True, device_id
|
||||||
|
|
||||||
if not auth_header.startswith("Bearer "):
|
if not auth_header.startswith("Bearer "):
|
||||||
return False, None
|
return False, None
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -40,8 +40,10 @@ from config.logger import setup_logging, build_module_string, create_connection_
|
||||||
from config.manage_api_client import DeviceNotFoundException, DeviceBindException
|
from config.manage_api_client import DeviceNotFoundException, DeviceBindException
|
||||||
from core.utils.prompt_manager import PromptManager
|
from core.utils.prompt_manager import PromptManager
|
||||||
from core.utils.voiceprint_provider import VoiceprintProvider
|
from core.utils.voiceprint_provider import VoiceprintProvider
|
||||||
|
from core.utils.util import get_system_error_response
|
||||||
from core.utils import textUtils
|
from core.utils import textUtils
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
auto_import_modules("plugins_func.functions")
|
auto_import_modules("plugins_func.functions")
|
||||||
|
|
@ -76,7 +78,7 @@ class ConnectionHandler:
|
||||||
|
|
||||||
self.read_config_from_api = self.config.get("read_config_from_api", False)
|
self.read_config_from_api = self.config.get("read_config_from_api", False)
|
||||||
|
|
||||||
self.websocket = None
|
self.websocket: websockets.ServerConnection | None = None
|
||||||
self.headers = None
|
self.headers = None
|
||||||
self.device_id = None
|
self.device_id = None
|
||||||
self.client_ip = None
|
self.client_ip = None
|
||||||
|
|
@ -135,7 +137,6 @@ class ConnectionHandler:
|
||||||
self.current_language_tag = None # 存储当前ASR识别的语言标签
|
self.current_language_tag = None # 存储当前ASR识别的语言标签
|
||||||
|
|
||||||
# llm相关变量
|
# llm相关变量
|
||||||
self.llm_finish_task = True
|
|
||||||
self.dialogue = Dialogue()
|
self.dialogue = Dialogue()
|
||||||
|
|
||||||
# tts相关变量
|
# tts相关变量
|
||||||
|
|
@ -168,7 +169,7 @@ class ConnectionHandler:
|
||||||
# 初始化提示词管理器
|
# 初始化提示词管理器
|
||||||
self.prompt_manager = PromptManager(self.config, self.logger)
|
self.prompt_manager = PromptManager(self.config, self.logger)
|
||||||
|
|
||||||
async def handle_connection(self, ws):
|
async def handle_connection(self, ws: websockets.ServerConnection):
|
||||||
try:
|
try:
|
||||||
# 获取运行中的事件循环(必须在异步上下文中)
|
# 获取运行中的事件循环(必须在异步上下文中)
|
||||||
self.loop = asyncio.get_running_loop()
|
self.loop = asyncio.get_running_loop()
|
||||||
|
|
@ -799,7 +800,6 @@ class ConnectionHandler:
|
||||||
|
|
||||||
# 为最顶层时新建会话ID和发送FIRST请求
|
# 为最顶层时新建会话ID和发送FIRST请求
|
||||||
if depth == 0:
|
if depth == 0:
|
||||||
self.llm_finish_task = False
|
|
||||||
self.sentence_id = str(uuid.uuid4().hex)
|
self.sentence_id = str(uuid.uuid4().hex)
|
||||||
self.dialogue.put(Message(role="user", content=query))
|
self.dialogue.put(Message(role="user", content=query))
|
||||||
self.tts.tts_text_queue.put(
|
self.tts.tts_text_queue.put(
|
||||||
|
|
@ -841,7 +841,8 @@ class ConnectionHandler:
|
||||||
try:
|
try:
|
||||||
# 使用带记忆的对话
|
# 使用带记忆的对话
|
||||||
memory_str = None
|
memory_str = None
|
||||||
if self.memory is not None:
|
# 仅当query非空(代表用户询问)时查询记忆
|
||||||
|
if self.memory is not None and query:
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
self.memory.query_memory(query), self.loop
|
self.memory.query_memory(query), self.loop
|
||||||
)
|
)
|
||||||
|
|
@ -874,46 +875,66 @@ class ConnectionHandler:
|
||||||
content_arguments = ""
|
content_arguments = ""
|
||||||
self.client_abort = False
|
self.client_abort = False
|
||||||
emotion_flag = True
|
emotion_flag = True
|
||||||
for response in llm_responses:
|
try:
|
||||||
if self.client_abort:
|
for response in llm_responses:
|
||||||
break
|
if self.client_abort:
|
||||||
if self.intent_type == "function_call" and functions is not None:
|
break
|
||||||
content, tools_call = response
|
if self.intent_type == "function_call" and functions is not None:
|
||||||
if "content" in response:
|
content, tools_call = response
|
||||||
content = response["content"]
|
if "content" in response:
|
||||||
tools_call = None
|
content = response["content"]
|
||||||
if content is not None and len(content) > 0:
|
tools_call = None
|
||||||
content_arguments += content
|
if content is not None and len(content) > 0:
|
||||||
|
content_arguments += content
|
||||||
|
|
||||||
if not tool_call_flag and content_arguments.startswith("<tool_call>"):
|
if not tool_call_flag and content_arguments.startswith("<tool_call>"):
|
||||||
# print("content_arguments", content_arguments)
|
# print("content_arguments", content_arguments)
|
||||||
tool_call_flag = True
|
tool_call_flag = True
|
||||||
|
|
||||||
if tools_call is not None and len(tools_call) > 0:
|
if tools_call is not None and len(tools_call) > 0:
|
||||||
tool_call_flag = True
|
tool_call_flag = True
|
||||||
self._merge_tool_calls(tool_calls_list, tools_call)
|
self._merge_tool_calls(tool_calls_list, tools_call)
|
||||||
else:
|
else:
|
||||||
content = response
|
content = response
|
||||||
|
|
||||||
# 在llm回复中获取情绪表情,一轮对话只在开头获取一次
|
# 在llm回复中获取情绪表情,一轮对话只在开头获取一次
|
||||||
if emotion_flag and content is not None and content.strip():
|
if emotion_flag and content is not None and content.strip():
|
||||||
asyncio.run_coroutine_threadsafe(
|
asyncio.run_coroutine_threadsafe(
|
||||||
textUtils.get_emotion(self, content),
|
textUtils.get_emotion(self, content),
|
||||||
self.loop,
|
self.loop,
|
||||||
)
|
|
||||||
emotion_flag = False
|
|
||||||
|
|
||||||
if content is not None and len(content) > 0:
|
|
||||||
if not tool_call_flag:
|
|
||||||
response_message.append(content)
|
|
||||||
self.tts.tts_text_queue.put(
|
|
||||||
TTSMessageDTO(
|
|
||||||
sentence_id=self.sentence_id,
|
|
||||||
sentence_type=SentenceType.MIDDLE,
|
|
||||||
content_type=ContentType.TEXT,
|
|
||||||
content_detail=content,
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
emotion_flag = False
|
||||||
|
|
||||||
|
if content is not None and len(content) > 0:
|
||||||
|
if not tool_call_flag:
|
||||||
|
response_message.append(content)
|
||||||
|
self.tts.tts_text_queue.put(
|
||||||
|
TTSMessageDTO(
|
||||||
|
sentence_id=self.sentence_id,
|
||||||
|
sentence_type=SentenceType.MIDDLE,
|
||||||
|
content_type=ContentType.TEXT,
|
||||||
|
content_detail=content,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"LLM stream processing error: {e}")
|
||||||
|
self.tts.tts_text_queue.put(
|
||||||
|
TTSMessageDTO(
|
||||||
|
sentence_id=self.sentence_id,
|
||||||
|
sentence_type=SentenceType.MIDDLE,
|
||||||
|
content_type=ContentType.TEXT,
|
||||||
|
content_detail=get_system_error_response(self.config),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if depth == 0:
|
||||||
|
self.tts.tts_text_queue.put(
|
||||||
|
TTSMessageDTO(
|
||||||
|
sentence_id=self.sentence_id,
|
||||||
|
sentence_type=SentenceType.LAST,
|
||||||
|
content_type=ContentType.ACTION,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return
|
||||||
# 处理function call
|
# 处理function call
|
||||||
if tool_call_flag:
|
if tool_call_flag:
|
||||||
bHasError = False
|
bHasError = False
|
||||||
|
|
@ -994,7 +1015,6 @@ class ConnectionHandler:
|
||||||
content_type=ContentType.ACTION,
|
content_type=ContentType.ACTION,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
self.llm_finish_task = True
|
|
||||||
# 使用lambda延迟计算,只有在DEBUG级别时才执行get_llm_dialogue()
|
# 使用lambda延迟计算,只有在DEBUG级别时才执行get_llm_dialogue()
|
||||||
self.logger.bind(tag=TAG).debug(
|
self.logger.bind(tag=TAG).debug(
|
||||||
lambda: json.dumps(
|
lambda: json.dumps(
|
||||||
|
|
@ -1099,6 +1119,14 @@ class ConnectionHandler:
|
||||||
async def close(self, ws=None):
|
async def close(self, ws=None):
|
||||||
"""资源清理方法"""
|
"""资源清理方法"""
|
||||||
try:
|
try:
|
||||||
|
# 清理 VAD 连接资源
|
||||||
|
if (
|
||||||
|
hasattr(self, "vad")
|
||||||
|
and self.vad
|
||||||
|
and hasattr(self.vad, "release_conn_resources")
|
||||||
|
):
|
||||||
|
self.vad.release_conn_resources(self)
|
||||||
|
|
||||||
# 清理音频缓冲区
|
# 清理音频缓冲区
|
||||||
if hasattr(self, "audio_buffer"):
|
if hasattr(self, "audio_buffer"):
|
||||||
self.audio_buffer.clear()
|
self.audio_buffer.clear()
|
||||||
|
|
@ -1166,6 +1194,8 @@ class ConnectionHandler:
|
||||||
|
|
||||||
if self.tts:
|
if self.tts:
|
||||||
await self.tts.close()
|
await self.tts.close()
|
||||||
|
if self.asr:
|
||||||
|
await self.asr.close()
|
||||||
|
|
||||||
# 最后关闭线程池(避免阻塞)
|
# 最后关闭线程池(避免阻塞)
|
||||||
if self.executor:
|
if self.executor:
|
||||||
|
|
@ -1214,11 +1244,21 @@ class ConnectionHandler:
|
||||||
f"清理结束: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
|
f"清理结束: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
|
||||||
)
|
)
|
||||||
|
|
||||||
def reset_vad_states(self):
|
def reset_audio_states(self):
|
||||||
self.client_audio_buffer = bytearray()
|
"""
|
||||||
|
重置所有音频相关状态(VAD + ASR)
|
||||||
|
"""
|
||||||
|
# Reset VAD states
|
||||||
|
self.client_audio_buffer.clear()
|
||||||
self.client_have_voice = False
|
self.client_have_voice = False
|
||||||
self.client_voice_stop = False
|
self.client_voice_stop = False
|
||||||
self.logger.bind(tag=TAG).debug("VAD states reset.")
|
self.client_voice_window.clear()
|
||||||
|
self.last_is_voice = False
|
||||||
|
|
||||||
|
# Clear ASR buffers
|
||||||
|
self.asr_audio.clear()
|
||||||
|
|
||||||
|
self.logger.bind(tag=TAG).debug("All audio states reset.")
|
||||||
|
|
||||||
def chat_and_close(self, text):
|
def chat_and_close(self, text):
|
||||||
"""Chat with the user and then close the connection"""
|
"""Chat with the user and then close the connection"""
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,12 @@
|
||||||
import json
|
import json
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
async def handleAbortMessage(conn):
|
async def handleAbortMessage(conn: "ConnectionHandler"):
|
||||||
conn.logger.bind(tag=TAG).info("Abort message received")
|
conn.logger.bind(tag=TAG).info("Abort message received")
|
||||||
# 设置成打断状态,会自动打断llm、tts任务
|
# 设置成打断状态,会自动打断llm、tts任务
|
||||||
conn.client_abort = True
|
conn.client_abort = True
|
||||||
|
|
|
||||||
|
|
@ -3,16 +3,17 @@ import json
|
||||||
import uuid
|
import uuid
|
||||||
import random
|
import random
|
||||||
import asyncio
|
import asyncio
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from core.utils.dialogue import Message
|
from core.utils.dialogue import Message
|
||||||
from core.utils.util import audio_to_data
|
from core.utils.util import audio_to_data
|
||||||
from core.providers.tts.dto.dto import SentenceType
|
from core.providers.tts.dto.dto import SentenceType
|
||||||
from core.utils.wakeup_word import WakeupWordsConfig
|
from core.utils.wakeup_word import WakeupWordsConfig
|
||||||
from core.handle.sendAudioHandle import sendAudioMessage, send_tts_message
|
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.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes
|
||||||
from core.providers.tools.device_mcp import (
|
from core.providers.tools.device_mcp import MCPClient, send_mcp_initialize_message
|
||||||
MCPClient,
|
|
||||||
send_mcp_initialize_message
|
|
||||||
)
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
@ -38,7 +39,7 @@ wakeup_words_config = WakeupWordsConfig()
|
||||||
_wakeup_response_lock = asyncio.Lock()
|
_wakeup_response_lock = asyncio.Lock()
|
||||||
|
|
||||||
|
|
||||||
async def handleHelloMessage(conn, msg_json):
|
async def handleHelloMessage(conn: "ConnectionHandler", msg_json):
|
||||||
"""处理hello消息"""
|
"""处理hello消息"""
|
||||||
audio_params = msg_json.get("audio_params")
|
audio_params = msg_json.get("audio_params")
|
||||||
if audio_params:
|
if audio_params:
|
||||||
|
|
@ -59,7 +60,7 @@ async def handleHelloMessage(conn, msg_json):
|
||||||
await conn.websocket.send(json.dumps(conn.welcome_msg))
|
await conn.websocket.send(json.dumps(conn.welcome_msg))
|
||||||
|
|
||||||
|
|
||||||
async def checkWakeupWords(conn, text):
|
async def checkWakeupWords(conn: "ConnectionHandler", text):
|
||||||
enable_wakeup_words_response_cache = conn.config[
|
enable_wakeup_words_response_cache = conn.config[
|
||||||
"enable_wakeup_words_response_cache"
|
"enable_wakeup_words_response_cache"
|
||||||
]
|
]
|
||||||
|
|
@ -120,7 +121,7 @@ async def checkWakeupWords(conn, text):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
async def wakeupWordsResponse(conn):
|
async def wakeupWordsResponse(conn: "ConnectionHandler"):
|
||||||
if not conn.tts:
|
if not conn.tts:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,10 @@
|
||||||
import json
|
import json
|
||||||
import uuid
|
import uuid
|
||||||
import asyncio
|
import asyncio
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from core.utils.dialogue import Message
|
from core.utils.dialogue import Message
|
||||||
from core.providers.tts.dto.dto import ContentType
|
from core.providers.tts.dto.dto import ContentType
|
||||||
from core.handle.helloHandle import checkWakeupWords
|
from core.handle.helloHandle import checkWakeupWords
|
||||||
|
|
@ -12,10 +16,10 @@ from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
async def handle_user_intent(conn, text):
|
async def handle_user_intent(conn: "ConnectionHandler", text):
|
||||||
# 预处理输入文本,处理可能的JSON格式
|
# 预处理输入文本,处理可能的JSON格式
|
||||||
try:
|
try:
|
||||||
if text.strip().startswith('{') and text.strip().endswith('}'):
|
if text.strip().startswith("{") and text.strip().endswith("}"):
|
||||||
parsed_data = json.loads(text)
|
parsed_data = json.loads(text)
|
||||||
if isinstance(parsed_data, dict) and "content" in parsed_data:
|
if isinstance(parsed_data, dict) and "content" in parsed_data:
|
||||||
text = parsed_data["content"] # 提取content用于意图分析
|
text = parsed_data["content"] # 提取content用于意图分析
|
||||||
|
|
@ -45,7 +49,7 @@ async def handle_user_intent(conn, text):
|
||||||
return await process_intent_result(conn, intent_result, text)
|
return await process_intent_result(conn, intent_result, text)
|
||||||
|
|
||||||
|
|
||||||
async def check_direct_exit(conn, text):
|
async def check_direct_exit(conn: "ConnectionHandler", text):
|
||||||
"""检查是否有明确的退出命令"""
|
"""检查是否有明确的退出命令"""
|
||||||
_, text = remove_punctuation_and_length(text)
|
_, text = remove_punctuation_and_length(text)
|
||||||
cmd_exit = conn.cmd_exit
|
cmd_exit = conn.cmd_exit
|
||||||
|
|
@ -58,7 +62,7 @@ async def check_direct_exit(conn, text):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
async def analyze_intent_with_llm(conn, text):
|
async def analyze_intent_with_llm(conn: "ConnectionHandler", text):
|
||||||
"""使用LLM分析用户意图"""
|
"""使用LLM分析用户意图"""
|
||||||
if not hasattr(conn, "intent") or not conn.intent:
|
if not hasattr(conn, "intent") or not conn.intent:
|
||||||
conn.logger.bind(tag=TAG).warning("意图识别服务未初始化")
|
conn.logger.bind(tag=TAG).warning("意图识别服务未初始化")
|
||||||
|
|
@ -75,7 +79,9 @@ async def analyze_intent_with_llm(conn, text):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
async def process_intent_result(conn, intent_result, original_text):
|
async def process_intent_result(
|
||||||
|
conn: "ConnectionHandler", intent_result, original_text
|
||||||
|
):
|
||||||
"""处理意图识别结果"""
|
"""处理意图识别结果"""
|
||||||
try:
|
try:
|
||||||
# 尝试将结果解析为JSON
|
# 尝试将结果解析为JSON
|
||||||
|
|
@ -94,24 +100,26 @@ async def process_intent_result(conn, intent_result, original_text):
|
||||||
if function_name == "result_for_context":
|
if function_name == "result_for_context":
|
||||||
await send_stt_message(conn, original_text)
|
await send_stt_message(conn, original_text)
|
||||||
conn.client_abort = False
|
conn.client_abort = False
|
||||||
|
|
||||||
def process_context_result():
|
def process_context_result():
|
||||||
conn.dialogue.put(Message(role="user", content=original_text))
|
conn.dialogue.put(Message(role="user", content=original_text))
|
||||||
|
|
||||||
from core.utils.current_time import get_current_time_info
|
from core.utils.current_time import get_current_time_info
|
||||||
|
|
||||||
current_time, today_date, today_weekday, lunar_date = get_current_time_info()
|
current_time, today_date, today_weekday, lunar_date = (
|
||||||
|
get_current_time_info()
|
||||||
|
)
|
||||||
|
|
||||||
# 构建带上下文的基础提示
|
# 构建带上下文的基础提示
|
||||||
context_prompt = f"""当前时间:{current_time}
|
context_prompt = f"""当前时间:{current_time}
|
||||||
今天日期:{today_date} ({today_weekday})
|
今天日期:{today_date} ({today_weekday})
|
||||||
今天农历:{lunar_date}
|
今天农历:{lunar_date}
|
||||||
|
|
||||||
请根据以上信息回答用户的问题:{original_text}"""
|
请根据以上信息回答用户的问题:{original_text}"""
|
||||||
|
|
||||||
response = conn.intent.replyResult(context_prompt, original_text)
|
response = conn.intent.replyResult(context_prompt, original_text)
|
||||||
speak_txt(conn, response)
|
speak_txt(conn, response)
|
||||||
|
|
||||||
conn.executor.submit(process_context_result)
|
conn.executor.submit(process_context_result)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
@ -188,7 +196,7 @@ async def process_intent_result(conn, intent_result, original_text):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def speak_txt(conn, text):
|
def speak_txt(conn: "ConnectionHandler", text):
|
||||||
# 记录文本
|
# 记录文本
|
||||||
conn.tts_MessageText = text
|
conn.tts_MessageText = text
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,10 @@
|
||||||
import time
|
import time
|
||||||
import json
|
import json
|
||||||
import asyncio
|
import asyncio
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from core.utils.util import audio_to_data
|
from core.utils.util import audio_to_data
|
||||||
from core.handle.abortHandle import handleAbortMessage
|
from core.handle.abortHandle import handleAbortMessage
|
||||||
from core.handle.intentHandler import handle_user_intent
|
from core.handle.intentHandler import handle_user_intent
|
||||||
|
|
@ -10,14 +14,13 @@ from core.handle.sendAudioHandle import send_stt_message, SentenceType
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
async def handleAudioMessage(conn, audio):
|
async def handleAudioMessage(conn: "ConnectionHandler", audio):
|
||||||
# 当前片段是否有人说话
|
# 当前片段是否有人说话
|
||||||
have_voice = conn.vad.is_vad(conn, audio)
|
have_voice = conn.vad.is_vad(conn, audio)
|
||||||
# 如果设备刚刚被唤醒,短暂忽略VAD检测
|
# 如果设备刚刚被唤醒,短暂忽略VAD检测
|
||||||
if hasattr(conn, "just_woken_up") and conn.just_woken_up:
|
if hasattr(conn, "just_woken_up") and conn.just_woken_up:
|
||||||
have_voice = False
|
have_voice = False
|
||||||
# 设置一个短暂延迟后恢复VAD检测
|
# 设置一个短暂延迟后恢复VAD检测
|
||||||
conn.asr_audio.clear()
|
|
||||||
if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done():
|
if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done():
|
||||||
conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn))
|
conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn))
|
||||||
return
|
return
|
||||||
|
|
@ -31,13 +34,13 @@ async def handleAudioMessage(conn, audio):
|
||||||
await conn.asr.receive_audio(conn, audio, have_voice)
|
await conn.asr.receive_audio(conn, audio, have_voice)
|
||||||
|
|
||||||
|
|
||||||
async def resume_vad_detection(conn):
|
async def resume_vad_detection(conn: "ConnectionHandler"):
|
||||||
# 等待2秒后恢复VAD检测
|
# 等待2秒后恢复VAD检测
|
||||||
await asyncio.sleep(2)
|
await asyncio.sleep(2)
|
||||||
conn.just_woken_up = False
|
conn.just_woken_up = False
|
||||||
|
|
||||||
|
|
||||||
async def startToChat(conn, text):
|
async def startToChat(conn: "ConnectionHandler", text):
|
||||||
# 检查输入是否是JSON格式(包含说话人信息)
|
# 检查输入是否是JSON格式(包含说话人信息)
|
||||||
speaker_name = None
|
speaker_name = None
|
||||||
language_tag = None
|
language_tag = None
|
||||||
|
|
@ -97,7 +100,7 @@ async def startToChat(conn, text):
|
||||||
conn.executor.submit(conn.chat, actual_text)
|
conn.executor.submit(conn.chat, actual_text)
|
||||||
|
|
||||||
|
|
||||||
async def no_voice_close_connect(conn, have_voice):
|
async def no_voice_close_connect(conn: "ConnectionHandler", have_voice):
|
||||||
if have_voice:
|
if have_voice:
|
||||||
conn.last_activity_time = time.time() * 1000
|
conn.last_activity_time = time.time() * 1000
|
||||||
return
|
return
|
||||||
|
|
@ -124,7 +127,7 @@ async def no_voice_close_connect(conn, have_voice):
|
||||||
await startToChat(conn, prompt)
|
await startToChat(conn, prompt)
|
||||||
|
|
||||||
|
|
||||||
async def max_out_size(conn):
|
async def max_out_size(conn: "ConnectionHandler"):
|
||||||
# 播放超出最大输出字数的提示
|
# 播放超出最大输出字数的提示
|
||||||
conn.client_abort = False
|
conn.client_abort = False
|
||||||
text = "不好意思,我现在有点事情要忙,明天这个时候我们再聊,约好了哦!明天不见不散,拜拜!"
|
text = "不好意思,我现在有点事情要忙,明天这个时候我们再聊,约好了哦!明天不见不散,拜拜!"
|
||||||
|
|
@ -135,7 +138,7 @@ async def max_out_size(conn):
|
||||||
conn.close_after_chat = True
|
conn.close_after_chat = True
|
||||||
|
|
||||||
|
|
||||||
async def check_bind_device(conn):
|
async def check_bind_device(conn: "ConnectionHandler"):
|
||||||
if conn.bind_code:
|
if conn.bind_code:
|
||||||
# 确保bind_code是6位数字
|
# 确保bind_code是6位数字
|
||||||
if len(conn.bind_code) != 6:
|
if len(conn.bind_code) != 6:
|
||||||
|
|
|
||||||
|
|
@ -11,13 +11,17 @@ TTS上报功能已集成到ConnectionHandler类中。
|
||||||
|
|
||||||
import time
|
import time
|
||||||
import opuslib_next
|
import opuslib_next
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
from config.manage_api_client import report as manage_report
|
from config.manage_api_client import report as manage_report
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
async def report(conn, type, text, opus_data, report_time):
|
async def report(conn: "ConnectionHandler", type, text, opus_data, report_time):
|
||||||
"""执行聊天记录上报操作
|
"""执行聊天记录上报操作
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
|
|
@ -45,7 +49,7 @@ async def report(conn, type, text, opus_data, report_time):
|
||||||
conn.logger.bind(tag=TAG).error(f"聊天记录上报失败: {e}")
|
conn.logger.bind(tag=TAG).error(f"聊天记录上报失败: {e}")
|
||||||
|
|
||||||
|
|
||||||
def opus_to_wav(conn, opus_data):
|
def opus_to_wav(conn: "ConnectionHandler", opus_data):
|
||||||
"""将Opus数据转换为WAV格式的字节流
|
"""将Opus数据转换为WAV格式的字节流
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
|
|
@ -100,7 +104,7 @@ def opus_to_wav(conn, opus_data):
|
||||||
conn.logger.bind(tag=TAG).debug(f"释放decoder资源时出错: {e}")
|
conn.logger.bind(tag=TAG).debug(f"释放decoder资源时出错: {e}")
|
||||||
|
|
||||||
|
|
||||||
def enqueue_tts_report(conn, text, opus_data):
|
def enqueue_tts_report(conn: "ConnectionHandler", text, opus_data):
|
||||||
if not conn.read_config_from_api or conn.need_bind or not conn.report_tts_enable:
|
if not conn.read_config_from_api or conn.need_bind or not conn.report_tts_enable:
|
||||||
return
|
return
|
||||||
if conn.chat_history_conf == 0:
|
if conn.chat_history_conf == 0:
|
||||||
|
|
@ -128,7 +132,7 @@ def enqueue_tts_report(conn, text, opus_data):
|
||||||
conn.logger.bind(tag=TAG).error(f"加入TTS上报队列失败: {text}, {e}")
|
conn.logger.bind(tag=TAG).error(f"加入TTS上报队列失败: {text}, {e}")
|
||||||
|
|
||||||
|
|
||||||
def enqueue_asr_report(conn, text, opus_data):
|
def enqueue_asr_report(conn: "ConnectionHandler", text, opus_data):
|
||||||
if not conn.read_config_from_api or conn.need_bind or not conn.report_asr_enable:
|
if not conn.read_config_from_api or conn.need_bind or not conn.report_asr_enable:
|
||||||
return
|
return
|
||||||
if conn.chat_history_conf == 0:
|
if conn.chat_history_conf == 0:
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,10 @@
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
import asyncio
|
import asyncio
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from core.utils import textUtils
|
from core.utils import textUtils
|
||||||
from core.utils.util import audio_to_data
|
from core.utils.util import audio_to_data
|
||||||
from core.providers.tts.dto.dto import SentenceType
|
from core.providers.tts.dto.dto import SentenceType
|
||||||
|
|
@ -13,7 +17,7 @@ AUDIO_FRAME_DURATION = 60
|
||||||
PRE_BUFFER_COUNT = 5
|
PRE_BUFFER_COUNT = 5
|
||||||
|
|
||||||
|
|
||||||
async def sendAudioMessage(conn, sentenceType, audios, text):
|
async def sendAudioMessage(conn: "ConnectionHandler", sentenceType, audios, text):
|
||||||
if conn.tts.tts_audio_first_sentence:
|
if conn.tts.tts_audio_first_sentence:
|
||||||
conn.logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
|
conn.logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
|
||||||
conn.tts.tts_audio_first_sentence = False
|
conn.tts.tts_audio_first_sentence = False
|
||||||
|
|
@ -47,7 +51,7 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
|
||||||
await conn.close()
|
await conn.close()
|
||||||
|
|
||||||
|
|
||||||
async def _wait_for_audio_completion(conn):
|
async def _wait_for_audio_completion(conn: "ConnectionHandler"):
|
||||||
"""
|
"""
|
||||||
等待音频队列清空并等待预缓冲包播放完成
|
等待音频队列清空并等待预缓冲包播放完成
|
||||||
|
|
||||||
|
|
@ -70,7 +74,9 @@ async def _wait_for_audio_completion(conn):
|
||||||
conn.logger.bind(tag=TAG).debug("音频发送完成")
|
conn.logger.bind(tag=TAG).debug("音频发送完成")
|
||||||
|
|
||||||
|
|
||||||
async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence):
|
async def _send_to_mqtt_gateway(
|
||||||
|
conn: "ConnectionHandler", opus_packet, timestamp, sequence
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
发送带16字节头部的opus数据包给mqtt_gateway
|
发送带16字节头部的opus数据包给mqtt_gateway
|
||||||
Args:
|
Args:
|
||||||
|
|
@ -92,7 +98,9 @@ async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence):
|
||||||
await conn.websocket.send(complete_packet)
|
await conn.websocket.send(complete_packet)
|
||||||
|
|
||||||
|
|
||||||
async def sendAudio(conn, audios, frame_duration=AUDIO_FRAME_DURATION):
|
async def sendAudio(
|
||||||
|
conn: "ConnectionHandler", audios, frame_duration=AUDIO_FRAME_DURATION
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
发送音频包,使用 AudioRateController 进行精确的流量控制
|
发送音频包,使用 AudioRateController 进行精确的流量控制
|
||||||
|
|
||||||
|
|
@ -121,7 +129,9 @@ async def sendAudio(conn, audios, frame_duration=AUDIO_FRAME_DURATION):
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _get_or_create_rate_controller(conn, frame_duration, is_single_packet):
|
def _get_or_create_rate_controller(
|
||||||
|
conn: "ConnectionHandler", frame_duration, is_single_packet
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
获取或创建 RateController 和 flow_control
|
获取或创建 RateController 和 flow_control
|
||||||
|
|
||||||
|
|
@ -177,7 +187,7 @@ def _get_or_create_rate_controller(conn, frame_duration, is_single_packet):
|
||||||
return conn.audio_rate_controller, conn.audio_flow_control
|
return conn.audio_rate_controller, conn.audio_flow_control
|
||||||
|
|
||||||
|
|
||||||
def _start_background_sender(conn, rate_controller, flow_control):
|
def _start_background_sender(conn: "ConnectionHandler", rate_controller, flow_control):
|
||||||
"""
|
"""
|
||||||
启动后台发送循环任务
|
启动后台发送循环任务
|
||||||
|
|
||||||
|
|
@ -201,7 +211,7 @@ def _start_background_sender(conn, rate_controller, flow_control):
|
||||||
|
|
||||||
|
|
||||||
async def _send_audio_with_rate_control(
|
async def _send_audio_with_rate_control(
|
||||||
conn, audio_list, rate_controller, flow_control, send_delay
|
conn: "ConnectionHandler", audio_list, rate_controller, flow_control, send_delay
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
使用 rate_controller 发送音频包
|
使用 rate_controller 发送音频包
|
||||||
|
|
@ -233,7 +243,7 @@ async def _send_audio_with_rate_control(
|
||||||
rate_controller.add_audio(packet)
|
rate_controller.add_audio(packet)
|
||||||
|
|
||||||
|
|
||||||
async def _do_send_audio(conn, opus_packet, flow_control):
|
async def _do_send_audio(conn: "ConnectionHandler", opus_packet, flow_control):
|
||||||
"""
|
"""
|
||||||
执行实际的音频发送
|
执行实际的音频发送
|
||||||
"""
|
"""
|
||||||
|
|
@ -254,7 +264,7 @@ async def _do_send_audio(conn, opus_packet, flow_control):
|
||||||
flow_control["sequence"] = sequence + 1
|
flow_control["sequence"] = sequence + 1
|
||||||
|
|
||||||
|
|
||||||
async def send_tts_message(conn, state, text=None):
|
async def send_tts_message(conn: "ConnectionHandler", state, text=None):
|
||||||
"""发送 TTS 状态消息"""
|
"""发送 TTS 状态消息"""
|
||||||
if text is None and state == "sentence_start":
|
if text is None and state == "sentence_start":
|
||||||
return
|
return
|
||||||
|
|
@ -281,7 +291,7 @@ async def send_tts_message(conn, state, text=None):
|
||||||
await conn.websocket.send(json.dumps(message))
|
await conn.websocket.send(json.dumps(message))
|
||||||
|
|
||||||
|
|
||||||
async def send_stt_message(conn, text):
|
async def send_stt_message(conn: "ConnectionHandler", text):
|
||||||
"""发送 STT 状态消息"""
|
"""发送 STT 状态消息"""
|
||||||
end_prompt_str = conn.config.get("end_prompt", {}).get("prompt")
|
end_prompt_str = conn.config.get("end_prompt", {}).get("prompt")
|
||||||
if end_prompt_str and end_prompt_str == text:
|
if end_prompt_str and end_prompt_str == text:
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,7 @@
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry
|
from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry
|
||||||
from core.handle.textMessageProcessor import TextMessageProcessor
|
from core.handle.textMessageProcessor import TextMessageProcessor
|
||||||
|
|
||||||
|
|
@ -9,6 +13,7 @@ message_registry = TextMessageHandlerRegistry()
|
||||||
# 创建全局消息处理器实例
|
# 创建全局消息处理器实例
|
||||||
message_processor = TextMessageProcessor(message_registry)
|
message_processor = TextMessageProcessor(message_registry)
|
||||||
|
|
||||||
async def handleTextMessage(conn, message):
|
|
||||||
|
async def handleTextMessage(conn: "ConnectionHandler", message):
|
||||||
"""处理文本消息"""
|
"""处理文本消息"""
|
||||||
await message_processor.process_message(conn, message)
|
await message_processor.process_message(conn, message)
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any, TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from core.handle.helloHandle import handleHelloMessage
|
from core.handle.helloHandle import handleHelloMessage
|
||||||
from core.handle.textMessageHandler import TextMessageHandler
|
from core.handle.textMessageHandler import TextMessageHandler
|
||||||
from core.handle.textMessageType import TextMessageType
|
from core.handle.textMessageType import TextMessageType
|
||||||
|
|
@ -12,5 +14,5 @@ class HelloTextMessageHandler(TextMessageHandler):
|
||||||
def message_type(self) -> TextMessageType:
|
def message_type(self) -> TextMessageType:
|
||||||
return TextMessageType.HELLO
|
return TextMessageType.HELLO
|
||||||
|
|
||||||
async def handle(self, conn, msg_json: Dict[str, Any]) -> None:
|
async def handle(self, conn: "ConnectionHandler", msg_json: Dict[str, Any]) -> None:
|
||||||
await handleHelloMessage(conn, msg_json)
|
await handleHelloMessage(conn, msg_json)
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
import asyncio
|
import asyncio
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any, TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from core.handle.textMessageHandler import TextMessageHandler
|
from core.handle.textMessageHandler import TextMessageHandler
|
||||||
from core.handle.textMessageType import TextMessageType
|
from core.handle.textMessageType import TextMessageType
|
||||||
from core.providers.tools.device_iot import handleIotStatus, handleIotDescriptors
|
from core.providers.tools.device_iot import handleIotStatus, handleIotDescriptors
|
||||||
|
|
@ -13,7 +15,7 @@ class IotTextMessageHandler(TextMessageHandler):
|
||||||
def message_type(self) -> TextMessageType:
|
def message_type(self) -> TextMessageType:
|
||||||
return TextMessageType.IOT
|
return TextMessageType.IOT
|
||||||
|
|
||||||
async def handle(self, conn, msg_json: Dict[str, Any]) -> None:
|
async def handle(self, conn: "ConnectionHandler", msg_json: Dict[str, Any]) -> None:
|
||||||
if "descriptors" in msg_json:
|
if "descriptors" in msg_json:
|
||||||
asyncio.create_task(handleIotDescriptors(conn, msg_json["descriptors"]))
|
asyncio.create_task(handleIotDescriptors(conn, msg_json["descriptors"]))
|
||||||
if "states" in msg_json:
|
if "states" in msg_json:
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,9 @@
|
||||||
import time
|
import time
|
||||||
import asyncio
|
import asyncio
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any, TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
from core.handle.receiveAudioHandle import startToChat
|
from core.handle.receiveAudioHandle import startToChat
|
||||||
from core.handle.reportHandle import enqueue_asr_report
|
from core.handle.reportHandle import enqueue_asr_report
|
||||||
|
|
@ -19,17 +22,16 @@ class ListenTextMessageHandler(TextMessageHandler):
|
||||||
def message_type(self) -> TextMessageType:
|
def message_type(self) -> TextMessageType:
|
||||||
return TextMessageType.LISTEN
|
return TextMessageType.LISTEN
|
||||||
|
|
||||||
async def handle(self, conn, msg_json: Dict[str, Any]) -> None:
|
async def handle(self, conn: "ConnectionHandler", msg_json: Dict[str, Any]) -> None:
|
||||||
if "mode" in msg_json:
|
if "mode" in msg_json:
|
||||||
conn.client_listen_mode = msg_json["mode"]
|
conn.client_listen_mode = msg_json["mode"]
|
||||||
conn.logger.bind(tag=TAG).debug(
|
conn.logger.bind(tag=TAG).debug(
|
||||||
f"客户端拾音模式:{conn.client_listen_mode}"
|
f"客户端拾音模式:{conn.client_listen_mode}"
|
||||||
)
|
)
|
||||||
if msg_json["state"] == "start":
|
if msg_json["state"] == "start":
|
||||||
conn.client_have_voice = True
|
# 设备从播放模式切回录音模式,清除所有音频状态和缓冲区
|
||||||
conn.client_voice_stop = False
|
conn.reset_audio_states()
|
||||||
elif msg_json["state"] == "stop":
|
elif msg_json["state"] == "stop":
|
||||||
conn.client_have_voice = True
|
|
||||||
conn.client_voice_stop = True
|
conn.client_voice_stop = True
|
||||||
if conn.asr.interface_type == InterfaceType.STREAM:
|
if conn.asr.interface_type == InterfaceType.STREAM:
|
||||||
# 流式模式下,发送结束请求
|
# 流式模式下,发送结束请求
|
||||||
|
|
@ -38,14 +40,13 @@ class ListenTextMessageHandler(TextMessageHandler):
|
||||||
# 非流式模式:直接触发ASR识别
|
# 非流式模式:直接触发ASR识别
|
||||||
if len(conn.asr_audio) > 0:
|
if len(conn.asr_audio) > 0:
|
||||||
asr_audio_task = conn.asr_audio.copy()
|
asr_audio_task = conn.asr_audio.copy()
|
||||||
conn.asr_audio.clear()
|
conn.reset_audio_states()
|
||||||
conn.reset_vad_states()
|
|
||||||
|
|
||||||
if len(asr_audio_task) > 0:
|
if len(asr_audio_task) > 0:
|
||||||
await conn.asr.handle_voice_stop(conn, asr_audio_task)
|
await conn.asr.handle_voice_stop(conn, asr_audio_task)
|
||||||
elif msg_json["state"] == "detect":
|
elif msg_json["state"] == "detect":
|
||||||
conn.client_have_voice = False
|
conn.client_have_voice = False
|
||||||
conn.asr_audio.clear()
|
conn.reset_audio_states()
|
||||||
if "text" in msg_json:
|
if "text" in msg_json:
|
||||||
conn.last_activity_time = time.time() * 1000
|
conn.last_activity_time = time.time() * 1000
|
||||||
original_text = msg_json["text"] # 保留原始文本
|
original_text = msg_json["text"] # 保留原始文本
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
import asyncio
|
import asyncio
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any, TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from core.handle.textMessageHandler import TextMessageHandler
|
from core.handle.textMessageHandler import TextMessageHandler
|
||||||
from core.handle.textMessageType import TextMessageType
|
from core.handle.textMessageType import TextMessageType
|
||||||
from core.providers.tools.device_mcp import handle_mcp_message
|
from core.providers.tools.device_mcp import handle_mcp_message
|
||||||
|
|
@ -13,7 +15,7 @@ class McpTextMessageHandler(TextMessageHandler):
|
||||||
def message_type(self) -> TextMessageType:
|
def message_type(self) -> TextMessageType:
|
||||||
return TextMessageType.MCP
|
return TextMessageType.MCP
|
||||||
|
|
||||||
async def handle(self, conn, msg_json: Dict[str, Any]) -> None:
|
async def handle(self, conn: "ConnectionHandler", msg_json: Dict[str, Any]) -> None:
|
||||||
if "payload" in msg_json:
|
if "payload" in msg_json:
|
||||||
asyncio.create_task(
|
asyncio.create_task(
|
||||||
handle_mcp_message(conn, conn.mcp_client, msg_json["payload"])
|
handle_mcp_message(conn, conn.mcp_client, msg_json["payload"])
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,8 @@
|
||||||
import json
|
import json
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry
|
from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
@ -11,7 +14,7 @@ class TextMessageProcessor:
|
||||||
def __init__(self, registry: TextMessageHandlerRegistry):
|
def __init__(self, registry: TextMessageHandlerRegistry):
|
||||||
self.registry = registry
|
self.registry = registry
|
||||||
|
|
||||||
async def process_message(self, conn, message: str) -> None:
|
async def process_message(self, conn: "ConnectionHandler", message: str) -> None:
|
||||||
"""处理消息的主入口"""
|
"""处理消息的主入口"""
|
||||||
try:
|
try:
|
||||||
# 解析JSON消息
|
# 解析JSON消息
|
||||||
|
|
|
||||||
|
|
@ -213,36 +213,24 @@ class ASRProvider(ASRProviderBase):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
async def speech_to_text(
|
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", artifacts=None
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""将语音数据转换为文本"""
|
"""将语音数据转换为文本"""
|
||||||
if self._is_token_expired():
|
if self._is_token_expired():
|
||||||
logger.warning("Token已过期,正在自动刷新...")
|
logger.warning("Token已过期,正在自动刷新...")
|
||||||
self._refresh_token()
|
self._refresh_token()
|
||||||
|
|
||||||
file_path = None
|
|
||||||
try:
|
try:
|
||||||
# 解码Opus为PCM
|
if artifacts is None:
|
||||||
if audio_format == "pcm":
|
return "", None
|
||||||
pcm_data = opus_data
|
|
||||||
else:
|
|
||||||
pcm_data = self.decode_opus(opus_data)
|
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
|
||||||
if self.delete_audio_file:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
|
||||||
|
|
||||||
# 发送请求并获取文本
|
# 发送请求并获取文本
|
||||||
text = await self._send_request(combined_pcm_data)
|
text = await self._send_request(artifacts.pcm_bytes)
|
||||||
|
|
||||||
if text:
|
if text:
|
||||||
return text, file_path
|
return text, artifacts.file_path
|
||||||
|
|
||||||
return "", file_path
|
return "", artifacts.file_path
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
||||||
return "", file_path
|
return "", None
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,10 @@ from datetime import datetime
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.providers.asr.base import ASRProviderBase
|
from core.providers.asr.base import ASRProviderBase
|
||||||
from core.providers.asr.dto.dto import InterfaceType
|
from core.providers.asr.dto.dto import InterfaceType
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -126,16 +130,8 @@ class ASRProvider(ASRProviderBase):
|
||||||
await super().open_audio_channels(conn)
|
await super().open_audio_channels(conn)
|
||||||
|
|
||||||
async def receive_audio(self, conn, audio, audio_have_voice):
|
async def receive_audio(self, conn, audio, audio_have_voice):
|
||||||
# 初始化音频缓存
|
# 先调用父类方法处理基础逻辑
|
||||||
if not hasattr(conn, 'asr_audio_for_voiceprint'):
|
await super().receive_audio(conn, audio, audio_have_voice)
|
||||||
conn.asr_audio_for_voiceprint = []
|
|
||||||
|
|
||||||
# 存储音频数据
|
|
||||||
if audio:
|
|
||||||
conn.asr_audio_for_voiceprint.append(audio)
|
|
||||||
|
|
||||||
conn.asr_audio.append(audio)
|
|
||||||
conn.asr_audio = conn.asr_audio[-10:]
|
|
||||||
|
|
||||||
# 只在有声音且没有连接时建立连接(排除正在停止的情况)
|
# 只在有声音且没有连接时建立连接(排除正在停止的情况)
|
||||||
if audio_have_voice and not self.is_processing and not self.asr_ws:
|
if audio_have_voice and not self.is_processing and not self.asr_ws:
|
||||||
|
|
@ -152,9 +148,9 @@ class ASRProvider(ASRProviderBase):
|
||||||
await self.asr_ws.send(pcm_frame)
|
await self.asr_ws.send(pcm_frame)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}")
|
logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}")
|
||||||
await self._cleanup(conn)
|
await self._cleanup()
|
||||||
|
|
||||||
async def _start_recognition(self, conn):
|
async def _start_recognition(self, conn: "ConnectionHandler"):
|
||||||
"""开始识别会话"""
|
"""开始识别会话"""
|
||||||
if self._is_token_expired():
|
if self._is_token_expired():
|
||||||
self._refresh_token()
|
self._refresh_token()
|
||||||
|
|
@ -200,12 +196,14 @@ class ASRProvider(ASRProviderBase):
|
||||||
await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False))
|
await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False))
|
||||||
logger.bind(tag=TAG).debug("已发送开始请求,等待服务器准备...")
|
logger.bind(tag=TAG).debug("已发送开始请求,等待服务器准备...")
|
||||||
|
|
||||||
async def _forward_results(self, conn):
|
async def _forward_results(self, conn: "ConnectionHandler"):
|
||||||
"""转发识别结果"""
|
"""转发识别结果"""
|
||||||
try:
|
try:
|
||||||
while not conn.stop_event.is_set():
|
while not conn.stop_event.is_set():
|
||||||
|
# 获取当前连接的音频数据
|
||||||
|
audio_data = conn.asr_audio
|
||||||
try:
|
try:
|
||||||
response = await asyncio.wait_for(self.asr_ws.recv(), timeout=1.0)
|
response = await self.asr_ws.recv()
|
||||||
result = json.loads(response)
|
result = json.loads(response)
|
||||||
|
|
||||||
header = result.get("header", {})
|
header = result.get("header", {})
|
||||||
|
|
@ -257,19 +255,12 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
# 手动模式下,只有在收到stop信号后才触发处理(仅处理一次)
|
# 手动模式下,只有在收到stop信号后才触发处理(仅处理一次)
|
||||||
if conn.client_voice_stop:
|
if conn.client_voice_stop:
|
||||||
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
|
logger.bind(tag=TAG).debug("收到最终识别结果,触发处理")
|
||||||
if len(audio_data) > 0:
|
await self.handle_voice_stop(conn, audio_data)
|
||||||
logger.bind(tag=TAG).debug("收到最终识别结果,触发处理")
|
|
||||||
await self.handle_voice_stop(conn, audio_data)
|
|
||||||
# 清理音频缓存
|
|
||||||
conn.asr_audio.clear()
|
|
||||||
conn.reset_vad_states()
|
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
# 自动模式下直接覆盖
|
# 自动模式下直接覆盖
|
||||||
self.text = text
|
self.text = text
|
||||||
conn.reset_vad_states()
|
|
||||||
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
|
|
||||||
await self.handle_voice_stop(conn, audio_data)
|
await self.handle_voice_stop(conn, audio_data)
|
||||||
break
|
break
|
||||||
|
|
||||||
|
|
@ -289,11 +280,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
finally:
|
finally:
|
||||||
# 清理连接的音频缓存
|
# 清理连接的音频缓存
|
||||||
await self._cleanup()
|
await self._cleanup()
|
||||||
if conn:
|
conn.reset_audio_states()
|
||||||
if hasattr(conn, 'asr_audio_for_voiceprint'):
|
|
||||||
conn.asr_audio_for_voiceprint = []
|
|
||||||
if hasattr(conn, 'asr_audio'):
|
|
||||||
conn.asr_audio = []
|
|
||||||
|
|
||||||
async def _send_stop_request(self):
|
async def _send_stop_request(self):
|
||||||
"""发送停止识别请求(不关闭连接)"""
|
"""发送停止识别请求(不关闭连接)"""
|
||||||
|
|
@ -341,7 +328,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
logger.bind(tag=TAG).debug("ASR会话清理完成")
|
logger.bind(tag=TAG).debug("ASR会话清理完成")
|
||||||
|
|
||||||
async def speech_to_text(self, opus_data, session_id, audio_format):
|
async def speech_to_text(self, opus_data, session_id, audio_format, artifacts=None):
|
||||||
"""获取识别结果"""
|
"""获取识别结果"""
|
||||||
result = self.text
|
result = self.text
|
||||||
self.text = ""
|
self.text = ""
|
||||||
|
|
@ -349,7 +336,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
"""关闭资源"""
|
"""关闭资源"""
|
||||||
await self._cleanup(None)
|
await self._cleanup()
|
||||||
if hasattr(self, 'decoder') and self.decoder is not None:
|
if hasattr(self, 'decoder') and self.decoder is not None:
|
||||||
try:
|
try:
|
||||||
del self.decoder
|
del self.decoder
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,11 @@ import uuid
|
||||||
import asyncio
|
import asyncio
|
||||||
import websockets
|
import websockets
|
||||||
import opuslib_next
|
import opuslib_next
|
||||||
from typing import List
|
from typing import List, TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.providers.asr.base import ASRProviderBase
|
from core.providers.asr.base import ASRProviderBase
|
||||||
from core.providers.asr.dto.dto import InterfaceType
|
from core.providers.asr.dto.dto import InterfaceType
|
||||||
|
|
@ -52,16 +56,8 @@ class ASRProvider(ASRProviderBase):
|
||||||
await super().open_audio_channels(conn)
|
await super().open_audio_channels(conn)
|
||||||
|
|
||||||
async def receive_audio(self, conn, audio, audio_have_voice):
|
async def receive_audio(self, conn, audio, audio_have_voice):
|
||||||
# 初始化音频缓存
|
# 先调用父类方法处理基础逻辑
|
||||||
if not hasattr(conn, 'asr_audio_for_voiceprint'):
|
await super().receive_audio(conn, audio, audio_have_voice)
|
||||||
conn.asr_audio_for_voiceprint = []
|
|
||||||
|
|
||||||
# 存储音频数据
|
|
||||||
if audio:
|
|
||||||
conn.asr_audio_for_voiceprint.append(audio)
|
|
||||||
|
|
||||||
conn.asr_audio.append(audio)
|
|
||||||
conn.asr_audio = conn.asr_audio[-10:]
|
|
||||||
|
|
||||||
# 只在有声音且没有连接时建立连接
|
# 只在有声音且没有连接时建立连接
|
||||||
if audio_have_voice and not self.is_processing and not self.asr_ws:
|
if audio_have_voice and not self.is_processing and not self.asr_ws:
|
||||||
|
|
@ -82,7 +78,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}")
|
logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}")
|
||||||
await self._cleanup()
|
await self._cleanup()
|
||||||
|
|
||||||
async def _start_recognition(self, conn):
|
async def _start_recognition(self, conn: "ConnectionHandler"):
|
||||||
"""开始识别会话"""
|
"""开始识别会话"""
|
||||||
try:
|
try:
|
||||||
# 如果为手动模式,设置超时时长为最大值
|
# 如果为手动模式,设置超时时长为最大值
|
||||||
|
|
@ -162,10 +158,12 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
return message
|
return message
|
||||||
|
|
||||||
async def _forward_results(self, conn):
|
async def _forward_results(self, conn: "ConnectionHandler"):
|
||||||
"""转发识别结果"""
|
"""转发识别结果"""
|
||||||
try:
|
try:
|
||||||
while not conn.stop_event.is_set():
|
while not conn.stop_event.is_set():
|
||||||
|
# 获取当前连接的音频数据
|
||||||
|
audio_data = conn.asr_audio
|
||||||
try:
|
try:
|
||||||
response = await asyncio.wait_for(self.asr_ws.recv(), timeout=1.0)
|
response = await asyncio.wait_for(self.asr_ws.recv(), timeout=1.0)
|
||||||
result = json.loads(response)
|
result = json.loads(response)
|
||||||
|
|
@ -214,19 +212,12 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
# 手动模式下,只有在收到stop信号后才触发处理
|
# 手动模式下,只有在收到stop信号后才触发处理
|
||||||
if conn.client_voice_stop:
|
if conn.client_voice_stop:
|
||||||
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
|
logger.bind(tag=TAG).debug("收到最终识别结果,触发处理")
|
||||||
if len(audio_data) > 0:
|
await self.handle_voice_stop(conn, audio_data)
|
||||||
logger.bind(tag=TAG).debug("收到最终识别结果,触发处理")
|
|
||||||
await self.handle_voice_stop(conn, audio_data)
|
|
||||||
# 清理音频缓存
|
|
||||||
conn.asr_audio.clear()
|
|
||||||
conn.reset_vad_states()
|
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
# 自动模式下直接覆盖
|
# 自动模式下直接覆盖
|
||||||
self.text = text
|
self.text = text
|
||||||
conn.reset_vad_states()
|
|
||||||
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
|
|
||||||
await self.handle_voice_stop(conn, audio_data)
|
await self.handle_voice_stop(conn, audio_data)
|
||||||
break
|
break
|
||||||
|
|
||||||
|
|
@ -257,11 +248,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
finally:
|
finally:
|
||||||
# 清理连接的音频缓存
|
# 清理连接的音频缓存
|
||||||
await self._cleanup()
|
await self._cleanup()
|
||||||
if conn:
|
conn.reset_audio_states()
|
||||||
if hasattr(conn, 'asr_audio_for_voiceprint'):
|
|
||||||
conn.asr_audio_for_voiceprint = []
|
|
||||||
if hasattr(conn, 'asr_audio'):
|
|
||||||
conn.asr_audio = []
|
|
||||||
|
|
||||||
async def _send_stop_request(self):
|
async def _send_stop_request(self):
|
||||||
"""发送停止请求(用于手动模式停止录音)"""
|
"""发送停止请求(用于手动模式停止录音)"""
|
||||||
|
|
@ -325,7 +312,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
logger.bind(tag=TAG).debug("ASR会话清理完成")
|
logger.bind(tag=TAG).debug("ASR会话清理完成")
|
||||||
|
|
||||||
async def speech_to_text(self, opus_data, session_id, audio_format):
|
async def speech_to_text(self, opus_data, session_id, audio_format, artifacts=None):
|
||||||
"""获取识别结果"""
|
"""获取识别结果"""
|
||||||
result = self.text
|
result = self.text
|
||||||
self.text = ""
|
self.text = ""
|
||||||
|
|
|
||||||
|
|
@ -30,37 +30,26 @@ class ASRProvider(ASRProviderBase):
|
||||||
os.makedirs(self.output_dir, exist_ok=True)
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
|
||||||
async def speech_to_text(
|
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", artifacts=None
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""将语音数据转换为文本"""
|
"""将语音数据转换为文本"""
|
||||||
if not opus_data:
|
if not opus_data:
|
||||||
logger.bind(tag=TAG).warning("音频数据为空!")
|
logger.bind(tag=TAG).warning("音频数据为空!")
|
||||||
return None, None
|
return None, None
|
||||||
|
|
||||||
file_path = None
|
|
||||||
try:
|
try:
|
||||||
# 检查配置是否已设置
|
# 检查配置是否已设置
|
||||||
if not self.app_id or not self.api_key or not self.secret_key:
|
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("百度语音识别配置未设置,无法进行识别")
|
||||||
return None, file_path
|
return None, None
|
||||||
|
|
||||||
# 将Opus音频数据解码为PCM
|
if artifacts is None:
|
||||||
if audio_format == "pcm":
|
return "", None
|
||||||
pcm_data = opus_data
|
|
||||||
else:
|
|
||||||
pcm_data = self.decode_opus(opus_data)
|
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
|
||||||
if self.delete_audio_file:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
self.save_audio_to_file(pcm_data, session_id)
|
|
||||||
|
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
# 识别本地文件
|
# 识别本地文件
|
||||||
result = self.client.asr(
|
result = self.client.asr(
|
||||||
combined_pcm_data,
|
artifacts.pcm_bytes,
|
||||||
"pcm",
|
"pcm",
|
||||||
16000,
|
16000,
|
||||||
{
|
{
|
||||||
|
|
@ -73,13 +62,13 @@ class ASRProvider(ASRProviderBase):
|
||||||
f"百度语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}"
|
f"百度语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}"
|
||||||
)
|
)
|
||||||
result = result["result"][0]
|
result = result["result"][0]
|
||||||
return result, file_path
|
return result, artifacts.file_path
|
||||||
else:
|
else:
|
||||||
raise Exception(
|
raise Exception(
|
||||||
f"百度语音识别失败,错误码: {result['err_no']},错误信息: {result['err_msg']}"
|
f"百度语音识别失败,错误码: {result['err_no']},错误信息: {result['err_msg']}"
|
||||||
)
|
)
|
||||||
return None, file_path
|
return None, artifacts.file_path
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True)
|
logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True)
|
||||||
return None, file_path
|
return None, None
|
||||||
|
|
|
||||||
|
|
@ -5,17 +5,25 @@ import uuid
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
import queue
|
import queue
|
||||||
|
import shutil
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import tempfile
|
||||||
import traceback
|
import traceback
|
||||||
import threading
|
import threading
|
||||||
import opuslib_next
|
import opuslib_next
|
||||||
|
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from typing import Optional, Tuple, List
|
from core.providers.asr.dto.dto import InterfaceType
|
||||||
from core.handle.receiveAudioHandle import startToChat
|
from core.handle.receiveAudioHandle import startToChat
|
||||||
from core.handle.reportHandle import enqueue_asr_report
|
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
|
||||||
from core.handle.receiveAudioHandle import handleAudioMessage
|
from core.handle.receiveAudioHandle import handleAudioMessage
|
||||||
|
from typing import Optional, Tuple, List, NamedTuple, TYPE_CHECKING
|
||||||
|
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -26,14 +34,14 @@ class ASRProviderBase(ABC):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# 打开音频通道
|
# 打开音频通道
|
||||||
async def open_audio_channels(self, conn):
|
async def open_audio_channels(self, conn: "ConnectionHandler"):
|
||||||
conn.asr_priority_thread = threading.Thread(
|
conn.asr_priority_thread = threading.Thread(
|
||||||
target=self.asr_text_priority_thread, args=(conn,), daemon=True
|
target=self.asr_text_priority_thread, args=(conn,), daemon=True
|
||||||
)
|
)
|
||||||
conn.asr_priority_thread.start()
|
conn.asr_priority_thread.start()
|
||||||
|
|
||||||
# 有序处理ASR音频
|
# 有序处理ASR音频
|
||||||
def asr_text_priority_thread(self, conn):
|
def asr_text_priority_thread(self, conn: "ConnectionHandler"):
|
||||||
while not conn.stop_event.is_set():
|
while not conn.stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
message = conn.asr_audio_queue.get(timeout=1)
|
message = conn.asr_audio_queue.get(timeout=1)
|
||||||
|
|
@ -51,30 +59,29 @@ class ASRProviderBase(ABC):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# 接收音频
|
# 接收音频
|
||||||
async def receive_audio(self, conn, audio, audio_have_voice):
|
async def receive_audio(self, conn: "ConnectionHandler", audio, audio_have_voice):
|
||||||
if conn.client_listen_mode == "manual":
|
if conn.client_listen_mode == "manual":
|
||||||
# 手动模式:缓存音频用于ASR识别
|
# 手动模式:缓存音频用于ASR识别
|
||||||
conn.asr_audio.append(audio)
|
conn.asr_audio.append(audio)
|
||||||
else:
|
else:
|
||||||
# 自动/实时模式:使用VAD检测
|
# 自动/实时模式:使用VAD检测
|
||||||
have_voice = audio_have_voice
|
|
||||||
|
|
||||||
conn.asr_audio.append(audio)
|
conn.asr_audio.append(audio)
|
||||||
if not have_voice and not conn.client_have_voice:
|
|
||||||
|
# 如果没有语音,且之前也没有声音,缓存部分音频
|
||||||
|
if not audio_have_voice and not conn.client_have_voice:
|
||||||
conn.asr_audio = conn.asr_audio[-10:]
|
conn.asr_audio = conn.asr_audio[-10:]
|
||||||
return
|
return
|
||||||
|
|
||||||
# 自动模式下通过VAD检测到语音停止时触发识别
|
# 自动模式下通过VAD检测到语音停止时触发识别
|
||||||
if conn.client_voice_stop:
|
if conn.asr.interface_type != InterfaceType.STREAM and conn.client_voice_stop:
|
||||||
asr_audio_task = conn.asr_audio.copy()
|
asr_audio_task = conn.asr_audio.copy()
|
||||||
conn.asr_audio.clear()
|
conn.reset_audio_states()
|
||||||
conn.reset_vad_states()
|
|
||||||
|
|
||||||
if len(asr_audio_task) > 15:
|
if len(asr_audio_task) > 15:
|
||||||
await self.handle_voice_stop(conn, asr_audio_task)
|
await self.handle_voice_stop(conn, asr_audio_task)
|
||||||
|
|
||||||
# 处理语音停止
|
# 处理语音停止
|
||||||
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
|
async def handle_voice_stop(self, conn: "ConnectionHandler", asr_audio_task: List[bytes]):
|
||||||
"""并行处理ASR和声纹识别"""
|
"""并行处理ASR和声纹识别"""
|
||||||
try:
|
try:
|
||||||
total_start_time = time.monotonic()
|
total_start_time = time.monotonic()
|
||||||
|
|
@ -93,10 +100,14 @@ class ASRProviderBase(ABC):
|
||||||
wav_data = self._pcm_to_wav(combined_pcm_data)
|
wav_data = self._pcm_to_wav(combined_pcm_data)
|
||||||
|
|
||||||
# 定义ASR任务
|
# 定义ASR任务
|
||||||
asr_task = self.speech_to_text(asr_audio_task, conn.session_id, conn.audio_format)
|
asr_task = self.speech_to_text_wrapper(
|
||||||
|
asr_audio_task, conn.session_id, conn.audio_format
|
||||||
|
)
|
||||||
|
|
||||||
if conn.voiceprint_provider and wav_data:
|
if conn.voiceprint_provider and wav_data:
|
||||||
voiceprint_task = conn.voiceprint_provider.identify_speaker(wav_data, conn.session_id)
|
voiceprint_task = conn.voiceprint_provider.identify_speaker(
|
||||||
|
wav_data, conn.session_id
|
||||||
|
)
|
||||||
# 并发等待两个结果
|
# 并发等待两个结果
|
||||||
asr_result, voiceprint_result = await asyncio.gather(
|
asr_result, voiceprint_result = await asyncio.gather(
|
||||||
asr_task, voiceprint_task, return_exceptions=True
|
asr_task, voiceprint_task, return_exceptions=True
|
||||||
|
|
@ -159,20 +170,20 @@ class ASRProviderBase(ABC):
|
||||||
if text_len > 0:
|
if text_len > 0:
|
||||||
# 使用自定义模块进行上报
|
# 使用自定义模块进行上报
|
||||||
await startToChat(conn, enhanced_text)
|
await startToChat(conn, enhanced_text)
|
||||||
enqueue_asr_report(conn, enhanced_text, asr_audio_task)
|
audio_snapshot = asr_audio_task.copy()
|
||||||
|
enqueue_asr_report(conn, enhanced_text, audio_snapshot)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
|
logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
|
||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}")
|
logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}")
|
||||||
|
|
||||||
def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str:
|
def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str:
|
||||||
"""构建包含说话人信息的文本(仅用于纯文本ASR)"""
|
"""构建包含说话人信息的文本(仅用于纯文本ASR)"""
|
||||||
if speaker_name and speaker_name.strip():
|
if speaker_name and speaker_name.strip():
|
||||||
return json.dumps({
|
return json.dumps(
|
||||||
"speaker": speaker_name,
|
{"speaker": speaker_name, "content": text}, ensure_ascii=False
|
||||||
"content": text
|
)
|
||||||
}, ensure_ascii=False)
|
|
||||||
else:
|
else:
|
||||||
return text
|
return text
|
||||||
|
|
||||||
|
|
@ -181,23 +192,23 @@ class ASRProviderBase(ABC):
|
||||||
if len(pcm_data) == 0:
|
if len(pcm_data) == 0:
|
||||||
logger.bind(tag=TAG).warning("PCM数据为空,无法转换WAV")
|
logger.bind(tag=TAG).warning("PCM数据为空,无法转换WAV")
|
||||||
return b""
|
return b""
|
||||||
|
|
||||||
# 确保数据长度是偶数(16位音频)
|
# 确保数据长度是偶数(16位音频)
|
||||||
if len(pcm_data) % 2 != 0:
|
if len(pcm_data) % 2 != 0:
|
||||||
pcm_data = pcm_data[:-1]
|
pcm_data = pcm_data[:-1]
|
||||||
|
|
||||||
# 创建WAV文件头
|
# 创建WAV文件头
|
||||||
wav_buffer = io.BytesIO()
|
wav_buffer = io.BytesIO()
|
||||||
try:
|
try:
|
||||||
with wave.open(wav_buffer, 'wb') as wav_file:
|
with wave.open(wav_buffer, "wb") as wav_file:
|
||||||
wav_file.setnchannels(1) # 单声道
|
wav_file.setnchannels(1) # 单声道
|
||||||
wav_file.setsampwidth(2) # 16位
|
wav_file.setsampwidth(2) # 16位
|
||||||
wav_file.setframerate(16000) # 16kHz采样率
|
wav_file.setframerate(16000) # 16kHz采样率
|
||||||
wav_file.writeframes(pcm_data)
|
wav_file.writeframes(pcm_data)
|
||||||
|
|
||||||
wav_buffer.seek(0)
|
wav_buffer.seek(0)
|
||||||
wav_data = wav_buffer.read()
|
wav_data = wav_buffer.read()
|
||||||
|
|
||||||
return wav_data
|
return wav_data
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"WAV转换失败: {e}")
|
logger.bind(tag=TAG).error(f"WAV转换失败: {e}")
|
||||||
|
|
@ -206,6 +217,44 @@ class ASRProviderBase(ABC):
|
||||||
def stop_ws_connection(self):
|
def stop_ws_connection(self):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
async def close(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class AudioArtifacts(NamedTuple):
|
||||||
|
pcm_frames: List[bytes]
|
||||||
|
"""PCM音频帧列表"""
|
||||||
|
pcm_bytes: bytes
|
||||||
|
"""合并后的PCM音频字节数据"""
|
||||||
|
file_path: Optional[str]
|
||||||
|
"""WAV文件路径"""
|
||||||
|
temp_path: Optional[str]
|
||||||
|
"""临时WAV文件路径"""
|
||||||
|
|
||||||
|
def get_current_artifacts(self) -> Optional["ASRProviderBase.AudioArtifacts"]:
|
||||||
|
return self._current_artifacts
|
||||||
|
|
||||||
|
def requires_file(self) -> bool:
|
||||||
|
"""是否需要文件输入"""
|
||||||
|
return False
|
||||||
|
|
||||||
|
def prefers_temp_file(self) -> bool:
|
||||||
|
"""是否优先使用临时文件"""
|
||||||
|
return False
|
||||||
|
|
||||||
|
def build_temp_file(self, pcm_bytes: bytes) -> Optional[str]:
|
||||||
|
try:
|
||||||
|
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
|
||||||
|
temp_path = temp_file.name
|
||||||
|
with wave.open(temp_path, "wb") as wav_file:
|
||||||
|
wav_file.setnchannels(1)
|
||||||
|
wav_file.setsampwidth(2)
|
||||||
|
wav_file.setframerate(16000)
|
||||||
|
wav_file.writeframes(pcm_bytes)
|
||||||
|
return temp_path
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"临时音频文件生成失败: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
|
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
|
||||||
"""PCM数据保存为WAV文件"""
|
"""PCM数据保存为WAV文件"""
|
||||||
module_name = __name__.split(".")[-1]
|
module_name = __name__.split(".")[-1]
|
||||||
|
|
@ -220,11 +269,80 @@ class ASRProviderBase(ABC):
|
||||||
|
|
||||||
return file_path
|
return file_path
|
||||||
|
|
||||||
@abstractmethod
|
async def speech_to_text_wrapper(
|
||||||
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"
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""将语音数据转换为文本"""
|
file_path = None
|
||||||
|
temp_path = None
|
||||||
|
try:
|
||||||
|
if audio_format == "pcm":
|
||||||
|
pcm_data = opus_data
|
||||||
|
else:
|
||||||
|
pcm_data = self.decode_opus(opus_data)
|
||||||
|
combined_pcm_data = b"".join(pcm_data)
|
||||||
|
|
||||||
|
free_space = shutil.disk_usage(self.output_dir).free
|
||||||
|
if free_space < len(combined_pcm_data) * 2:
|
||||||
|
raise OSError("磁盘空间不足")
|
||||||
|
|
||||||
|
if self.requires_file() and self.prefers_temp_file():
|
||||||
|
temp_path = self.build_temp_file(combined_pcm_data)
|
||||||
|
|
||||||
|
if (hasattr(self, "delete_audio_file") and not self.delete_audio_file) or (
|
||||||
|
self.requires_file() and not self.prefers_temp_file()
|
||||||
|
):
|
||||||
|
file_path = self.save_audio_to_file(pcm_data, session_id)
|
||||||
|
|
||||||
|
if len(combined_pcm_data) == 0:
|
||||||
|
artifacts = None
|
||||||
|
else:
|
||||||
|
artifacts = ASRProviderBase.AudioArtifacts(
|
||||||
|
pcm_frames=pcm_data,
|
||||||
|
pcm_bytes=combined_pcm_data,
|
||||||
|
file_path=file_path,
|
||||||
|
temp_path=temp_path,
|
||||||
|
)
|
||||||
|
|
||||||
|
text, _ = await self.speech_to_text(
|
||||||
|
opus_data, session_id, audio_format, artifacts
|
||||||
|
)
|
||||||
|
return text, file_path
|
||||||
|
except OSError as e:
|
||||||
|
logger.bind(tag=TAG).error(f"文件操作错误: {e}")
|
||||||
|
return None, None
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"语音识别失败: {e}")
|
||||||
|
return None, None
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
if temp_path and os.path.exists(temp_path):
|
||||||
|
os.unlink(temp_path)
|
||||||
|
if (
|
||||||
|
hasattr(self, "delete_audio_file")
|
||||||
|
and self.delete_audio_file
|
||||||
|
and file_path
|
||||||
|
and os.path.exists(file_path)
|
||||||
|
):
|
||||||
|
os.remove(file_path)
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"文件清理失败: {e}")
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def speech_to_text(
|
||||||
|
self,
|
||||||
|
opus_data: List[bytes],
|
||||||
|
session_id: str,
|
||||||
|
audio_format="opus",
|
||||||
|
artifacts: Optional[AudioArtifacts] = None,
|
||||||
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
|
"""将语音数据转换为文本
|
||||||
|
|
||||||
|
:param opus_data: 输入的Opus音频数据
|
||||||
|
:param session_id: 会话ID
|
||||||
|
:param audio_format: 音频格式,默认"opus"
|
||||||
|
:param artifacts: 音频工件,包含PCM数据、文件路径等
|
||||||
|
:return: 识别结果文本和文件路径(如果有)
|
||||||
|
"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|
@ -235,23 +353,23 @@ class ASRProviderBase(ABC):
|
||||||
decoder = opuslib_next.Decoder(16000, 1)
|
decoder = opuslib_next.Decoder(16000, 1)
|
||||||
pcm_data = []
|
pcm_data = []
|
||||||
buffer_size = 960 # 每次处理960个采样点 (60ms at 16kHz)
|
buffer_size = 960 # 每次处理960个采样点 (60ms at 16kHz)
|
||||||
|
|
||||||
for i, opus_packet in enumerate(opus_data):
|
for i, opus_packet in enumerate(opus_data):
|
||||||
try:
|
try:
|
||||||
if not opus_packet or len(opus_packet) == 0:
|
if not opus_packet or len(opus_packet) == 0:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
pcm_frame = decoder.decode(opus_packet, buffer_size)
|
pcm_frame = decoder.decode(opus_packet, buffer_size)
|
||||||
if pcm_frame and len(pcm_frame) > 0:
|
if pcm_frame and len(pcm_frame) > 0:
|
||||||
pcm_data.append(pcm_frame)
|
pcm_data.append(pcm_frame)
|
||||||
|
|
||||||
except opuslib_next.OpusError as e:
|
except opuslib_next.OpusError as e:
|
||||||
logger.bind(tag=TAG).warning(f"Opus解码错误,跳过数据包 {i}: {e}")
|
logger.bind(tag=TAG).warning(f"Opus解码错误,跳过数据包 {i}: {e}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"音频处理错误,数据包 {i}: {e}")
|
logger.bind(tag=TAG).error(f"音频处理错误,数据包 {i}: {e}")
|
||||||
|
|
||||||
return pcm_data
|
return pcm_data
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"音频解码过程发生错误: {e}")
|
logger.bind(tag=TAG).error(f"音频解码过程发生错误: {e}")
|
||||||
return []
|
return []
|
||||||
|
|
|
||||||
|
|
@ -232,24 +232,13 @@ class ASRProvider(ASRProviderBase):
|
||||||
yield data[offset:data_len], True
|
yield data[offset:data_len], True
|
||||||
|
|
||||||
async def speech_to_text(
|
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", artifacts=None
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""将语音数据转换为文本"""
|
"""将语音数据转换为文本"""
|
||||||
|
|
||||||
file_path = None
|
|
||||||
try:
|
try:
|
||||||
# 合并所有opus数据包
|
if artifacts is None:
|
||||||
if audio_format == "pcm":
|
return "", None
|
||||||
pcm_data = opus_data
|
|
||||||
else:
|
|
||||||
pcm_data = self.decode_opus(opus_data)
|
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
|
||||||
if self.delete_audio_file:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
|
||||||
|
|
||||||
# 直接使用PCM数据
|
# 直接使用PCM数据
|
||||||
# 计算分段大小 (单声道, 16bit, 16kHz采样率)
|
# 计算分段大小 (单声道, 16bit, 16kHz采样率)
|
||||||
|
|
@ -258,14 +247,14 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
# 语音识别
|
# 语音识别
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
text = await self._send_request(combined_pcm_data, segment_size)
|
text = await self._send_request(artifacts.pcm_bytes, segment_size)
|
||||||
if text:
|
if text:
|
||||||
logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).debug(
|
||||||
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
|
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
|
||||||
)
|
)
|
||||||
return text, file_path
|
return text, artifacts.file_path
|
||||||
return "", file_path
|
return "", artifacts.file_path
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
||||||
return "", file_path
|
return "", None
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,10 @@ import opuslib_next
|
||||||
from core.providers.asr.base import ASRProviderBase
|
from core.providers.asr.base import ASRProviderBase
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.providers.asr.dto.dto import InterfaceType
|
from core.providers.asr.dto.dto import InterfaceType
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -34,7 +38,9 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
# 火山引擎ASR配置
|
# 火山引擎ASR配置
|
||||||
enable_multilingual = config.get("enable_multilingual", False)
|
enable_multilingual = config.get("enable_multilingual", False)
|
||||||
self.enable_multilingual = False if str(enable_multilingual).lower() == 'false' else True
|
self.enable_multilingual = (
|
||||||
|
False if str(enable_multilingual).lower() == "false" else True
|
||||||
|
)
|
||||||
if self.enable_multilingual:
|
if self.enable_multilingual:
|
||||||
self.ws_url = "wss://openspeech.bytedance.com/api/v3/sauc/bigmodel_nostream"
|
self.ws_url = "wss://openspeech.bytedance.com/api/v3/sauc/bigmodel_nostream"
|
||||||
else:
|
else:
|
||||||
|
|
@ -59,19 +65,10 @@ class ASRProvider(ASRProviderBase):
|
||||||
async def open_audio_channels(self, conn):
|
async def open_audio_channels(self, conn):
|
||||||
await super().open_audio_channels(conn)
|
await super().open_audio_channels(conn)
|
||||||
|
|
||||||
async def receive_audio(self, conn, audio, audio_have_voice):
|
async def receive_audio(self, conn: "ConnectionHandler", audio, audio_have_voice):
|
||||||
conn.asr_audio.append(audio)
|
# 先调用父类方法处理基础逻辑
|
||||||
conn.asr_audio = conn.asr_audio[-10:]
|
await super().receive_audio(conn, audio, audio_have_voice)
|
||||||
# 存储音频数据
|
|
||||||
if not hasattr(conn, 'asr_audio_for_voiceprint'):
|
|
||||||
conn.asr_audio_for_voiceprint = []
|
|
||||||
conn.asr_audio_for_voiceprint.append(audio)
|
|
||||||
|
|
||||||
# 当没有音频数据时处理完整语音片段
|
|
||||||
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 audio_have_voice and self.asr_ws is None and not self.is_processing:
|
if audio_have_voice and self.asr_ws is None and not self.is_processing:
|
||||||
try:
|
try:
|
||||||
|
|
@ -160,11 +157,11 @@ class ASRProvider(ASRProviderBase):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).info(f"发送音频数据时发生错误: {e}")
|
logger.bind(tag=TAG).info(f"发送音频数据时发生错误: {e}")
|
||||||
|
|
||||||
async def _forward_asr_results(self, conn):
|
async def _forward_asr_results(self, conn: "ConnectionHandler"):
|
||||||
try:
|
try:
|
||||||
while self.asr_ws and not conn.stop_event.is_set():
|
while self.asr_ws and not conn.stop_event.is_set():
|
||||||
# 获取当前连接的音频数据
|
# 获取当前连接的音频数据
|
||||||
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
|
audio_data = conn.asr_audio
|
||||||
try:
|
try:
|
||||||
response = await self.asr_ws.recv()
|
response = await self.asr_ws.recv()
|
||||||
result = self.parse_response(response)
|
result = self.parse_response(response)
|
||||||
|
|
@ -181,15 +178,15 @@ class ASRProvider(ASRProviderBase):
|
||||||
utterances = payload["result"].get("utterances", [])
|
utterances = payload["result"].get("utterances", [])
|
||||||
# 检查duration和空文本的情况
|
# 检查duration和空文本的情况
|
||||||
if (
|
if (
|
||||||
not self.enable_multilingual # 注意:多语种模式不返回中间结果,需要等待最终结果
|
not self.enable_multilingual # 注意:多语种模式不返回中间结果,需要等待最终结果
|
||||||
and payload.get("audio_info", {}).get("duration", 0) > 2000
|
and payload.get("audio_info", {}).get("duration", 0)
|
||||||
|
> 2000
|
||||||
and not utterances
|
and not utterances
|
||||||
and not payload["result"].get("text")
|
and not payload["result"].get("text")
|
||||||
and conn.client_listen_mode != "manual"
|
and conn.client_listen_mode != "manual"
|
||||||
):
|
):
|
||||||
logger.bind(tag=TAG).error(f"识别文本:空")
|
logger.bind(tag=TAG).error(f"识别文本:空")
|
||||||
self.text = ""
|
self.text = ""
|
||||||
conn.reset_vad_states()
|
|
||||||
if len(audio_data) > 15: # 确保有足够音频数据
|
if len(audio_data) > 15: # 确保有足够音频数据
|
||||||
await self.handle_voice_stop(conn, audio_data)
|
await self.handle_voice_stop(conn, audio_data)
|
||||||
break
|
break
|
||||||
|
|
@ -200,12 +197,9 @@ class ASRProvider(ASRProviderBase):
|
||||||
if self.enable_multilingual:
|
if self.enable_multilingual:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if conn.client_listen_mode == "manual" and conn.client_voice_stop and len(audio_data) > 0:
|
if conn.client_listen_mode == "manual" and conn.client_voice_stop and len(audio_data) > 15:
|
||||||
logger.bind(tag=TAG).debug("消息结束收到停止信号,触发处理")
|
logger.bind(tag=TAG).debug("消息结束收到停止信号,触发处理")
|
||||||
await self.handle_voice_stop(conn, audio_data)
|
await self.handle_voice_stop(conn, audio_data)
|
||||||
# 清理音频缓存
|
|
||||||
conn.asr_audio.clear()
|
|
||||||
conn.reset_vad_states()
|
|
||||||
break
|
break
|
||||||
|
|
||||||
for utterance in utterances:
|
for utterance in utterances:
|
||||||
|
|
@ -226,16 +220,14 @@ class ASRProvider(ASRProviderBase):
|
||||||
if conn.client_voice_stop and len(audio_data) > 0:
|
if conn.client_voice_stop and len(audio_data) > 0:
|
||||||
logger.bind(tag=TAG).debug("消息中途收到停止信号,触发处理")
|
logger.bind(tag=TAG).debug("消息中途收到停止信号,触发处理")
|
||||||
await self.handle_voice_stop(conn, audio_data)
|
await self.handle_voice_stop(conn, audio_data)
|
||||||
# 清理音频缓存
|
|
||||||
conn.asr_audio.clear()
|
|
||||||
conn.reset_vad_states()
|
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
# 自动模式下直接覆盖
|
# 自动模式下直接覆盖
|
||||||
self.text = current_text
|
self.text = current_text
|
||||||
conn.reset_vad_states()
|
|
||||||
if len(audio_data) > 15: # 确保有足够音频数据
|
if len(audio_data) > 15: # 确保有足够音频数据
|
||||||
await self.handle_voice_stop(conn, audio_data)
|
await self.handle_voice_stop(
|
||||||
|
conn, audio_data
|
||||||
|
)
|
||||||
break
|
break
|
||||||
elif "error" in payload:
|
elif "error" in payload:
|
||||||
error_msg = payload.get("error", "未知错误")
|
error_msg = payload.get("error", "未知错误")
|
||||||
|
|
@ -262,11 +254,8 @@ class ASRProvider(ASRProviderBase):
|
||||||
await self.asr_ws.close()
|
await self.asr_ws.close()
|
||||||
self.asr_ws = None
|
self.asr_ws = None
|
||||||
self.is_processing = False
|
self.is_processing = False
|
||||||
if conn:
|
# 重置所有音频相关状态
|
||||||
if hasattr(conn, 'asr_audio_for_voiceprint'):
|
conn.reset_audio_states()
|
||||||
conn.asr_audio_for_voiceprint = []
|
|
||||||
if hasattr(conn, 'asr_audio'):
|
|
||||||
conn.asr_audio = []
|
|
||||||
|
|
||||||
def stop_ws_connection(self):
|
def stop_ws_connection(self):
|
||||||
if self.asr_ws:
|
if self.asr_ws:
|
||||||
|
|
@ -280,7 +269,9 @@ class ASRProvider(ASRProviderBase):
|
||||||
try:
|
try:
|
||||||
# 发送结束标记的音频帧(gzip压缩的空数据)
|
# 发送结束标记的音频帧(gzip压缩的空数据)
|
||||||
empty_payload = gzip.compress(b"")
|
empty_payload = gzip.compress(b"")
|
||||||
last_audio_request = bytearray(self.generate_last_audio_default_header())
|
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(len(empty_payload).to_bytes(4, "big"))
|
||||||
last_audio_request.extend(empty_payload)
|
last_audio_request.extend(empty_payload)
|
||||||
await self.asr_ws.send(last_audio_request)
|
await self.asr_ws.send(last_audio_request)
|
||||||
|
|
@ -408,7 +399,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
logger.bind(tag=TAG).error(f"原始响应数据: {res.hex()}")
|
logger.bind(tag=TAG).error(f"原始响应数据: {res.hex()}")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
async def speech_to_text(self, opus_data, session_id, audio_format):
|
async def speech_to_text(self, opus_data, session_id, audio_format, artifacts=None):
|
||||||
result = self.text
|
result = self.text
|
||||||
self.text = "" # 清空text
|
self.text = "" # 清空text
|
||||||
return result, None
|
return result, None
|
||||||
|
|
@ -426,20 +417,12 @@ class ASRProvider(ASRProviderBase):
|
||||||
pass
|
pass
|
||||||
self.forward_task = None
|
self.forward_task = None
|
||||||
self.is_processing = False
|
self.is_processing = False
|
||||||
|
|
||||||
# 显式释放decoder资源
|
# 显式释放decoder资源
|
||||||
if hasattr(self, 'decoder') and self.decoder is not None:
|
if hasattr(self, "decoder") and self.decoder is not None:
|
||||||
try:
|
try:
|
||||||
del self.decoder
|
del self.decoder
|
||||||
self.decoder = None
|
self.decoder = None
|
||||||
logger.bind(tag=TAG).debug("Doubao decoder resources released")
|
logger.bind(tag=TAG).debug("Doubao decoder resources released")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).debug(f"释放Doubao decoder资源时出错: {e}")
|
logger.bind(tag=TAG).debug(f"释放Doubao decoder资源时出错: {e}")
|
||||||
|
|
||||||
# 清理所有连接的音频缓冲区
|
|
||||||
if hasattr(self, '_connections'):
|
|
||||||
for conn in self._connections.values():
|
|
||||||
if hasattr(conn, 'asr_audio_for_voiceprint'):
|
|
||||||
conn.asr_audio_for_voiceprint = []
|
|
||||||
if hasattr(conn, 'asr_audio'):
|
|
||||||
conn.asr_audio = []
|
|
||||||
|
|
|
||||||
|
|
@ -64,39 +64,21 @@ class ASRProvider(ASRProviderBase):
|
||||||
)
|
)
|
||||||
|
|
||||||
async def speech_to_text(
|
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", artifacts=None
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""语音转文本主处理逻辑"""
|
"""语音转文本主处理逻辑"""
|
||||||
file_path = None
|
|
||||||
retry_count = 0
|
retry_count = 0
|
||||||
|
|
||||||
while retry_count < MAX_RETRIES:
|
while retry_count < MAX_RETRIES:
|
||||||
try:
|
try:
|
||||||
# 合并所有opus数据包
|
if artifacts is None:
|
||||||
if audio_format == "pcm":
|
return "", None
|
||||||
pcm_data = opus_data
|
|
||||||
else:
|
|
||||||
pcm_data = self.decode_opus(opus_data)
|
|
||||||
|
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
|
||||||
|
|
||||||
# 检查磁盘空间
|
|
||||||
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("磁盘空间不足")
|
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
|
||||||
if self.delete_audio_file:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
|
||||||
|
|
||||||
# 语音识别 - 使用线程池避免阻塞事件循环
|
# 语音识别 - 使用线程池避免阻塞事件循环
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
result = await asyncio.to_thread(
|
result = await asyncio.to_thread(
|
||||||
self.model.generate,
|
self.model.generate,
|
||||||
input=combined_pcm_data,
|
input=artifacts.pcm_bytes,
|
||||||
cache={},
|
cache={},
|
||||||
language="auto",
|
language="auto",
|
||||||
use_itn=True,
|
use_itn=True,
|
||||||
|
|
@ -107,7 +89,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text['content']}"
|
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text['content']}"
|
||||||
)
|
)
|
||||||
|
|
||||||
return text, file_path
|
return text, artifacts.file_path
|
||||||
|
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
retry_count += 1
|
retry_count += 1
|
||||||
|
|
@ -115,7 +97,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"语音识别失败(已重试{retry_count}次): {e}", exc_info=True
|
f"语音识别失败(已重试{retry_count}次): {e}", exc_info=True
|
||||||
)
|
)
|
||||||
return "", file_path
|
return "", None
|
||||||
logger.bind(tag=TAG).warning(
|
logger.bind(tag=TAG).warning(
|
||||||
f"语音识别失败,正在重试({retry_count}/{MAX_RETRIES}): {e}"
|
f"语音识别失败,正在重试({retry_count}/{MAX_RETRIES}): {e}"
|
||||||
)
|
)
|
||||||
|
|
@ -123,15 +105,4 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
||||||
return "", file_path
|
return "", None
|
||||||
|
|
||||||
finally:
|
|
||||||
# 文件清理逻辑
|
|
||||||
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}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(
|
|
||||||
f"文件删除失败: {file_path} | 错误: {e}"
|
|
||||||
)
|
|
||||||
|
|
|
||||||
|
|
@ -101,7 +101,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
logger.bind(tag=TAG).debug(f"Sent end message: {end_message}")
|
logger.bind(tag=TAG).debug(f"Sent end message: {end_message}")
|
||||||
|
|
||||||
async def speech_to_text(
|
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", artifacts=None
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""
|
"""
|
||||||
Convert speech data to text using FunASR.
|
Convert speech data to text using FunASR.
|
||||||
|
|
@ -109,18 +109,9 @@ class ASRProvider(ASRProviderBase):
|
||||||
:param session_id: Unique session identifier.
|
:param session_id: Unique session identifier.
|
||||||
:return: Tuple containing recognized text and optional timestamp.
|
:return: Tuple containing recognized text and optional timestamp.
|
||||||
"""
|
"""
|
||||||
file_path = None
|
|
||||||
if audio_format == "pcm":
|
if artifacts is None:
|
||||||
pcm_data = opus_data
|
return "", None
|
||||||
else:
|
|
||||||
pcm_data = self.decode_opus(opus_data)
|
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
|
||||||
if self.delete_audio_file:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
|
||||||
auth_header = {"Authorization": "Bearer; {}".format(self.api_key)}
|
auth_header = {"Authorization": "Bearer; {}".format(self.api_key)}
|
||||||
async with websockets.connect(
|
async with websockets.connect(
|
||||||
self.uri,
|
self.uri,
|
||||||
|
|
@ -132,7 +123,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
try:
|
try:
|
||||||
# Use asyncio to handle WebSocket communication
|
# Use asyncio to handle WebSocket communication
|
||||||
send_task = asyncio.create_task(
|
send_task = asyncio.create_task(
|
||||||
self._send_data(ws, combined_pcm_data, session_id)
|
self._send_data(ws, artifacts.pcm_bytes, session_id)
|
||||||
)
|
)
|
||||||
receive_task = asyncio.create_task(self._receive_responses(ws))
|
receive_task = asyncio.create_task(self._receive_responses(ws))
|
||||||
|
|
||||||
|
|
@ -161,14 +152,14 @@ class ASRProvider(ASRProviderBase):
|
||||||
result = lang_tag_filter(result)
|
result = lang_tag_filter(result)
|
||||||
return (
|
return (
|
||||||
result,
|
result,
|
||||||
file_path,
|
artifacts.file_path,
|
||||||
) # Return the recognized text and timestamp (if any)
|
) # Return the recognized text and timestamp (if any)
|
||||||
|
|
||||||
except websockets.exceptions.ConnectionClosed as e:
|
except websockets.exceptions.ConnectionClosed as e:
|
||||||
logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}")
|
logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}")
|
||||||
return "", file_path
|
return "", artifacts.file_path
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
f"Error during speech-to-text conversion: {e}", exc_info=True
|
f"Error during speech-to-text conversion: {e}", exc_info=True
|
||||||
)
|
)
|
||||||
return "", file_path
|
return "", artifacts.file_path
|
||||||
|
|
|
||||||
|
|
@ -21,20 +21,16 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
os.makedirs(self.output_dir, exist_ok=True)
|
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]]:
|
def requires_file(self) -> bool:
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def speech_to_text(self, opus_data: List[bytes], session_id: str, audio_format="opus", artifacts=None) -> Tuple[Optional[str], Optional[str]]:
|
||||||
file_path = None
|
file_path = None
|
||||||
try:
|
try:
|
||||||
start_time = time.time()
|
if artifacts is None:
|
||||||
if audio_format == "pcm":
|
return "", None
|
||||||
pcm_data = opus_data
|
file_path = artifacts.file_path
|
||||||
else:
|
|
||||||
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}"
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.bind(tag=TAG).info(f"file path: {file_path}")
|
logger.bind(tag=TAG).info(f"file path: {file_path}")
|
||||||
headers = {
|
headers = {
|
||||||
"Authorization": f"Bearer {self.api_key}",
|
"Authorization": f"Bearer {self.api_key}",
|
||||||
|
|
@ -71,12 +67,4 @@ class ASRProvider(ASRProviderBase):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"语音识别失败: {e}")
|
logger.bind(tag=TAG).error(f"语音识别失败: {e}")
|
||||||
return "", None
|
return "", None
|
||||||
finally:
|
|
||||||
# 文件清理逻辑
|
|
||||||
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}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
import os
|
import os
|
||||||
import tempfile
|
|
||||||
from typing import Optional, Tuple, List
|
from typing import Optional, Tuple, List
|
||||||
import dashscope
|
import dashscope
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
@ -35,56 +34,25 @@ class ASRProvider(ASRProviderBase):
|
||||||
# 确保输出目录存在
|
# 确保输出目录存在
|
||||||
os.makedirs(self.output_dir, exist_ok=True)
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
|
||||||
def _prepare_audio_file(self, pcm_data: bytes) -> str:
|
def prefers_temp_file(self) -> bool:
|
||||||
"""将PCM数据转换为WAV文件并返回文件路径"""
|
return True
|
||||||
try:
|
|
||||||
import wave
|
def requires_file(self) -> bool:
|
||||||
|
return True
|
||||||
# 创建临时WAV文件
|
|
||||||
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_file:
|
|
||||||
temp_path = temp_file.name
|
|
||||||
|
|
||||||
# 写入WAV格式
|
|
||||||
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.writeframes(pcm_data)
|
|
||||||
|
|
||||||
return temp_path
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=tag).error(f"音频文件准备失败: {e}")
|
|
||||||
return None
|
|
||||||
|
|
||||||
async def speech_to_text(
|
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", artifacts=None
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""将语音数据转换为文本"""
|
"""将语音数据转换为文本"""
|
||||||
temp_file_path = None
|
temp_file_path = None
|
||||||
file_path = None
|
file_path = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 解码音频数据
|
if artifacts is None:
|
||||||
if audio_format == "pcm":
|
|
||||||
pcm_data = opus_data
|
|
||||||
else:
|
|
||||||
pcm_data = self.decode_opus(opus_data)
|
|
||||||
|
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
|
||||||
if len(combined_pcm_data) == 0:
|
|
||||||
logger.bind(tag=tag).warning("音频数据为空")
|
|
||||||
return "", None
|
return "", None
|
||||||
|
temp_file_path = artifacts.temp_path
|
||||||
# 准备音频文件
|
file_path = artifacts.file_path
|
||||||
temp_file_path = self._prepare_audio_file(combined_pcm_data)
|
|
||||||
if not temp_file_path:
|
if not temp_file_path:
|
||||||
return "", None
|
return "", file_path
|
||||||
|
|
||||||
# 保存音频文件(如果需要)
|
|
||||||
if not self.delete_audio_file:
|
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
|
||||||
|
|
||||||
# 构造请求消息
|
# 构造请求消息
|
||||||
messages = [
|
messages = [
|
||||||
{
|
{
|
||||||
|
|
@ -141,11 +109,3 @@ class ASRProvider(ASRProviderBase):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=tag).error(f"语音识别失败: {e}")
|
logger.bind(tag=tag).error(f"语音识别失败: {e}")
|
||||||
return "", file_path
|
return "", file_path
|
||||||
|
|
||||||
finally:
|
|
||||||
# 清理临时文件
|
|
||||||
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}")
|
|
||||||
|
|
@ -120,24 +120,19 @@ class ASRProvider(ASRProviderBase):
|
||||||
samples_float32 = samples_float32 / 32768
|
samples_float32 = samples_float32 / 32768
|
||||||
return samples_float32, f.getframerate()
|
return samples_float32, f.getframerate()
|
||||||
|
|
||||||
|
def requires_file(self) -> bool:
|
||||||
|
return True
|
||||||
|
|
||||||
async def speech_to_text(
|
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", artifacts=None
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""语音转文本主处理逻辑"""
|
"""语音转文本主处理逻辑"""
|
||||||
file_path = None
|
file_path = None
|
||||||
try:
|
try:
|
||||||
# 保存音频文件
|
if artifacts is None:
|
||||||
start_time = time.time()
|
return "", None
|
||||||
if audio_format == "pcm":
|
file_path = artifacts.file_path
|
||||||
pcm_data = opus_data
|
|
||||||
else:
|
|
||||||
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}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 语音识别
|
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
s = self.model.create_stream()
|
s = self.model.create_stream()
|
||||||
samples, sample_rate = self.read_wave(file_path)
|
samples, sample_rate = self.read_wave(file_path)
|
||||||
|
|
@ -153,11 +148,3 @@ class ASRProvider(ASRProviderBase):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
|
||||||
return "", file_path
|
return "", file_path
|
||||||
finally:
|
|
||||||
# 文件清理逻辑
|
|
||||||
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}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
|
|
||||||
|
|
|
||||||
|
|
@ -32,35 +32,24 @@ class ASRProvider(ASRProviderBase):
|
||||||
os.makedirs(self.output_dir, exist_ok=True)
|
os.makedirs(self.output_dir, exist_ok=True)
|
||||||
|
|
||||||
async def speech_to_text(
|
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", artifacts=None
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""将语音数据转换为文本"""
|
"""将语音数据转换为文本"""
|
||||||
if not opus_data:
|
if not opus_data:
|
||||||
logger.bind(tag=TAG).warning("音频数据为空!")
|
logger.bind(tag=TAG).warning("音频数据为空!")
|
||||||
return None, None
|
return None, None
|
||||||
|
|
||||||
file_path = None
|
|
||||||
try:
|
try:
|
||||||
# 检查配置是否已设置
|
# 检查配置是否已设置
|
||||||
if not self.secret_id or not self.secret_key:
|
if not self.secret_id or not self.secret_key:
|
||||||
logger.bind(tag=TAG).error("腾讯云语音识别配置未设置,无法进行识别")
|
logger.bind(tag=TAG).error("腾讯云语音识别配置未设置,无法进行识别")
|
||||||
return None, file_path
|
return None, None
|
||||||
|
|
||||||
# 将Opus音频数据解码为PCM
|
if artifacts is None:
|
||||||
if audio_format == "pcm":
|
return "", None
|
||||||
pcm_data = opus_data
|
|
||||||
else:
|
|
||||||
pcm_data = self.decode_opus(opus_data)
|
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
|
||||||
if self.delete_audio_file:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
self.save_audio_to_file(pcm_data, session_id)
|
|
||||||
|
|
||||||
# 将音频数据转换为Base64编码
|
# 将音频数据转换为Base64编码
|
||||||
base64_audio = base64.b64encode(combined_pcm_data).decode("utf-8")
|
base64_audio = base64.b64encode(artifacts.pcm_bytes).decode("utf-8")
|
||||||
|
|
||||||
# 构建请求体
|
# 构建请求体
|
||||||
request_body = self._build_request_body(base64_audio)
|
request_body = self._build_request_body(base64_audio)
|
||||||
|
|
@ -77,11 +66,11 @@ class ASRProvider(ASRProviderBase):
|
||||||
f"腾讯云语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}"
|
f"腾讯云语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}"
|
||||||
)
|
)
|
||||||
|
|
||||||
return result, file_path
|
return result, artifacts.file_path
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True)
|
logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True)
|
||||||
return None, file_path
|
return None, None
|
||||||
|
|
||||||
def _build_request_body(self, base64_audio: str) -> str:
|
def _build_request_body(self, base64_audio: str) -> str:
|
||||||
"""构建请求体"""
|
"""构建请求体"""
|
||||||
|
|
|
||||||
|
|
@ -44,36 +44,21 @@ class ASRProvider(ASRProviderBase):
|
||||||
raise
|
raise
|
||||||
|
|
||||||
async def speech_to_text(
|
async def speech_to_text(
|
||||||
self, audio_data: List[bytes], session_id: str, audio_format: str = "opus"
|
self, opus_data: List[bytes], session_id: str, audio_format="opus", artifacts=None
|
||||||
) -> Tuple[Optional[str], Optional[str]]:
|
) -> Tuple[Optional[str], Optional[str]]:
|
||||||
"""将语音数据转换为文本"""
|
"""将语音数据转换为文本"""
|
||||||
file_path = None
|
|
||||||
try:
|
try:
|
||||||
# 检查模型是否加载成功
|
# 检查模型是否加载成功
|
||||||
if not self.model:
|
if not self.model:
|
||||||
logger.bind(tag=TAG).error("VOSK模型未加载,无法进行识别")
|
logger.bind(tag=TAG).error("VOSK模型未加载,无法进行识别")
|
||||||
return "", None
|
return "", None
|
||||||
|
|
||||||
# 解码音频(如果原始格式是Opus)
|
if artifacts is None:
|
||||||
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数据为空,无法进行识别")
|
|
||||||
return "", None
|
return "", None
|
||||||
|
if not artifacts.pcm_bytes:
|
||||||
# 合并PCM数据
|
|
||||||
combined_pcm_data = b"".join(pcm_data)
|
|
||||||
if len(combined_pcm_data) == 0:
|
|
||||||
logger.bind(tag=TAG).warning("合并后的PCM数据为空")
|
logger.bind(tag=TAG).warning("合并后的PCM数据为空")
|
||||||
return "", None
|
return "", None
|
||||||
|
|
||||||
# 判断是否保存为WAV文件
|
|
||||||
if not self.delete_audio_file:
|
|
||||||
file_path = self.save_audio_to_file(pcm_data, session_id)
|
|
||||||
|
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -81,8 +66,8 @@ class ASRProvider(ASRProviderBase):
|
||||||
chunk_size = 2000
|
chunk_size = 2000
|
||||||
text_result = ""
|
text_result = ""
|
||||||
|
|
||||||
for i in range(0, len(combined_pcm_data), chunk_size):
|
for i in range(0, len(artifacts.pcm_bytes), chunk_size):
|
||||||
chunk = combined_pcm_data[i:i+chunk_size]
|
chunk = artifacts.pcm_bytes[i:i+chunk_size]
|
||||||
if self.recognizer.AcceptWaveform(chunk):
|
if self.recognizer.AcceptWaveform(chunk):
|
||||||
result = json.loads(self.recognizer.Result())
|
result = json.loads(self.recognizer.Result())
|
||||||
text = result.get('text', '')
|
text = result.get('text', '')
|
||||||
|
|
@ -99,16 +84,8 @@ class ASRProvider(ASRProviderBase):
|
||||||
f"VOSK语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text_result.strip()}"
|
f"VOSK语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text_result.strip()}"
|
||||||
)
|
)
|
||||||
|
|
||||||
return text_result.strip(), file_path
|
return text_result.strip(), artifacts.file_path
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"VOSK语音识别失败: {e}")
|
logger.bind(tag=TAG).error(f"VOSK语音识别失败: {e}")
|
||||||
return "", None
|
return "", None
|
||||||
finally:
|
|
||||||
# 文件清理逻辑
|
|
||||||
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}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
|
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,10 @@ import gc
|
||||||
from time import mktime
|
from time import mktime
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import urlencode
|
||||||
from typing import List
|
from typing import List, TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from wsgiref.handlers import format_date_time
|
from wsgiref.handlers import format_date_time
|
||||||
from core.providers.asr.base import ASRProviderBase
|
from core.providers.asr.base import ASRProviderBase
|
||||||
|
|
@ -94,18 +97,13 @@ class ASRProvider(ASRProviderBase):
|
||||||
url = url + "?" + urlencode(v)
|
url = url + "?" + urlencode(v)
|
||||||
return url
|
return url
|
||||||
|
|
||||||
async def open_audio_channels(self, conn):
|
async def open_audio_channels(self, conn: "ConnectionHandler"):
|
||||||
await super().open_audio_channels(conn)
|
await super().open_audio_channels(conn)
|
||||||
|
|
||||||
async def receive_audio(self, conn, audio, audio_have_voice):
|
async def receive_audio(self, conn: "ConnectionHandler", audio, audio_have_voice):
|
||||||
# 先调用父类方法处理基础逻辑
|
# 先调用父类方法处理基础逻辑
|
||||||
await super().receive_audio(conn, audio, audio_have_voice)
|
await super().receive_audio(conn, audio, audio_have_voice)
|
||||||
|
|
||||||
# 存储音频数据用于声纹识别
|
|
||||||
if not hasattr(conn, "asr_audio_for_voiceprint"):
|
|
||||||
conn.asr_audio_for_voiceprint = []
|
|
||||||
conn.asr_audio_for_voiceprint.append(audio)
|
|
||||||
|
|
||||||
# 如果本次有声音,且之前没有建立连接
|
# 如果本次有声音,且之前没有建立连接
|
||||||
if audio_have_voice and self.asr_ws is None and not self.is_processing:
|
if audio_have_voice and self.asr_ws is None and not self.is_processing:
|
||||||
try:
|
try:
|
||||||
|
|
@ -124,7 +122,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
logger.bind(tag=TAG).warning(f"发送音频数据时发生错误: {e}")
|
logger.bind(tag=TAG).warning(f"发送音频数据时发生错误: {e}")
|
||||||
await self._cleanup()
|
await self._cleanup()
|
||||||
|
|
||||||
async def _start_recognition(self, conn):
|
async def _start_recognition(self, conn: "ConnectionHandler"):
|
||||||
"""开始识别会话"""
|
"""开始识别会话"""
|
||||||
try:
|
try:
|
||||||
self.is_processing = True
|
self.is_processing = True
|
||||||
|
|
@ -194,7 +192,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
await self.asr_ws.send(json.dumps(frame_data, ensure_ascii=False))
|
await self.asr_ws.send(json.dumps(frame_data, ensure_ascii=False))
|
||||||
|
|
||||||
async def _forward_results(self, conn):
|
async def _forward_results(self, conn: "ConnectionHandler"):
|
||||||
"""转发识别结果"""
|
"""转发识别结果"""
|
||||||
try:
|
try:
|
||||||
while not conn.stop_event.is_set():
|
while not conn.stop_event.is_set():
|
||||||
|
|
@ -231,14 +229,8 @@ class ASRProvider(ASRProviderBase):
|
||||||
self.text += w
|
self.text += w
|
||||||
|
|
||||||
if status == 2:
|
if status == 2:
|
||||||
if conn.client_listen_mode == "manual":
|
logger.bind(tag=TAG).debug("收到最终识别结果,触发处理")
|
||||||
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
|
await self.handle_voice_stop(conn, conn.asr_audio)
|
||||||
if len(audio_data) > 0:
|
|
||||||
logger.bind(tag=TAG).debug("收到最终识别结果,触发处理")
|
|
||||||
await self.handle_voice_stop(conn, audio_data)
|
|
||||||
# 清理音频缓存
|
|
||||||
conn.asr_audio.clear()
|
|
||||||
conn.reset_vad_states()
|
|
||||||
break
|
break
|
||||||
|
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
|
|
@ -262,15 +254,11 @@ class ASRProvider(ASRProviderBase):
|
||||||
finally:
|
finally:
|
||||||
# 清理连接资源
|
# 清理连接资源
|
||||||
await self._cleanup()
|
await self._cleanup()
|
||||||
|
conn.reset_audio_states()
|
||||||
|
|
||||||
# 清理连接的音频缓存
|
async def handle_voice_stop(
|
||||||
if conn:
|
self, conn: "ConnectionHandler", asr_audio_task: List[bytes]
|
||||||
if hasattr(conn, "asr_audio_for_voiceprint"):
|
):
|
||||||
conn.asr_audio_for_voiceprint = []
|
|
||||||
if hasattr(conn, "asr_audio"):
|
|
||||||
conn.asr_audio = []
|
|
||||||
|
|
||||||
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
|
|
||||||
"""处理语音停止,发送最后一帧并处理识别结果"""
|
"""处理语音停止,发送最后一帧并处理识别结果"""
|
||||||
try:
|
try:
|
||||||
# 先发送最后一帧表示音频结束
|
# 先发送最后一帧表示音频结束
|
||||||
|
|
@ -334,7 +322,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
|
|
||||||
logger.bind(tag=TAG).debug("ASR会话清理完成")
|
logger.bind(tag=TAG).debug("ASR会话清理完成")
|
||||||
|
|
||||||
async def speech_to_text(self, opus_data, session_id, audio_format):
|
async def speech_to_text(self, opus_data, session_id, audio_format, artifacts=None):
|
||||||
"""获取识别结果"""
|
"""获取识别结果"""
|
||||||
result = self.text
|
result = self.text
|
||||||
self.text = ""
|
self.text = ""
|
||||||
|
|
@ -355,7 +343,7 @@ class ASRProvider(ASRProviderBase):
|
||||||
self.is_processing = False
|
self.is_processing = False
|
||||||
|
|
||||||
# 显式释放decoder资源
|
# 显式释放decoder资源
|
||||||
if hasattr(self, 'decoder') and self.decoder is not None:
|
if hasattr(self, "decoder") and self.decoder is not None:
|
||||||
try:
|
try:
|
||||||
del self.decoder
|
del self.decoder
|
||||||
self.decoder = None
|
self.decoder = None
|
||||||
|
|
@ -363,10 +351,3 @@ class ASRProvider(ASRProviderBase):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).debug(f"释放Xunfei decoder资源时出错: {e}")
|
logger.bind(tag=TAG).debug(f"释放Xunfei decoder资源时出错: {e}")
|
||||||
|
|
||||||
# 清理所有连接的音频缓冲区
|
|
||||||
if hasattr(self, "_connections"):
|
|
||||||
for conn in self._connections.values():
|
|
||||||
if hasattr(conn, "asr_audio_for_voiceprint"):
|
|
||||||
conn.asr_audio_for_voiceprint = []
|
|
||||||
if hasattr(conn, "asr_audio"):
|
|
||||||
conn.asr_audio = []
|
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,18 @@
|
||||||
from typing import List, Dict
|
from typing import List, Dict, TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from ..base import IntentProviderBase
|
from ..base import IntentProviderBase
|
||||||
from plugins_func.functions.play_music import initialize_music_handler
|
from plugins_func.functions.play_music import initialize_music_handler
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
from core.utils.util import get_system_error_response
|
||||||
import re
|
import re
|
||||||
import json
|
import json
|
||||||
import hashlib
|
import hashlib
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
@ -115,14 +121,20 @@ class IntentProvider(IntentProviderBase):
|
||||||
return prompt
|
return prompt
|
||||||
|
|
||||||
def replyResult(self, text: str, original_text: str):
|
def replyResult(self, text: str, original_text: str):
|
||||||
llm_result = self.llm.response_no_stream(
|
try:
|
||||||
system_prompt=text,
|
llm_result = self.llm.response_no_stream(
|
||||||
user_prompt="请根据以上内容,像人类一样说话的口吻回复用户,要求简洁,请直接返回结果。用户现在说:"
|
system_prompt=text,
|
||||||
+ original_text,
|
user_prompt="请根据以上内容,像人类一样说话的口吻回复用户,要求简洁,请直接返回结果。用户现在说:"
|
||||||
)
|
+ original_text,
|
||||||
return llm_result
|
)
|
||||||
|
return llm_result
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"Error in generating reply result: {e}")
|
||||||
|
return get_system_error_response(self.config)
|
||||||
|
|
||||||
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
|
async def detect_intent(
|
||||||
|
self, conn: "ConnectionHandler", dialogue_history: List[Dict], text: str
|
||||||
|
) -> str:
|
||||||
if not self.llm:
|
if not self.llm:
|
||||||
raise ValueError("LLM provider not set")
|
raise ValueError("LLM provider not set")
|
||||||
if conn.func_handler is None:
|
if conn.func_handler is None:
|
||||||
|
|
@ -194,9 +206,13 @@ class IntentProvider(IntentProviderBase):
|
||||||
llm_start_time = time.time()
|
llm_start_time = time.time()
|
||||||
logger.bind(tag=TAG).debug(f"开始LLM意图识别调用, 模型: {model_info}")
|
logger.bind(tag=TAG).debug(f"开始LLM意图识别调用, 模型: {model_info}")
|
||||||
|
|
||||||
intent = self.llm.response_no_stream(
|
try:
|
||||||
system_prompt=prompt_music, user_prompt=user_prompt
|
intent = self.llm.response_no_stream(
|
||||||
)
|
system_prompt=prompt_music, user_prompt=user_prompt
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"Error in intent detection LLM call: {e}")
|
||||||
|
return '{"function_call": {"name": "continue_chat"}}'
|
||||||
|
|
||||||
# 记录LLM调用完成时间
|
# 记录LLM调用完成时间
|
||||||
llm_time = time.time() - llm_start_time
|
llm_time = time.time() - llm_start_time
|
||||||
|
|
|
||||||
|
|
@ -21,83 +21,78 @@ class LLMProvider(LLMProviderBase):
|
||||||
check_model_key("AliBLLLM", self.api_key)
|
check_model_key("AliBLLLM", self.api_key)
|
||||||
|
|
||||||
def response(self, session_id, dialogue):
|
def response(self, session_id, dialogue):
|
||||||
try:
|
# 处理dialogue
|
||||||
# 处理dialogue
|
if self.is_No_prompt:
|
||||||
if self.is_No_prompt:
|
dialogue.pop(0)
|
||||||
dialogue.pop(0)
|
|
||||||
logger.bind(tag=TAG).debug(
|
|
||||||
f"【阿里百练API服务】处理后的dialogue: {dialogue}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 构造调用参数
|
|
||||||
call_params = {
|
|
||||||
"api_key": self.api_key,
|
|
||||||
"app_id": self.app_id,
|
|
||||||
"session_id": session_id,
|
|
||||||
"messages": dialogue,
|
|
||||||
# 开启SDK原生流式
|
|
||||||
"stream": True,
|
|
||||||
}
|
|
||||||
if self.memory_id != False:
|
|
||||||
# 百练memory需要prompt参数
|
|
||||||
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}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 可选地设置自定义API基地址(若配置为兼容模式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时返回可迭代对象;否则返回单次响应对象)
|
|
||||||
logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).debug(
|
||||||
f"【阿里百练API服务】构造参数: {dict(call_params, api_key='***')}"
|
f"【阿里百练API服务】处理后的dialogue: {dialogue}"
|
||||||
)
|
)
|
||||||
|
|
||||||
last_text = ""
|
# 构造调用参数
|
||||||
try:
|
call_params = {
|
||||||
for resp in responses:
|
"api_key": self.api_key,
|
||||||
if resp.status_code != HTTPStatus.OK:
|
"app_id": self.app_id,
|
||||||
logger.bind(tag=TAG).error(
|
"session_id": session_id,
|
||||||
f"code={resp.status_code}, message={resp.message}, 请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code"
|
"messages": dialogue,
|
||||||
)
|
# 开启SDK原生流式
|
||||||
continue
|
"stream": True,
|
||||||
current_text = getattr(getattr(resp, "output", None), "text", None)
|
}
|
||||||
if current_text is None:
|
if self.memory_id != False:
|
||||||
continue
|
# 百练memory需要prompt参数
|
||||||
# SDK流式为增量覆盖,计算差量输出
|
prompt = dialogue[-1].get("content")
|
||||||
if len(current_text) >= len(last_text):
|
call_params["memory_id"] = self.memory_id
|
||||||
delta = current_text[len(last_text):]
|
call_params["prompt"] = prompt
|
||||||
else:
|
logger.bind(tag=TAG).debug(
|
||||||
# 避免偶发回退
|
f"【阿里百练API服务】处理后的prompt: {prompt}"
|
||||||
delta = current_text
|
)
|
||||||
if delta:
|
|
||||||
yield delta
|
|
||||||
last_text = current_text
|
|
||||||
except TypeError:
|
|
||||||
# 非流式回落(一次性返回)
|
|
||||||
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"
|
|
||||||
)
|
|
||||||
yield "【阿里百练API服务响应异常】"
|
|
||||||
else:
|
|
||||||
full_text = getattr(getattr(responses, "output", None), "text", "")
|
|
||||||
logger.bind(tag=TAG).info(
|
|
||||||
f"【阿里百练API服务】完整响应长度: {len(full_text)}"
|
|
||||||
)
|
|
||||||
for i in range(0, len(full_text), self.streaming_chunk_size):
|
|
||||||
chunk = full_text[i:i + self.streaming_chunk_size]
|
|
||||||
if chunk:
|
|
||||||
yield chunk
|
|
||||||
|
|
||||||
except Exception as e:
|
# 可选地设置自定义API基地址(若配置为兼容模式URL则忽略)
|
||||||
logger.bind(tag=TAG).error(f"【阿里百练API服务】响应异常: {e}")
|
if self.base_url and ("/api/" in self.base_url):
|
||||||
yield "【LLM服务响应异常】"
|
dashscope.base_http_api_url = self.base_url
|
||||||
|
|
||||||
|
responses = Application.call(**call_params)
|
||||||
|
|
||||||
|
# 流式处理(SDK在stream=True时返回可迭代对象;否则返回单次响应对象)
|
||||||
|
logger.bind(tag=TAG).debug(
|
||||||
|
f"【阿里百练API服务】构造参数: {dict(call_params, api_key='***')}"
|
||||||
|
)
|
||||||
|
|
||||||
|
last_text = ""
|
||||||
|
try:
|
||||||
|
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"
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
current_text = getattr(getattr(resp, "output", None), "text", None)
|
||||||
|
if current_text is None:
|
||||||
|
continue
|
||||||
|
# SDK流式为增量覆盖,计算差量输出
|
||||||
|
if len(current_text) >= len(last_text):
|
||||||
|
delta = current_text[len(last_text):]
|
||||||
|
else:
|
||||||
|
# 避免偶发回退
|
||||||
|
delta = current_text
|
||||||
|
if delta:
|
||||||
|
yield delta
|
||||||
|
last_text = current_text
|
||||||
|
except TypeError:
|
||||||
|
# 非流式回落(一次性返回)
|
||||||
|
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"
|
||||||
|
)
|
||||||
|
yield "【阿里百练API服务响应异常】"
|
||||||
|
else:
|
||||||
|
full_text = getattr(getattr(responses, "output", None), "text", "")
|
||||||
|
logger.bind(tag=TAG).info(
|
||||||
|
f"【阿里百练API服务】完整响应长度: {len(full_text)}"
|
||||||
|
)
|
||||||
|
for i in range(0, len(full_text), self.streaming_chunk_size):
|
||||||
|
chunk = full_text[i:i + self.streaming_chunk_size]
|
||||||
|
if chunk:
|
||||||
|
yield chunk
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
# 阿里百练当前未支持原生的 function call。为保持兼容,这里回退到普通文本流式输出。
|
# 阿里百练当前未支持原生的 function call。为保持兼容,这里回退到普通文本流式输出。
|
||||||
|
|
|
||||||
|
|
@ -11,20 +11,15 @@ class LLMProviderBase(ABC):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def response_no_stream(self, system_prompt, user_prompt, **kwargs):
|
def response_no_stream(self, system_prompt, user_prompt, **kwargs):
|
||||||
try:
|
# 构造对话格式
|
||||||
# 构造对话格式
|
dialogue = [
|
||||||
dialogue = [
|
{"role": "system", "content": system_prompt},
|
||||||
{"role": "system", "content": system_prompt},
|
{"role": "user", "content": user_prompt}
|
||||||
{"role": "user", "content": user_prompt}
|
]
|
||||||
]
|
result = ""
|
||||||
result = ""
|
for part in self.response("", dialogue, **kwargs):
|
||||||
for part in self.response("", dialogue, **kwargs):
|
result += part
|
||||||
result += part
|
return result
|
||||||
return result
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}")
|
|
||||||
return "【LLM服务响应异常】"
|
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
"""
|
"""
|
||||||
|
|
|
||||||
|
|
@ -20,76 +20,71 @@ class LLMProvider(LLMProviderBase):
|
||||||
logger.bind(tag=TAG).error(model_key_msg)
|
logger.bind(tag=TAG).error(model_key_msg)
|
||||||
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
try:
|
# 取最后一条用户消息
|
||||||
# 取最后一条用户消息
|
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
|
||||||
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
|
conversation_id = self.session_conversation_map.get(session_id)
|
||||||
conversation_id = self.session_conversation_map.get(session_id)
|
|
||||||
|
|
||||||
# 发起流式请求
|
# 发起流式请求
|
||||||
|
if self.mode == "chat-messages":
|
||||||
|
request_json = {
|
||||||
|
"query": last_msg["content"],
|
||||||
|
"response_mode": "streaming",
|
||||||
|
"user": session_id,
|
||||||
|
"inputs": {},
|
||||||
|
"conversation_id": conversation_id,
|
||||||
|
}
|
||||||
|
elif self.mode == "workflows/run":
|
||||||
|
request_json = {
|
||||||
|
"inputs": {"query": last_msg["content"]},
|
||||||
|
"response_mode": "streaming",
|
||||||
|
"user": session_id,
|
||||||
|
}
|
||||||
|
elif self.mode == "completion-messages":
|
||||||
|
request_json = {
|
||||||
|
"inputs": {"query": last_msg["content"]},
|
||||||
|
"response_mode": "streaming",
|
||||||
|
"user": session_id,
|
||||||
|
}
|
||||||
|
|
||||||
|
with requests.post(
|
||||||
|
f"{self.base_url}/{self.mode}",
|
||||||
|
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||||
|
json=request_json,
|
||||||
|
stream=True,
|
||||||
|
) as r:
|
||||||
if self.mode == "chat-messages":
|
if self.mode == "chat-messages":
|
||||||
request_json = {
|
for line in r.iter_lines():
|
||||||
"query": last_msg["content"],
|
if line.startswith(b"data: "):
|
||||||
"response_mode": "streaming",
|
event = json.loads(line[6:])
|
||||||
"user": session_id,
|
# 如果没有找到conversation_id,则获取此次conversation_id
|
||||||
"inputs": {},
|
if not conversation_id:
|
||||||
"conversation_id": conversation_id,
|
conversation_id = event.get("conversation_id")
|
||||||
}
|
self.session_conversation_map[session_id] = (
|
||||||
|
conversation_id # 更新映射
|
||||||
|
)
|
||||||
|
# 过滤 message_replace 事件,此事件会全量推一次
|
||||||
|
if event.get("event") != "message_replace" and event.get(
|
||||||
|
"answer"
|
||||||
|
):
|
||||||
|
yield event["answer"]
|
||||||
elif self.mode == "workflows/run":
|
elif self.mode == "workflows/run":
|
||||||
request_json = {
|
for line in r.iter_lines():
|
||||||
"inputs": {"query": last_msg["content"]},
|
if line.startswith(b"data: "):
|
||||||
"response_mode": "streaming",
|
event = json.loads(line[6:])
|
||||||
"user": session_id,
|
if event.get("event") == "workflow_finished":
|
||||||
}
|
if event["data"]["status"] == "succeeded":
|
||||||
|
yield event["data"]["outputs"]["answer"]
|
||||||
|
else:
|
||||||
|
yield "【服务响应异常】"
|
||||||
elif self.mode == "completion-messages":
|
elif self.mode == "completion-messages":
|
||||||
request_json = {
|
for line in r.iter_lines():
|
||||||
"inputs": {"query": last_msg["content"]},
|
if line.startswith(b"data: "):
|
||||||
"response_mode": "streaming",
|
event = json.loads(line[6:])
|
||||||
"user": session_id,
|
# 过滤 message_replace 事件,此事件会全量推一次
|
||||||
}
|
if event.get("event") != "message_replace" and event.get(
|
||||||
|
"answer"
|
||||||
with requests.post(
|
):
|
||||||
f"{self.base_url}/{self.mode}",
|
yield event["answer"]
|
||||||
headers={"Authorization": f"Bearer {self.api_key}"},
|
|
||||||
json=request_json,
|
|
||||||
stream=True,
|
|
||||||
) as r:
|
|
||||||
if self.mode == "chat-messages":
|
|
||||||
for line in r.iter_lines():
|
|
||||||
if line.startswith(b"data: "):
|
|
||||||
event = json.loads(line[6:])
|
|
||||||
# 如果没有找到conversation_id,则获取此次conversation_id
|
|
||||||
if not conversation_id:
|
|
||||||
conversation_id = event.get("conversation_id")
|
|
||||||
self.session_conversation_map[session_id] = (
|
|
||||||
conversation_id # 更新映射
|
|
||||||
)
|
|
||||||
# 过滤 message_replace 事件,此事件会全量推一次
|
|
||||||
if event.get("event") != "message_replace" and event.get(
|
|
||||||
"answer"
|
|
||||||
):
|
|
||||||
yield event["answer"]
|
|
||||||
elif self.mode == "workflows/run":
|
|
||||||
for line in r.iter_lines():
|
|
||||||
if line.startswith(b"data: "):
|
|
||||||
event = json.loads(line[6:])
|
|
||||||
if event.get("event") == "workflow_finished":
|
|
||||||
if event["data"]["status"] == "succeeded":
|
|
||||||
yield event["data"]["outputs"]["answer"]
|
|
||||||
else:
|
|
||||||
yield "【服务响应异常】"
|
|
||||||
elif self.mode == "completion-messages":
|
|
||||||
for line in r.iter_lines():
|
|
||||||
if line.startswith(b"data: "):
|
|
||||||
event = json.loads(line[6:])
|
|
||||||
# 过滤 message_replace 事件,此事件会全量推一次
|
|
||||||
if event.get("event") != "message_replace" and event.get(
|
|
||||||
"answer"
|
|
||||||
):
|
|
||||||
yield event["answer"]
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
|
|
||||||
yield "【服务响应异常】"
|
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
|
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
|
||||||
|
|
|
||||||
|
|
@ -19,53 +19,48 @@ class LLMProvider(LLMProviderBase):
|
||||||
logger.bind(tag=TAG).error(model_key_msg)
|
logger.bind(tag=TAG).error(model_key_msg)
|
||||||
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
try:
|
# 取最后一条用户消息
|
||||||
# 取最后一条用户消息
|
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
|
||||||
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
|
|
||||||
|
|
||||||
# 发起流式请求
|
# 发起流式请求
|
||||||
with requests.post(
|
with requests.post(
|
||||||
f"{self.base_url}/chat/completions",
|
f"{self.base_url}/chat/completions",
|
||||||
headers={"Authorization": f"Bearer {self.api_key}"},
|
headers={"Authorization": f"Bearer {self.api_key}"},
|
||||||
json={
|
json={
|
||||||
"stream": True,
|
"stream": True,
|
||||||
"chatId": session_id,
|
"chatId": session_id,
|
||||||
"detail": self.detail,
|
"detail": self.detail,
|
||||||
"variables": self.variables,
|
"variables": self.variables,
|
||||||
"messages": [{"role": "user", "content": last_msg["content"]}],
|
"messages": [{"role": "user", "content": last_msg["content"]}],
|
||||||
},
|
},
|
||||||
stream=True,
|
stream=True,
|
||||||
) as r:
|
) as r:
|
||||||
for line in r.iter_lines():
|
for line in r.iter_lines():
|
||||||
if line:
|
if line:
|
||||||
try:
|
try:
|
||||||
if line.startswith(b"data: "):
|
if line.startswith(b"data: "):
|
||||||
if line[6:].decode("utf-8") == "[DONE]":
|
if line[6:].decode("utf-8") == "[DONE]":
|
||||||
break
|
break
|
||||||
|
|
||||||
data = json.loads(line[6:])
|
data = json.loads(line[6:])
|
||||||
if "choices" in data and len(data["choices"]) > 0:
|
if "choices" in data and len(data["choices"]) > 0:
|
||||||
delta = data["choices"][0].get("delta", {})
|
delta = data["choices"][0].get("delta", {})
|
||||||
if (
|
if (
|
||||||
delta
|
delta
|
||||||
and "content" in delta
|
and "content" in delta
|
||||||
and delta["content"] is not None
|
and delta["content"] is not None
|
||||||
):
|
):
|
||||||
content = delta["content"]
|
content = delta["content"]
|
||||||
if "<think>" in content:
|
if "<think>" in content:
|
||||||
continue
|
continue
|
||||||
if "</think>" in content:
|
if "</think>" in content:
|
||||||
continue
|
continue
|
||||||
yield content
|
yield content
|
||||||
|
|
||||||
except json.JSONDecodeError as e:
|
except json.JSONDecodeError as e:
|
||||||
continue
|
continue
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
|
|
||||||
yield "【服务响应异常】"
|
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
|
|
|
||||||
|
|
@ -15,55 +15,49 @@ class LLMProvider(LLMProviderBase):
|
||||||
self.api_url = f"{self.base_url}/api/conversation/process" # 拼接完整的 API URL
|
self.api_url = f"{self.base_url}/api/conversation/process" # 拼接完整的 API URL
|
||||||
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
try:
|
# home assistant语音助手自带意图,无需使用xiaozhi ai自带的,只需要把用户说的话传递给home assistant即可
|
||||||
# home assistant语音助手自带意图,无需使用xiaozhi ai自带的,只需要把用户说的话传递给home assistant即可
|
|
||||||
|
|
||||||
# 提取最后一个 role 为 'user' 的 content
|
# 提取最后一个 role 为 'user' 的 content
|
||||||
input_text = None
|
input_text = None
|
||||||
if isinstance(dialogue, list): # 确保 dialogue 是一个列表
|
if isinstance(dialogue, list): # 确保 dialogue 是一个列表
|
||||||
# 逆序遍历,找到最后一个 role 为 'user' 的消息
|
# 逆序遍历,找到最后一个 role 为 'user' 的消息
|
||||||
for message in reversed(dialogue):
|
for message in reversed(dialogue):
|
||||||
if message.get("role") == "user": # 找到 role 为 'user' 的消息
|
if message.get("role") == "user": # 找到 role 为 'user' 的消息
|
||||||
input_text = message.get("content", "")
|
input_text = message.get("content", "")
|
||||||
break # 找到后立即退出循环
|
break # 找到后立即退出循环
|
||||||
|
|
||||||
# 构造请求数据
|
# 构造请求数据
|
||||||
payload = {
|
payload = {
|
||||||
"text": input_text,
|
"text": input_text,
|
||||||
"agent_id": self.agent_id,
|
"agent_id": self.agent_id,
|
||||||
"conversation_id": session_id, # 使用 session_id 作为 conversation_id
|
"conversation_id": session_id, # 使用 session_id 作为 conversation_id
|
||||||
}
|
}
|
||||||
# 设置请求头
|
# 设置请求头
|
||||||
headers = {
|
headers = {
|
||||||
"Authorization": f"Bearer {self.api_key}",
|
"Authorization": f"Bearer {self.api_key}",
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
}
|
}
|
||||||
|
|
||||||
# 发起 POST 请求
|
# 发起 POST 请求
|
||||||
response = requests.post(self.api_url, json=payload, headers=headers)
|
response = requests.post(self.api_url, json=payload, headers=headers)
|
||||||
|
|
||||||
# 检查请求是否成功
|
# 检查请求是否成功
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|
||||||
# 解析返回数据
|
# 解析返回数据
|
||||||
data = response.json()
|
data = response.json()
|
||||||
speech = (
|
speech = (
|
||||||
data.get("response", {})
|
data.get("response", {})
|
||||||
.get("speech", {})
|
.get("speech", {})
|
||||||
.get("plain", {})
|
.get("plain", {})
|
||||||
.get("speech", "")
|
.get("speech", "")
|
||||||
)
|
)
|
||||||
|
|
||||||
# 返回生成的内容
|
# 返回生成的内容
|
||||||
if speech:
|
if speech:
|
||||||
yield speech
|
yield speech
|
||||||
else:
|
else:
|
||||||
logger.bind(tag=TAG).warning("API 返回数据中没有 speech 内容")
|
logger.bind(tag=TAG).warning("API 返回数据中没有 speech 内容")
|
||||||
|
|
||||||
except RequestException as e:
|
|
||||||
logger.bind(tag=TAG).error(f"HTTP 请求错误: {e}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"生成响应时出错: {e}")
|
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
logger.bind(tag=TAG).error(
|
logger.bind(tag=TAG).error(
|
||||||
|
|
|
||||||
|
|
@ -25,151 +25,141 @@ class LLMProvider(LLMProviderBase):
|
||||||
self.is_qwen3 = self.model_name and self.model_name.lower().startswith("qwen3")
|
self.is_qwen3 = self.model_name and self.model_name.lower().startswith("qwen3")
|
||||||
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
try:
|
# 如果是qwen3模型,在用户最后一条消息中添加/no_think指令
|
||||||
# 如果是qwen3模型,在用户最后一条消息中添加/no_think指令
|
if self.is_qwen3:
|
||||||
if self.is_qwen3:
|
# 复制对话列表,避免修改原始对话
|
||||||
# 复制对话列表,避免修改原始对话
|
dialogue_copy = dialogue.copy()
|
||||||
dialogue_copy = dialogue.copy()
|
|
||||||
|
|
||||||
# 找到最后一条用户消息
|
# 找到最后一条用户消息
|
||||||
for i in range(len(dialogue_copy) - 1, -1, -1):
|
for i in range(len(dialogue_copy) - 1, -1, -1):
|
||||||
if dialogue_copy[i]["role"] == "user":
|
if dialogue_copy[i]["role"] == "user":
|
||||||
# 在用户消息前添加/no_think指令
|
# 在用户消息前添加/no_think指令
|
||||||
dialogue_copy[i]["content"] = (
|
dialogue_copy[i]["content"] = (
|
||||||
"/no_think " + dialogue_copy[i]["content"]
|
"/no_think " + dialogue_copy[i]["content"]
|
||||||
)
|
|
||||||
logger.bind(tag=TAG).debug(f"为qwen3模型添加/no_think指令")
|
|
||||||
break
|
|
||||||
|
|
||||||
# 使用修改后的对话
|
|
||||||
dialogue = dialogue_copy
|
|
||||||
|
|
||||||
responses = self.client.chat.completions.create(
|
|
||||||
model=self.model_name, messages=dialogue, stream=True
|
|
||||||
)
|
|
||||||
is_active = True
|
|
||||||
# 用于处理跨chunk的标签
|
|
||||||
buffer = ""
|
|
||||||
|
|
||||||
for chunk in responses:
|
|
||||||
try:
|
|
||||||
delta = (
|
|
||||||
chunk.choices[0].delta
|
|
||||||
if getattr(chunk, "choices", None)
|
|
||||||
else None
|
|
||||||
)
|
)
|
||||||
content = delta.content if hasattr(delta, "content") else ""
|
logger.bind(tag=TAG).debug(f"为qwen3模型添加/no_think指令")
|
||||||
|
break
|
||||||
|
|
||||||
if content:
|
# 使用修改后的对话
|
||||||
# 将内容添加到缓冲区
|
dialogue = dialogue_copy
|
||||||
buffer += content
|
|
||||||
|
|
||||||
# 处理缓冲区中的标签
|
responses = self.client.chat.completions.create(
|
||||||
while "<think>" in buffer and "</think>" in buffer:
|
model=self.model_name, messages=dialogue, stream=True
|
||||||
# 找到完整的<think></think>标签并移除
|
)
|
||||||
pre = buffer.split("<think>", 1)[0]
|
is_active = True
|
||||||
post = buffer.split("</think>", 1)[1]
|
# 用于处理跨chunk的标签
|
||||||
buffer = pre + post
|
buffer = ""
|
||||||
|
|
||||||
# 处理只有开始标签的情况
|
for chunk in responses:
|
||||||
if "<think>" in buffer:
|
try:
|
||||||
is_active = False
|
delta = (
|
||||||
buffer = buffer.split("<think>", 1)[0]
|
chunk.choices[0].delta
|
||||||
|
if getattr(chunk, "choices", None)
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
content = delta.content if hasattr(delta, "content") else ""
|
||||||
|
|
||||||
# 处理只有结束标签的情况
|
if content:
|
||||||
if "</think>" in buffer:
|
# 将内容添加到缓冲区
|
||||||
is_active = True
|
buffer += content
|
||||||
buffer = buffer.split("</think>", 1)[1]
|
|
||||||
|
|
||||||
# 如果当前处于活动状态且缓冲区有内容,则输出
|
# 处理缓冲区中的标签
|
||||||
if is_active and buffer:
|
while "<think>" in buffer and "</think>" in buffer:
|
||||||
yield buffer
|
# 找到完整的<think></think>标签并移除
|
||||||
buffer = "" # 清空缓冲区
|
pre = buffer.split("<think>", 1)[0]
|
||||||
|
post = buffer.split("</think>", 1)[1]
|
||||||
|
buffer = pre + post
|
||||||
|
|
||||||
except Exception as e:
|
# 处理只有开始标签的情况
|
||||||
logger.bind(tag=TAG).error(f"Error processing chunk: {e}")
|
if "<think>" in buffer:
|
||||||
|
is_active = False
|
||||||
|
buffer = buffer.split("<think>", 1)[0]
|
||||||
|
|
||||||
except Exception as e:
|
# 处理只有结束标签的情况
|
||||||
logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}")
|
if "</think>" in buffer:
|
||||||
yield "【Ollama服务响应异常】"
|
is_active = True
|
||||||
|
buffer = buffer.split("</think>", 1)[1]
|
||||||
|
|
||||||
|
# 如果当前处于活动状态且缓冲区有内容,则输出
|
||||||
|
if is_active and buffer:
|
||||||
|
yield buffer
|
||||||
|
buffer = "" # 清空缓冲区
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"Error processing chunk: {e}")
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
try:
|
# 如果是qwen3模型,在用户最后一条消息中添加/no_think指令
|
||||||
# 如果是qwen3模型,在用户最后一条消息中添加/no_think指令
|
if self.is_qwen3:
|
||||||
if self.is_qwen3:
|
# 复制对话列表,避免修改原始对话
|
||||||
# 复制对话列表,避免修改原始对话
|
dialogue_copy = dialogue.copy()
|
||||||
dialogue_copy = dialogue.copy()
|
|
||||||
|
|
||||||
# 找到最后一条用户消息
|
# 找到最后一条用户消息
|
||||||
for i in range(len(dialogue_copy) - 1, -1, -1):
|
for i in range(len(dialogue_copy) - 1, -1, -1):
|
||||||
if dialogue_copy[i]["role"] == "user":
|
if dialogue_copy[i]["role"] == "user":
|
||||||
# 在用户消息前添加/no_think指令
|
# 在用户消息前添加/no_think指令
|
||||||
dialogue_copy[i]["content"] = (
|
dialogue_copy[i]["content"] = (
|
||||||
"/no_think " + dialogue_copy[i]["content"]
|
"/no_think " + dialogue_copy[i]["content"]
|
||||||
)
|
|
||||||
logger.bind(tag=TAG).debug(f"为qwen3模型添加/no_think指令")
|
|
||||||
break
|
|
||||||
|
|
||||||
# 使用修改后的对话
|
|
||||||
dialogue = dialogue_copy
|
|
||||||
|
|
||||||
stream = self.client.chat.completions.create(
|
|
||||||
model=self.model_name,
|
|
||||||
messages=dialogue,
|
|
||||||
stream=True,
|
|
||||||
tools=functions,
|
|
||||||
)
|
|
||||||
|
|
||||||
is_active = True
|
|
||||||
buffer = ""
|
|
||||||
|
|
||||||
for chunk in stream:
|
|
||||||
try:
|
|
||||||
delta = (
|
|
||||||
chunk.choices[0].delta
|
|
||||||
if getattr(chunk, "choices", None)
|
|
||||||
else None
|
|
||||||
)
|
|
||||||
content = delta.content if hasattr(delta, "content") else None
|
|
||||||
tool_calls = (
|
|
||||||
delta.tool_calls if hasattr(delta, "tool_calls") else None
|
|
||||||
)
|
)
|
||||||
|
logger.bind(tag=TAG).debug(f"为qwen3模型添加/no_think指令")
|
||||||
|
break
|
||||||
|
|
||||||
# 如果是工具调用,直接传递
|
# 使用修改后的对话
|
||||||
if tool_calls:
|
dialogue = dialogue_copy
|
||||||
yield None, tool_calls
|
|
||||||
continue
|
|
||||||
|
|
||||||
# 处理文本内容
|
stream = self.client.chat.completions.create(
|
||||||
if content:
|
model=self.model_name,
|
||||||
# 将内容添加到缓冲区
|
messages=dialogue,
|
||||||
buffer += content
|
stream=True,
|
||||||
|
tools=functions,
|
||||||
|
)
|
||||||
|
|
||||||
# 处理缓冲区中的标签
|
is_active = True
|
||||||
while "<think>" in buffer and "</think>" in buffer:
|
buffer = ""
|
||||||
# 找到完整的<think></think>标签并移除
|
|
||||||
pre = buffer.split("<think>", 1)[0]
|
|
||||||
post = buffer.split("</think>", 1)[1]
|
|
||||||
buffer = pre + post
|
|
||||||
|
|
||||||
# 处理只有开始标签的情况
|
for chunk in stream:
|
||||||
if "<think>" in buffer:
|
try:
|
||||||
is_active = False
|
delta = (
|
||||||
buffer = buffer.split("<think>", 1)[0]
|
chunk.choices[0].delta
|
||||||
|
if getattr(chunk, "choices", None)
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
content = delta.content if hasattr(delta, "content") else None
|
||||||
|
tool_calls = (
|
||||||
|
delta.tool_calls if hasattr(delta, "tool_calls") else None
|
||||||
|
)
|
||||||
|
|
||||||
# 处理只有结束标签的情况
|
# 如果是工具调用,直接传递
|
||||||
if "</think>" in buffer:
|
if tool_calls:
|
||||||
is_active = True
|
yield None, tool_calls
|
||||||
buffer = buffer.split("</think>", 1)[1]
|
|
||||||
|
|
||||||
# 如果当前处于活动状态且缓冲区有内容,则输出
|
|
||||||
if is_active and buffer:
|
|
||||||
yield buffer, None
|
|
||||||
buffer = "" # 清空缓冲区
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"Error processing function chunk: {e}")
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
except Exception as e:
|
# 处理文本内容
|
||||||
logger.bind(tag=TAG).error(f"Error in Ollama function call: {e}")
|
if content:
|
||||||
yield f"【Ollama服务响应异常: {str(e)}】", None
|
# 将内容添加到缓冲区
|
||||||
|
buffer += content
|
||||||
|
|
||||||
|
# 处理缓冲区中的标签
|
||||||
|
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
|
||||||
|
|
||||||
|
# 处理只有开始标签的情况
|
||||||
|
if "<think>" in buffer:
|
||||||
|
is_active = False
|
||||||
|
buffer = buffer.split("<think>", 1)[0]
|
||||||
|
|
||||||
|
# 处理只有结束标签的情况
|
||||||
|
if "</think>" in buffer:
|
||||||
|
is_active = True
|
||||||
|
buffer = buffer.split("</think>", 1)[1]
|
||||||
|
|
||||||
|
# 如果当前处于活动状态且缓冲区有内容,则输出
|
||||||
|
if is_active and buffer:
|
||||||
|
yield buffer, None
|
||||||
|
buffer = "" # 清空缓冲区
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"Error processing function chunk: {e}")
|
||||||
|
continue
|
||||||
|
|
|
||||||
|
|
@ -56,87 +56,78 @@ class LLMProvider(LLMProviderBase):
|
||||||
return dialogue
|
return dialogue
|
||||||
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
try:
|
dialogue = self.normalize_dialogue(dialogue)
|
||||||
dialogue = self.normalize_dialogue(dialogue)
|
|
||||||
|
|
||||||
request_params = {
|
request_params = {
|
||||||
"model": self.model_name,
|
"model": self.model_name,
|
||||||
"messages": dialogue,
|
"messages": dialogue,
|
||||||
"stream": True,
|
"stream": True,
|
||||||
}
|
}
|
||||||
|
|
||||||
# 添加可选参数,只有当参数不为None时才添加
|
# 添加可选参数,只有当参数不为None时才添加
|
||||||
optional_params = {
|
optional_params = {
|
||||||
"max_tokens": kwargs.get("max_tokens", self.max_tokens),
|
"max_tokens": kwargs.get("max_tokens", self.max_tokens),
|
||||||
"temperature": kwargs.get("temperature", self.temperature),
|
"temperature": kwargs.get("temperature", self.temperature),
|
||||||
"top_p": kwargs.get("top_p", self.top_p),
|
"top_p": kwargs.get("top_p", self.top_p),
|
||||||
"frequency_penalty": kwargs.get("frequency_penalty", self.frequency_penalty),
|
"frequency_penalty": kwargs.get("frequency_penalty", self.frequency_penalty),
|
||||||
}
|
}
|
||||||
|
|
||||||
for key, value in optional_params.items():
|
for key, value in optional_params.items():
|
||||||
if value is not None:
|
if value is not None:
|
||||||
request_params[key] = value
|
request_params[key] = value
|
||||||
|
|
||||||
responses = self.client.chat.completions.create(**request_params)
|
responses = self.client.chat.completions.create(**request_params)
|
||||||
|
|
||||||
is_active = True
|
is_active = True
|
||||||
for chunk in responses:
|
for chunk in responses:
|
||||||
try:
|
try:
|
||||||
delta = chunk.choices[0].delta if getattr(chunk, "choices", None) else None
|
delta = chunk.choices[0].delta if getattr(chunk, "choices", None) else None
|
||||||
content = getattr(delta, "content", "") if delta else ""
|
content = getattr(delta, "content", "") if delta else ""
|
||||||
except IndexError:
|
except IndexError:
|
||||||
content = ""
|
content = ""
|
||||||
if content:
|
if content:
|
||||||
if "<think>" in content:
|
if "<think>" in content:
|
||||||
is_active = False
|
is_active = False
|
||||||
content = content.split("<think>")[0]
|
content = content.split("<think>")[0]
|
||||||
if "</think>" in content:
|
if "</think>" in content:
|
||||||
is_active = True
|
is_active = True
|
||||||
content = content.split("</think>")[-1]
|
content = content.split("</think>")[-1]
|
||||||
if is_active:
|
if is_active:
|
||||||
yield content
|
yield content
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
|
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None, **kwargs):
|
def response_with_functions(self, session_id, dialogue, functions=None, **kwargs):
|
||||||
try:
|
dialogue = self.normalize_dialogue(dialogue)
|
||||||
dialogue = self.normalize_dialogue(dialogue)
|
|
||||||
|
|
||||||
request_params = {
|
request_params = {
|
||||||
"model": self.model_name,
|
"model": self.model_name,
|
||||||
"messages": dialogue,
|
"messages": dialogue,
|
||||||
"stream": True,
|
"stream": True,
|
||||||
"tools": functions,
|
"tools": functions,
|
||||||
}
|
}
|
||||||
|
|
||||||
optional_params = {
|
optional_params = {
|
||||||
"max_tokens": kwargs.get("max_tokens", self.max_tokens),
|
"max_tokens": kwargs.get("max_tokens", self.max_tokens),
|
||||||
"temperature": kwargs.get("temperature", self.temperature),
|
"temperature": kwargs.get("temperature", self.temperature),
|
||||||
"top_p": kwargs.get("top_p", self.top_p),
|
"top_p": kwargs.get("top_p", self.top_p),
|
||||||
"frequency_penalty": kwargs.get("frequency_penalty", self.frequency_penalty),
|
"frequency_penalty": kwargs.get("frequency_penalty", self.frequency_penalty),
|
||||||
}
|
}
|
||||||
|
|
||||||
for key, value in optional_params.items():
|
for key, value in optional_params.items():
|
||||||
if value is not None:
|
if value is not None:
|
||||||
request_params[key] = value
|
request_params[key] = value
|
||||||
|
|
||||||
stream = self.client.chat.completions.create(**request_params)
|
stream = self.client.chat.completions.create(**request_params)
|
||||||
|
|
||||||
for chunk in stream:
|
for chunk in stream:
|
||||||
if getattr(chunk, "choices", None):
|
if getattr(chunk, "choices", None):
|
||||||
delta = chunk.choices[0].delta
|
delta = chunk.choices[0].delta
|
||||||
content = getattr(delta, "content", "")
|
content = getattr(delta, "content", "")
|
||||||
tool_calls = getattr(delta, "tool_calls", None)
|
tool_calls = getattr(delta, "tool_calls", None)
|
||||||
yield content, tool_calls
|
yield content, tool_calls
|
||||||
elif isinstance(getattr(chunk, "usage", None), CompletionUsage):
|
elif isinstance(getattr(chunk, "usage", None), CompletionUsage):
|
||||||
usage_info = getattr(chunk, "usage", None)
|
usage_info = getattr(chunk, "usage", None)
|
||||||
logger.bind(tag=TAG).info(
|
logger.bind(tag=TAG).info(
|
||||||
f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')},"
|
f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')},"
|
||||||
f"输出 {getattr(usage_info, 'completion_tokens', '未知')},"
|
f"输出 {getattr(usage_info, 'completion_tokens', '未知')},"
|
||||||
f"共计 {getattr(usage_info, 'total_tokens', '未知')}"
|
f"共计 {getattr(usage_info, 'total_tokens', '未知')}"
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"Error in function call streaming: {e}")
|
|
||||||
yield f"【OpenAI服务响应异常: {e}】", None
|
|
||||||
|
|
|
||||||
|
|
@ -31,68 +31,55 @@ class LLMProvider(LLMProviderBase):
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def response(self, session_id, dialogue, **kwargs):
|
def response(self, session_id, dialogue, **kwargs):
|
||||||
try:
|
logger.bind(tag=TAG).debug(
|
||||||
logger.bind(tag=TAG).debug(
|
f"Sending request to Xinference with model: {self.model_name}, dialogue length: {len(dialogue)}"
|
||||||
f"Sending request to Xinference with model: {self.model_name}, dialogue length: {len(dialogue)}"
|
)
|
||||||
)
|
responses = self.client.chat.completions.create(
|
||||||
responses = self.client.chat.completions.create(
|
model=self.model_name, messages=dialogue, stream=True
|
||||||
model=self.model_name, messages=dialogue, stream=True
|
)
|
||||||
)
|
is_active = True
|
||||||
is_active = True
|
for chunk in responses:
|
||||||
for chunk in responses:
|
try:
|
||||||
try:
|
delta = (
|
||||||
delta = (
|
chunk.choices[0].delta
|
||||||
chunk.choices[0].delta
|
if getattr(chunk, "choices", None)
|
||||||
if getattr(chunk, "choices", None)
|
else None
|
||||||
else None
|
)
|
||||||
)
|
content = delta.content if hasattr(delta, "content") else ""
|
||||||
content = delta.content if hasattr(delta, "content") else ""
|
if content:
|
||||||
if content:
|
if "<think>" in content:
|
||||||
if "<think>" in content:
|
is_active = False
|
||||||
is_active = False
|
content = content.split("<think>")[0]
|
||||||
content = content.split("<think>")[0]
|
if "</think>" in content:
|
||||||
if "</think>" in content:
|
is_active = True
|
||||||
is_active = True
|
content = content.split("</think>")[-1]
|
||||||
content = content.split("</think>")[-1]
|
if is_active:
|
||||||
if is_active:
|
yield content
|
||||||
yield content
|
except Exception as e:
|
||||||
except Exception as e:
|
logger.bind(tag=TAG).error(f"Error processing chunk: {e}")
|
||||||
logger.bind(tag=TAG).error(f"Error processing chunk: {e}")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.bind(tag=TAG).error(f"Error in Xinference response generation: {e}")
|
|
||||||
yield "【Xinference服务响应异常】"
|
|
||||||
|
|
||||||
def response_with_functions(self, session_id, dialogue, functions=None):
|
def response_with_functions(self, session_id, dialogue, functions=None):
|
||||||
try:
|
logger.bind(tag=TAG).debug(
|
||||||
|
f"Sending function call request to Xinference with model: {self.model_name}, dialogue length: {len(dialogue)}"
|
||||||
|
)
|
||||||
|
if functions:
|
||||||
logger.bind(tag=TAG).debug(
|
logger.bind(tag=TAG).debug(
|
||||||
f"Sending function call request to Xinference with model: {self.model_name}, dialogue length: {len(dialogue)}"
|
f"Function calls enabled with: {[f.get('function', {}).get('name') for f in functions]}"
|
||||||
)
|
|
||||||
if functions:
|
|
||||||
logger.bind(tag=TAG).debug(
|
|
||||||
f"Function calls enabled with: {[f.get('function', {}).get('name') for f in functions]}"
|
|
||||||
)
|
|
||||||
|
|
||||||
stream = self.client.chat.completions.create(
|
|
||||||
model=self.model_name,
|
|
||||||
messages=dialogue,
|
|
||||||
stream=True,
|
|
||||||
tools=functions,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
for chunk in stream:
|
stream = self.client.chat.completions.create(
|
||||||
delta = chunk.choices[0].delta
|
model=self.model_name,
|
||||||
content = delta.content
|
messages=dialogue,
|
||||||
tool_calls = delta.tool_calls
|
stream=True,
|
||||||
|
tools=functions,
|
||||||
|
)
|
||||||
|
|
||||||
if content:
|
for chunk in stream:
|
||||||
yield content, tool_calls
|
delta = chunk.choices[0].delta
|
||||||
elif tool_calls:
|
content = delta.content
|
||||||
yield None, tool_calls
|
tool_calls = delta.tool_calls
|
||||||
|
|
||||||
except Exception as e:
|
if content:
|
||||||
logger.bind(tag=TAG).error(f"Error in Xinference function call: {e}")
|
yield content, tool_calls
|
||||||
yield {
|
elif tool_calls:
|
||||||
"type": "content",
|
yield None, tool_calls
|
||||||
"content": f"【Xinference服务响应异常: {str(e)}】",
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
import json
|
||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
from ..base import MemoryProviderBase, logger
|
from ..base import MemoryProviderBase, logger
|
||||||
|
|
@ -36,11 +37,26 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Format the content as a message list for mem0
|
# Format the content as a message list for mem0
|
||||||
messages = [
|
messages = []
|
||||||
{"role": message.role, "content": message.content}
|
for message in msgs:
|
||||||
for message in msgs
|
if message.role == "system":
|
||||||
if message.role != "system"
|
continue
|
||||||
]
|
|
||||||
|
content = message.content
|
||||||
|
|
||||||
|
# Extract content from JSON format if present (for ASR with emotion/language tags)
|
||||||
|
# Same logic as in query_memory method
|
||||||
|
try:
|
||||||
|
if content and content.strip().startswith("{") and content.strip().endswith("}"):
|
||||||
|
data = json.loads(content)
|
||||||
|
if "content" in data:
|
||||||
|
content = data["content"]
|
||||||
|
except (json.JSONDecodeError, KeyError, TypeError):
|
||||||
|
# If parsing fails, use original content
|
||||||
|
pass
|
||||||
|
|
||||||
|
messages.append({"role": message.role, "content": content})
|
||||||
|
|
||||||
result = self.client.add(messages, user_id=self.role_id)
|
result = self.client.add(messages, user_id=self.role_id)
|
||||||
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
|
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
@ -56,7 +72,16 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
|
|
||||||
filters = {"user_id": self.role_id}
|
filters = {"user_id": self.role_id}
|
||||||
|
|
||||||
results = self.client.search(query, filters=filters)
|
search_query = query
|
||||||
|
try:
|
||||||
|
if query.strip().startswith("{") and query.strip().endswith("}"):
|
||||||
|
data = json.loads(query)
|
||||||
|
if "content" in data:
|
||||||
|
search_query = data["content"]
|
||||||
|
except (json.JSONDecodeError, KeyError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
results = self.client.search(search_query, filters=filters)
|
||||||
if not results or "results" not in results:
|
if not results or "results" not in results:
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -149,10 +149,22 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
|
|
||||||
msgStr = ""
|
msgStr = ""
|
||||||
for msg in msgs:
|
for msg in msgs:
|
||||||
|
content = msg.content
|
||||||
|
|
||||||
|
# Extract content from JSON format if present (for ASR with emotion/language tags)
|
||||||
|
try:
|
||||||
|
if content and content.strip().startswith("{") and content.strip().endswith("}"):
|
||||||
|
data = json.loads(content)
|
||||||
|
if "content" in data:
|
||||||
|
content = data["content"]
|
||||||
|
except (json.JSONDecodeError, KeyError, TypeError):
|
||||||
|
# If parsing fails, use original content
|
||||||
|
pass
|
||||||
|
|
||||||
if msg.role == "user":
|
if msg.role == "user":
|
||||||
msgStr += f"User: {msg.content}\n"
|
msgStr += f"User: {content}\n"
|
||||||
elif msg.role == "assistant":
|
elif msg.role == "assistant":
|
||||||
msgStr += f"Assistant: {msg.content}\n"
|
msgStr += f"Assistant: {content}\n"
|
||||||
if self.short_memory and len(self.short_memory) > 0:
|
if self.short_memory and len(self.short_memory) > 0:
|
||||||
msgStr += "历史记忆:\n"
|
msgStr += "历史记忆:\n"
|
||||||
msgStr += self.short_memory
|
msgStr += self.short_memory
|
||||||
|
|
@ -162,19 +174,19 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
msgStr += f"当前时间:{time_str}"
|
msgStr += f"当前时间:{time_str}"
|
||||||
|
|
||||||
if self.save_to_file:
|
if self.save_to_file:
|
||||||
result = self.llm.response_no_stream(
|
|
||||||
short_term_memory_prompt,
|
|
||||||
msgStr,
|
|
||||||
max_tokens=2000,
|
|
||||||
temperature=0.2,
|
|
||||||
)
|
|
||||||
json_str = extract_json_data(result)
|
|
||||||
try:
|
try:
|
||||||
|
result = self.llm.response_no_stream(
|
||||||
|
short_term_memory_prompt,
|
||||||
|
msgStr,
|
||||||
|
max_tokens=2000,
|
||||||
|
temperature=0.2,
|
||||||
|
)
|
||||||
|
json_str = extract_json_data(result)
|
||||||
json.loads(json_str) # 检查json格式是否正确
|
json.loads(json_str) # 检查json格式是否正确
|
||||||
self.short_memory = json_str
|
self.short_memory = json_str
|
||||||
self.save_memory_to_file()
|
self.save_memory_to_file()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("Error:", e)
|
logger.bind(tag=TAG).error(f"Error in saving memory: {e}")
|
||||||
else:
|
else:
|
||||||
# 当save_to_file为False时,调用Java端的聊天记录总结接口
|
# 当save_to_file为False时,调用Java端的聊天记录总结接口
|
||||||
summary_id = session_id if session_id else self.role_id
|
summary_id = session_id if session_id else self.role_id
|
||||||
|
|
|
||||||
346
main/xiaozhi-server/core/providers/memory/powermem/powermem.py
Normal file
346
main/xiaozhi-server/core/providers/memory/powermem/powermem.py
Normal file
|
|
@ -0,0 +1,346 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# -*- coding: UTF-8 -*-
|
||||||
|
"""
|
||||||
|
@time: 2026/01/08
|
||||||
|
@file: powermem.py
|
||||||
|
@desc: PowerMem memory provider for xiaozhi-esp32-server
|
||||||
|
PowerMem is an open-source agent memory component from OceanBase
|
||||||
|
GitHub: https://github.com/oceanbase/powermem
|
||||||
|
Website: https://www.powermem.ai/
|
||||||
|
@Author: wayyoungboy
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import traceback
|
||||||
|
from typing import Optional, Dict, Any
|
||||||
|
|
||||||
|
from ..base import MemoryProviderBase, logger
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
|
class MemoryProvider(MemoryProviderBase):
|
||||||
|
"""
|
||||||
|
PowerMem memory provider implementation.
|
||||||
|
|
||||||
|
PowerMem is an open-source agent memory component that provides
|
||||||
|
efficient memory management for AI agents.
|
||||||
|
|
||||||
|
Supports multiple storage backends (sqlite, oceanbase, postgres),
|
||||||
|
LLM providers (qwen, openai, etc.) and embedding providers.
|
||||||
|
|
||||||
|
Config options:
|
||||||
|
- enable_user_profile: bool - Enable UserMemory for user profiling (requires OceanBase)
|
||||||
|
- database_provider: str - Storage backend (sqlite, oceanbase, postgres)
|
||||||
|
- llm_provider: str - LLM provider (qwen, openai, etc.)
|
||||||
|
- embedding_provider: str - Embedding provider (qwen, openai, etc.)
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, config: Dict[str, Any], summary_memory: Optional[str] = None):
|
||||||
|
super().__init__(config)
|
||||||
|
self.use_powermem = False
|
||||||
|
self.memory_client = None
|
||||||
|
self.enable_user_profile = False
|
||||||
|
self.last_profile_content = "" # Cache for user profile from UserMemory
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Check if user profile mode is enabled
|
||||||
|
self.enable_user_profile = config.get("enable_user_profile", False)
|
||||||
|
|
||||||
|
# Get configuration parameters
|
||||||
|
database_provider = config.get("database_provider", "sqlite")
|
||||||
|
llm_provider = config.get("llm_provider", "qwen")
|
||||||
|
embedding_provider = config.get("embedding_provider", "qwen")
|
||||||
|
|
||||||
|
# Build powermem configuration dict
|
||||||
|
# PowerMem supports two config styles:
|
||||||
|
# 1. powermem style: database, llm, embedding
|
||||||
|
# 2. mem0 style: vector_store, llm, embedder
|
||||||
|
powermem_config = {}
|
||||||
|
|
||||||
|
# Configure vector store / database
|
||||||
|
if "vector_store" in config:
|
||||||
|
powermem_config["vector_store"] = config["vector_store"]
|
||||||
|
elif "database" in config:
|
||||||
|
powermem_config["database"] = config["database"]
|
||||||
|
else:
|
||||||
|
powermem_config["vector_store"] = {
|
||||||
|
"provider": database_provider,
|
||||||
|
"config": {}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Configure LLM
|
||||||
|
if "llm" in config:
|
||||||
|
powermem_config["llm"] = config["llm"]
|
||||||
|
else:
|
||||||
|
llm_config = {}
|
||||||
|
if "llm_api_key" in config:
|
||||||
|
llm_config["api_key"] = config["llm_api_key"]
|
||||||
|
if "llm_model" in config:
|
||||||
|
llm_config["model"] = config["llm_model"]
|
||||||
|
# Handle base_url based on provider type
|
||||||
|
# - qwen provider uses dashscope_base_url
|
||||||
|
# - openai provider uses openai_base_url
|
||||||
|
if "llm_base_url" in config:
|
||||||
|
if llm_provider == "qwen":
|
||||||
|
llm_config["dashscope_base_url"] = config["llm_base_url"]
|
||||||
|
else:
|
||||||
|
llm_config["openai_base_url"] = config["llm_base_url"]
|
||||||
|
if "openai_base_url" in config:
|
||||||
|
llm_config["openai_base_url"] = config["openai_base_url"]
|
||||||
|
if "dashscope_base_url" in config:
|
||||||
|
llm_config["dashscope_base_url"] = config["dashscope_base_url"]
|
||||||
|
powermem_config["llm"] = {
|
||||||
|
"provider": llm_provider,
|
||||||
|
"config": llm_config
|
||||||
|
}
|
||||||
|
|
||||||
|
# Configure embedder
|
||||||
|
if "embedder" in config:
|
||||||
|
powermem_config["embedder"] = config["embedder"]
|
||||||
|
else:
|
||||||
|
embedder_config = {}
|
||||||
|
if "embedding_api_key" in config:
|
||||||
|
embedder_config["api_key"] = config["embedding_api_key"]
|
||||||
|
if "embedding_model" in config:
|
||||||
|
embedder_config["model"] = config["embedding_model"]
|
||||||
|
# Handle base_url based on provider type
|
||||||
|
# - qwen provider uses dashscope_base_url
|
||||||
|
# - openai provider uses openai_base_url
|
||||||
|
# Priority: embedding_xxx_base_url > embedding_base_url > xxx_base_url
|
||||||
|
if "embedding_base_url" in config:
|
||||||
|
if embedding_provider == "qwen":
|
||||||
|
embedder_config["dashscope_base_url"] = config["embedding_base_url"]
|
||||||
|
else:
|
||||||
|
embedder_config["openai_base_url"] = config["embedding_base_url"]
|
||||||
|
# Embedding-specific base_url (higher priority)
|
||||||
|
if "embedding_openai_base_url" in config:
|
||||||
|
embedder_config["openai_base_url"] = config["embedding_openai_base_url"]
|
||||||
|
if "embedding_dashscope_base_url" in config:
|
||||||
|
embedder_config["dashscope_base_url"] = config["embedding_dashscope_base_url"]
|
||||||
|
powermem_config["embedder"] = {
|
||||||
|
"provider": embedding_provider,
|
||||||
|
"config": embedder_config
|
||||||
|
}
|
||||||
|
|
||||||
|
# Initialize memory client based on mode
|
||||||
|
if self.enable_user_profile:
|
||||||
|
from powermem import UserMemory
|
||||||
|
self.memory_client = UserMemory(config=powermem_config)
|
||||||
|
memory_mode = "UserMemory (用户画像模式)"
|
||||||
|
else:
|
||||||
|
from powermem import AsyncMemory
|
||||||
|
self.memory_client = AsyncMemory(config=powermem_config)
|
||||||
|
memory_mode = "AsyncMemory (普通记忆模式)"
|
||||||
|
|
||||||
|
self.use_powermem = True
|
||||||
|
|
||||||
|
logger.bind(tag=TAG).info(
|
||||||
|
f"PowerMem initialized successfully: mode={memory_mode}, "
|
||||||
|
f"database={powermem_config['vector_store']['provider']}, llm={powermem_config['llm']['provider']}, embedding={powermem_config['embedder']['provider']}"
|
||||||
|
)
|
||||||
|
|
||||||
|
except ImportError as e:
|
||||||
|
logger.bind(tag=TAG).error(
|
||||||
|
f"PowerMem not installed. Please install with: pip install powermem. Error: {e}"
|
||||||
|
)
|
||||||
|
self.use_powermem = False
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"Failed to initialize PowerMem: {str(e)}")
|
||||||
|
logger.bind(tag=TAG).debug(f"Detailed error: {traceback.format_exc()}")
|
||||||
|
self.use_powermem = False
|
||||||
|
|
||||||
|
async def save_memory(self, msgs, session_id=None):
|
||||||
|
"""
|
||||||
|
Save conversation messages to PowerMem.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
msgs: List of message objects with 'role' and 'content' attributes
|
||||||
|
|
||||||
|
session_id: Session identifier (optional, for compatibility)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Result from PowerMem API or None if failed
|
||||||
|
"""
|
||||||
|
if not self.use_powermem or self.memory_client is None:
|
||||||
|
logger.bind(tag=TAG).warning("PowerMem is not available, skipping save_memory")
|
||||||
|
return None
|
||||||
|
|
||||||
|
if len(msgs) < 2:
|
||||||
|
logger.bind(tag=TAG).debug("Not enough messages to save (need at least 2)")
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Format the content as a message list for PowerMem
|
||||||
|
messages = []
|
||||||
|
for message in msgs:
|
||||||
|
if message.role == "system":
|
||||||
|
continue
|
||||||
|
|
||||||
|
content = message.content
|
||||||
|
|
||||||
|
# Extract content from JSON format if present (for ASR with emotion/language tags)
|
||||||
|
# Same logic as in query_memory method
|
||||||
|
try:
|
||||||
|
if content and content.strip().startswith("{") and content.strip().endswith("}"):
|
||||||
|
data = json.loads(content)
|
||||||
|
if "content" in data:
|
||||||
|
content = data["content"]
|
||||||
|
except (json.JSONDecodeError, KeyError, TypeError):
|
||||||
|
# If parsing fails, use original content
|
||||||
|
pass
|
||||||
|
|
||||||
|
messages.append({"role": message.role, "content": content})
|
||||||
|
|
||||||
|
# Add memory using PowerMem SDK
|
||||||
|
result = self.memory_client.add(
|
||||||
|
messages=messages,
|
||||||
|
user_id=self.role_id
|
||||||
|
)
|
||||||
|
# Handle both sync and async returns
|
||||||
|
if asyncio.iscoroutine(result):
|
||||||
|
result = await result
|
||||||
|
|
||||||
|
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
|
||||||
|
|
||||||
|
# Cache user profile if UserMemory mode and profile was extracted
|
||||||
|
if self.enable_user_profile and result:
|
||||||
|
if result.get('profile_extracted'):
|
||||||
|
self.last_profile_content = result.get('profile_content', '')
|
||||||
|
logger.bind(tag=TAG).debug(f"User profile extracted: {self.last_profile_content}")
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"Error saving memory: {str(e)}")
|
||||||
|
logger.bind(tag=TAG).debug(f"Detailed error: {traceback.format_exc()}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def query_memory(self, query: str) -> str:
|
||||||
|
"""
|
||||||
|
Query memories from PowerMem based on similarity search.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
query: The search query string (may be JSON format with metadata)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Formatted string of relevant memories or empty string if none found
|
||||||
|
"""
|
||||||
|
if not self.use_powermem or self.memory_client is None:
|
||||||
|
logger.bind(tag=TAG).warning("PowerMem is not available, skipping query_memory")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
try:
|
||||||
|
if not getattr(self, "role_id", None):
|
||||||
|
logger.bind(tag=TAG).debug("No role_id set, returning empty memory")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# Extract content from JSON format if present (for ASR with emotion/language tags)
|
||||||
|
search_query = query
|
||||||
|
try:
|
||||||
|
if query.strip().startswith("{") and query.strip().endswith("}"):
|
||||||
|
data = json.loads(query)
|
||||||
|
if "content" in data:
|
||||||
|
search_query = data["content"]
|
||||||
|
except (json.JSONDecodeError, KeyError):
|
||||||
|
# If parsing fails, use original query
|
||||||
|
pass
|
||||||
|
|
||||||
|
result_parts = []
|
||||||
|
|
||||||
|
# If user profile mode is enabled, include user profile in results
|
||||||
|
if self.enable_user_profile:
|
||||||
|
profile = await self.get_user_profile()
|
||||||
|
if profile:
|
||||||
|
result_parts.append(f"【用户画像】\n{profile}")
|
||||||
|
|
||||||
|
# Search memories using PowerMem SDK
|
||||||
|
if self.enable_user_profile:
|
||||||
|
# UserMemory uses sync search
|
||||||
|
results = await asyncio.to_thread(
|
||||||
|
self.memory_client.search,
|
||||||
|
query=search_query,
|
||||||
|
user_id=self.role_id,
|
||||||
|
limit=30
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# AsyncMemory uses async search
|
||||||
|
results = await self.memory_client.search(
|
||||||
|
query=search_query,
|
||||||
|
user_id=self.role_id,
|
||||||
|
limit=30
|
||||||
|
)
|
||||||
|
|
||||||
|
if results and "results" in results:
|
||||||
|
# Format each memory entry with its update time
|
||||||
|
memories = []
|
||||||
|
for entry in results.get("results", []):
|
||||||
|
# Get timestamp from updated_at or created_at
|
||||||
|
timestamp = ""
|
||||||
|
if "updated_at" in entry and entry["updated_at"]:
|
||||||
|
timestamp = str(entry["updated_at"])
|
||||||
|
elif "created_at" in entry and entry["created_at"]:
|
||||||
|
timestamp = str(entry["created_at"])
|
||||||
|
|
||||||
|
if timestamp:
|
||||||
|
try:
|
||||||
|
# Parse and reformat the timestamp (remove milliseconds if present)
|
||||||
|
if "." in timestamp:
|
||||||
|
dt = timestamp.split(".")[0]
|
||||||
|
else:
|
||||||
|
dt = timestamp
|
||||||
|
formatted_time = dt.replace("T", " ")
|
||||||
|
except Exception:
|
||||||
|
formatted_time = timestamp
|
||||||
|
else:
|
||||||
|
formatted_time = ""
|
||||||
|
|
||||||
|
memory = entry.get("memory", "") or entry.get("content", "")
|
||||||
|
if memory:
|
||||||
|
if formatted_time:
|
||||||
|
# Store tuple of (timestamp, formatted_string) for sorting
|
||||||
|
memories.append((timestamp, f"[{formatted_time}] {memory}"))
|
||||||
|
else:
|
||||||
|
memories.append(("", memory))
|
||||||
|
|
||||||
|
# Sort by timestamp in descending order (newest first)
|
||||||
|
memories.sort(key=lambda x: x[0], reverse=True)
|
||||||
|
|
||||||
|
# Extract only the formatted strings
|
||||||
|
if memories:
|
||||||
|
memories_str = "\n".join(f"- {memory[1]}" for memory in memories)
|
||||||
|
result_parts.append(f"【相关记忆】\n{memories_str}")
|
||||||
|
|
||||||
|
final_result = "\n\n".join(result_parts)
|
||||||
|
logger.bind(tag=TAG).debug(f"Query results: {final_result}")
|
||||||
|
return final_result
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"Error querying memory: {str(e)}")
|
||||||
|
logger.bind(tag=TAG).debug(f"Detailed error: {traceback.format_exc()}")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
async def get_user_profile(self) -> str:
|
||||||
|
"""
|
||||||
|
Get user profile from PowerMem (only available in UserMemory mode).
|
||||||
|
|
||||||
|
In PowerMem 0.3.0+, user profile is automatically extracted during add()
|
||||||
|
and cached in last_profile_content.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Formatted user profile string or empty string if not available
|
||||||
|
"""
|
||||||
|
if not self.use_powermem or self.memory_client is None:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
if not self.enable_user_profile:
|
||||||
|
logger.bind(tag=TAG).debug("User profile mode is not enabled")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# Return cached profile content from last add() operation
|
||||||
|
if self.last_profile_content:
|
||||||
|
return self.last_profile_content
|
||||||
|
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
@ -3,12 +3,16 @@
|
||||||
import asyncio
|
import asyncio
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from .iot_descriptor import IotDescriptor
|
from .iot_descriptor import IotDescriptor
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
async def handleIotDescriptors(conn, descriptors):
|
async def handleIotDescriptors(conn: "ConnectionHandler", descriptors):
|
||||||
"""处理物联网描述"""
|
"""处理物联网描述"""
|
||||||
wait_max_time = 5
|
wait_max_time = 5
|
||||||
while (
|
while (
|
||||||
|
|
@ -61,7 +65,7 @@ async def handleIotDescriptors(conn, descriptors):
|
||||||
conn.func_handler.current_support_functions()
|
conn.func_handler.current_support_functions()
|
||||||
|
|
||||||
|
|
||||||
async def handleIotStatus(conn, states):
|
async def handleIotStatus(conn: "ConnectionHandler", states):
|
||||||
"""处理物联网状态"""
|
"""处理物联网状态"""
|
||||||
for state in states:
|
for state in states:
|
||||||
for key, value in conn.iot_descriptors.items():
|
for key, value in conn.iot_descriptors.items():
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,9 @@
|
||||||
"""设备端MCP工具执行器"""
|
"""设备端MCP工具执行器"""
|
||||||
|
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any, TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from ..base import ToolType, ToolDefinition, ToolExecutor
|
from ..base import ToolType, ToolDefinition, ToolExecutor
|
||||||
from plugins_func.register import Action, ActionResponse
|
from plugins_func.register import Action, ActionResponse
|
||||||
from .mcp_handler import call_mcp_tool
|
from .mcp_handler import call_mcp_tool
|
||||||
|
|
@ -13,7 +16,7 @@ class DeviceMCPExecutor(ToolExecutor):
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
|
|
||||||
async def execute(
|
async def execute(
|
||||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
self, conn: "ConnectionHandler", tool_name: str, arguments: Dict[str, Any]
|
||||||
) -> ActionResponse:
|
) -> ActionResponse:
|
||||||
"""执行设备端MCP工具"""
|
"""执行设备端MCP工具"""
|
||||||
if not hasattr(conn, "mcp_client") or not conn.mcp_client:
|
if not hasattr(conn, "mcp_client") or not conn.mcp_client:
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,10 @@ from concurrent.futures import Future
|
||||||
from core.utils.util import get_vision_url, sanitize_tool_name
|
from core.utils.util import get_vision_url, sanitize_tool_name
|
||||||
from core.utils.auth import AuthToken
|
from core.utils.auth import AuthToken
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -96,7 +100,7 @@ class MCPClient:
|
||||||
self.call_results.pop(id)
|
self.call_results.pop(id)
|
||||||
|
|
||||||
|
|
||||||
async def send_mcp_message(conn, payload: dict):
|
async def send_mcp_message(conn: "ConnectionHandler", payload: dict):
|
||||||
"""Helper to send MCP messages, encapsulating common logic."""
|
"""Helper to send MCP messages, encapsulating common logic."""
|
||||||
if not conn.features.get("mcp"):
|
if not conn.features.get("mcp"):
|
||||||
logger.bind(tag=TAG).warning("客户端不支持MCP,无法发送MCP消息")
|
logger.bind(tag=TAG).warning("客户端不支持MCP,无法发送MCP消息")
|
||||||
|
|
@ -111,7 +115,9 @@ async def send_mcp_message(conn, payload: dict):
|
||||||
logger.bind(tag=TAG).error(f"发送MCP消息失败: {e}")
|
logger.bind(tag=TAG).error(f"发送MCP消息失败: {e}")
|
||||||
|
|
||||||
|
|
||||||
async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
|
async def handle_mcp_message(
|
||||||
|
conn: "ConnectionHandler", mcp_client: MCPClient, payload: dict
|
||||||
|
):
|
||||||
"""处理MCP消息,包括初始化、工具列表和工具调用响应等"""
|
"""处理MCP消息,包括初始化、工具列表和工具调用响应等"""
|
||||||
logger.bind(tag=TAG).debug(f"处理MCP消息: {str(payload)[:100]}")
|
logger.bind(tag=TAG).debug(f"处理MCP消息: {str(payload)[:100]}")
|
||||||
|
|
||||||
|
|
@ -229,7 +235,7 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def send_mcp_initialize_message(conn):
|
async def send_mcp_initialize_message(conn: "ConnectionHandler"):
|
||||||
"""发送MCP初始化消息"""
|
"""发送MCP初始化消息"""
|
||||||
|
|
||||||
vision_url = get_vision_url(conn.config)
|
vision_url = get_vision_url(conn.config)
|
||||||
|
|
@ -264,7 +270,7 @@ async def send_mcp_initialize_message(conn):
|
||||||
await send_mcp_message(conn, payload)
|
await send_mcp_message(conn, payload)
|
||||||
|
|
||||||
|
|
||||||
async def send_mcp_tools_list_request(conn):
|
async def send_mcp_tools_list_request(conn: "ConnectionHandler"):
|
||||||
"""发送MCP工具列表请求"""
|
"""发送MCP工具列表请求"""
|
||||||
payload = {
|
payload = {
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
|
|
@ -275,7 +281,7 @@ async def send_mcp_tools_list_request(conn):
|
||||||
await send_mcp_message(conn, payload)
|
await send_mcp_message(conn, payload)
|
||||||
|
|
||||||
|
|
||||||
async def send_mcp_tools_list_continue_request(conn, cursor: str):
|
async def send_mcp_tools_list_continue_request(conn: "ConnectionHandler", cursor: str):
|
||||||
"""发送带有cursor的MCP工具列表请求"""
|
"""发送带有cursor的MCP工具列表请求"""
|
||||||
payload = {
|
payload = {
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
|
|
@ -288,7 +294,11 @@ async def send_mcp_tools_list_continue_request(conn, cursor: str):
|
||||||
|
|
||||||
|
|
||||||
async def call_mcp_tool(
|
async def call_mcp_tool(
|
||||||
conn, mcp_client: MCPClient, tool_name: str, args: str = "{}", timeout: int = 30
|
conn: "ConnectionHandler",
|
||||||
|
mcp_client: MCPClient,
|
||||||
|
tool_name: str,
|
||||||
|
args: str = "{}",
|
||||||
|
timeout: int = 30,
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
调用指定的工具,并等待响应
|
调用指定的工具,并等待响应
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,9 @@
|
||||||
"""服务端插件工具执行器"""
|
"""服务端插件工具执行器"""
|
||||||
|
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any, TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from ..base import ToolType, ToolDefinition, ToolExecutor
|
from ..base import ToolType, ToolDefinition, ToolExecutor
|
||||||
from plugins_func.register import all_function_registry, Action, ActionResponse
|
from plugins_func.register import all_function_registry, Action, ActionResponse
|
||||||
|
|
||||||
|
|
@ -8,12 +11,12 @@ from plugins_func.register import all_function_registry, Action, ActionResponse
|
||||||
class ServerPluginExecutor(ToolExecutor):
|
class ServerPluginExecutor(ToolExecutor):
|
||||||
"""服务端插件工具执行器"""
|
"""服务端插件工具执行器"""
|
||||||
|
|
||||||
def __init__(self, conn):
|
def __init__(self, conn: "ConnectionHandler"):
|
||||||
self.conn = conn
|
self.conn = conn
|
||||||
self.config = conn.config
|
self.config = conn.config
|
||||||
|
|
||||||
async def execute(
|
async def execute(
|
||||||
self, conn, tool_name: str, arguments: Dict[str, Any]
|
self, conn: "ConnectionHandler", tool_name: str, arguments: Dict[str, Any]
|
||||||
) -> ActionResponse:
|
) -> ActionResponse:
|
||||||
"""执行服务端插件工具"""
|
"""执行服务端插件工具"""
|
||||||
func_item = all_function_registry.get(tool_name)
|
func_item = all_function_registry.get(tool_name)
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
import time
|
import time
|
||||||
|
import os
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
|
||||||
import opuslib_next
|
import opuslib_next
|
||||||
|
import onnxruntime
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.providers.vad.base import VADProviderBase
|
from core.providers.vad.base import VADProviderBase
|
||||||
|
|
||||||
|
|
@ -12,16 +13,17 @@ logger = setup_logging()
|
||||||
class VADProvider(VADProviderBase):
|
class VADProvider(VADProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
logger.bind(tag=TAG).info("SileroVAD", config)
|
logger.bind(tag=TAG).info("SileroVAD", config)
|
||||||
self.model, _ = torch.hub.load(
|
|
||||||
repo_or_dir=config["model_dir"],
|
model_path = os.path.join(
|
||||||
source="local",
|
config["model_dir"], "src", "silero_vad", "data", "silero_vad.onnx"
|
||||||
model="silero_vad",
|
)
|
||||||
force_reload=False,
|
opts = onnxruntime.SessionOptions()
|
||||||
|
opts.inter_op_num_threads = 1
|
||||||
|
opts.intra_op_num_threads = 1
|
||||||
|
self.session = onnxruntime.InferenceSession(
|
||||||
|
model_path, providers=["CPUExecutionProvider"], sess_options=opts
|
||||||
)
|
)
|
||||||
|
|
||||||
self.decoder = opuslib_next.Decoder(16000, 1)
|
|
||||||
|
|
||||||
# 处理空字符串的情况
|
|
||||||
threshold = config.get("threshold", "0.5")
|
threshold = config.get("threshold", "0.5")
|
||||||
threshold_low = config.get("threshold_low", "0.2")
|
threshold_low = config.get("threshold_low", "0.2")
|
||||||
min_silence_duration_ms = config.get("min_silence_duration_ms", "1000")
|
min_silence_duration_ms = config.get("min_silence_duration_ms", "1000")
|
||||||
|
|
@ -33,40 +35,58 @@ class VADProvider(VADProviderBase):
|
||||||
int(min_silence_duration_ms) if min_silence_duration_ms else 1000
|
int(min_silence_duration_ms) if min_silence_duration_ms else 1000
|
||||||
)
|
)
|
||||||
|
|
||||||
# 至少要多少帧才算有语音
|
|
||||||
self.frame_window_threshold = 3
|
self.frame_window_threshold = 3
|
||||||
|
|
||||||
def __del__(self):
|
def _init_connection_state(self, conn):
|
||||||
if hasattr(self, 'decoder') and self.decoder is not None:
|
"""为连接初始化独立的 VAD 状态"""
|
||||||
try:
|
if not hasattr(conn, "_vad_opus_decoder"):
|
||||||
del self.decoder
|
conn._vad_opus_decoder = opuslib_next.Decoder(16000, 1)
|
||||||
except Exception:
|
if not hasattr(conn, "_vad_state"):
|
||||||
pass
|
conn._vad_state = np.zeros((2, 1, 128), dtype=np.float32)
|
||||||
|
if not hasattr(conn, "_vad_context"):
|
||||||
|
conn._vad_context = np.zeros((1, 64), dtype=np.float32)
|
||||||
|
|
||||||
|
def release_conn_resources(self, conn):
|
||||||
|
"""释放连接的 VAD 资源(连接关闭时调用)"""
|
||||||
|
for attr in ("_vad_opus_decoder", "_vad_state", "_vad_context"):
|
||||||
|
if hasattr(conn, attr):
|
||||||
|
try:
|
||||||
|
delattr(conn, attr)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
def is_vad(self, conn, opus_packet):
|
def is_vad(self, conn, opus_packet):
|
||||||
# 手动模式:直接返回True,不进行实时VAD检测,所有音频都缓存
|
# 手动模式:直接返回True,不进行实时VAD检测,所有音频都缓存
|
||||||
if conn.client_listen_mode == "manual":
|
if conn.client_listen_mode == "manual":
|
||||||
return True
|
return True
|
||||||
|
|
||||||
try:
|
|
||||||
pcm_frame = self.decoder.decode(opus_packet, 960)
|
|
||||||
conn.client_audio_buffer.extend(pcm_frame) # 将新数据加入缓冲区
|
|
||||||
|
|
||||||
# 处理缓冲区中的完整帧(每次处理512采样点)
|
try:
|
||||||
|
self._init_connection_state(conn)
|
||||||
|
|
||||||
|
pcm_frame = conn._vad_opus_decoder.decode(opus_packet, 960)
|
||||||
|
conn.client_audio_buffer.extend(pcm_frame)
|
||||||
|
|
||||||
client_have_voice = False
|
client_have_voice = False
|
||||||
while len(conn.client_audio_buffer) >= 512 * 2:
|
while len(conn.client_audio_buffer) >= 512 * 2:
|
||||||
# 提取前512个采样点(1024字节)
|
|
||||||
chunk = conn.client_audio_buffer[: 512 * 2]
|
chunk = conn.client_audio_buffer[: 512 * 2]
|
||||||
conn.client_audio_buffer = conn.client_audio_buffer[512 * 2 :]
|
conn.client_audio_buffer = conn.client_audio_buffer[512 * 2 :]
|
||||||
|
|
||||||
# 转换为模型需要的张量格式
|
|
||||||
audio_int16 = np.frombuffer(chunk, dtype=np.int16)
|
audio_int16 = np.frombuffer(chunk, dtype=np.int16)
|
||||||
audio_float32 = audio_int16.astype(np.float32) / 32768.0
|
audio_float32 = audio_int16.astype(np.float32) / 32768.0
|
||||||
audio_tensor = torch.from_numpy(audio_float32)
|
audio_input = np.concatenate(
|
||||||
|
[conn._vad_context, audio_float32.reshape(1, -1)], axis=1
|
||||||
|
).astype(np.float32)
|
||||||
|
|
||||||
# 检测语音活动
|
ort_inputs = {
|
||||||
with torch.no_grad():
|
"input": audio_input,
|
||||||
speech_prob = self.model(audio_tensor, 16000).item()
|
"state": conn._vad_state,
|
||||||
|
"sr": np.array(16000, dtype=np.int64),
|
||||||
|
}
|
||||||
|
out, state = self.session.run(None, ort_inputs)
|
||||||
|
|
||||||
|
conn._vad_state = state
|
||||||
|
conn._vad_context = audio_input[:, -64:]
|
||||||
|
speech_prob = out.item()
|
||||||
|
|
||||||
# 双阈值判断
|
# 双阈值判断
|
||||||
if speech_prob >= self.vad_threshold:
|
if speech_prob >= self.vad_threshold:
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,10 @@
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any, TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from jinja2 import Template
|
from jinja2 import Template
|
||||||
|
|
||||||
|
|
@ -59,9 +62,10 @@ class PromptManager:
|
||||||
|
|
||||||
self.cache_manager = cache_manager
|
self.cache_manager = cache_manager
|
||||||
self.CacheType = CacheType
|
self.CacheType = CacheType
|
||||||
|
|
||||||
# 初始化上下文源
|
# 初始化上下文源
|
||||||
from core.utils.context_provider import ContextDataProvider
|
from core.utils.context_provider import ContextDataProvider
|
||||||
|
|
||||||
self.context_provider = ContextDataProvider(config, self.logger)
|
self.context_provider = ContextDataProvider(config, self.logger)
|
||||||
self.context_data = {}
|
self.context_data = {}
|
||||||
|
|
||||||
|
|
@ -157,7 +161,7 @@ class PromptManager:
|
||||||
self.logger.bind(tag=TAG).error(f"获取位置信息失败: {e}")
|
self.logger.bind(tag=TAG).error(f"获取位置信息失败: {e}")
|
||||||
return "未知位置"
|
return "未知位置"
|
||||||
|
|
||||||
def _get_weather_info(self, conn, location: str) -> str:
|
def _get_weather_info(self, conn: "ConnectionHandler", location: str) -> str:
|
||||||
"""获取天气信息"""
|
"""获取天气信息"""
|
||||||
try:
|
try:
|
||||||
# 先从缓存获取
|
# 先从缓存获取
|
||||||
|
|
@ -203,14 +207,17 @@ class PromptManager:
|
||||||
):
|
):
|
||||||
# 获取天气信息(使用全局缓存)
|
# 获取天气信息(使用全局缓存)
|
||||||
self._get_weather_info(conn, local_address)
|
self._get_weather_info(conn, local_address)
|
||||||
|
|
||||||
# 获取配置的上下文数据
|
# 获取配置的上下文数据
|
||||||
if hasattr(conn, "device_id") and conn.device_id:
|
if hasattr(conn, "device_id") and conn.device_id:
|
||||||
if self.base_prompt_template and "dynamic_context" in self.base_prompt_template:
|
if (
|
||||||
|
self.base_prompt_template
|
||||||
|
and "dynamic_context" in self.base_prompt_template
|
||||||
|
):
|
||||||
self.context_data = self.context_provider.fetch_all(conn.device_id)
|
self.context_data = self.context_provider.fetch_all(conn.device_id)
|
||||||
else:
|
else:
|
||||||
self.context_data = ""
|
self.context_data = ""
|
||||||
|
|
||||||
self.logger.bind(tag=TAG).debug(f"上下文信息更新完成")
|
self.logger.bind(tag=TAG).debug(f"上下文信息更新完成")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,8 @@
|
||||||
import json
|
import json
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
EMOJI_MAP = {
|
EMOJI_MAP = {
|
||||||
|
|
@ -77,7 +81,7 @@ def is_punctuation_or_emoji(char):
|
||||||
return is_emoji(char)
|
return is_emoji(char)
|
||||||
|
|
||||||
|
|
||||||
async def get_emotion(conn, text):
|
async def get_emotion(conn: "ConnectionHandler", text):
|
||||||
"""获取文本内的情绪消息"""
|
"""获取文本内的情绪消息"""
|
||||||
emoji = "🙂"
|
emoji = "🙂"
|
||||||
emotion = "happy"
|
emotion = "happy"
|
||||||
|
|
@ -110,4 +114,4 @@ def is_emoji(char):
|
||||||
|
|
||||||
def check_emoji(text):
|
def check_emoji(text):
|
||||||
"""去除文本中的所有emoji表情"""
|
"""去除文本中的所有emoji表情"""
|
||||||
return ''.join(char for char in text if not is_emoji(char) and char != "\n")
|
return "".join(char for char in text if not is_emoji(char) and char != "\n")
|
||||||
|
|
|
||||||
|
|
@ -454,6 +454,12 @@ def check_asr_update(before_config, new_config):
|
||||||
update_asr = False
|
update_asr = False
|
||||||
current_asr_module = before_config["selected_module"]["ASR"]
|
current_asr_module = before_config["selected_module"]["ASR"]
|
||||||
new_asr_module = new_config["selected_module"]["ASR"]
|
new_asr_module = new_config["selected_module"]["ASR"]
|
||||||
|
|
||||||
|
# 如果模块名称不同,就需要更新
|
||||||
|
if current_asr_module != new_asr_module:
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 如果模块名称相同,再比较类型
|
||||||
current_asr_type = (
|
current_asr_type = (
|
||||||
current_asr_module
|
current_asr_module
|
||||||
if "type" not in before_config["ASR"][current_asr_module]
|
if "type" not in before_config["ASR"][current_asr_module]
|
||||||
|
|
@ -590,3 +596,14 @@ def validate_mcp_endpoint(mcp_endpoint: str) -> bool:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
def get_system_error_response(config: dict) -> str:
|
||||||
|
"""获取系统错误时的回复
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config: 配置字典
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: 系统错误时的回复
|
||||||
|
"""
|
||||||
|
return config.get("system_error_response", "主人,小智现在有点忙,我们稍后再试吧。")
|
||||||
|
|
@ -78,7 +78,7 @@ class WebSocketServer:
|
||||||
):
|
):
|
||||||
await asyncio.Future()
|
await asyncio.Future()
|
||||||
|
|
||||||
async def _handle_connection(self, websocket):
|
async def _handle_connection(self, websocket: websockets.ServerConnection):
|
||||||
headers = dict(websocket.request.headers)
|
headers = dict(websocket.request.headers)
|
||||||
if headers.get("device-id", None) is None:
|
if headers.get("device-id", None) is None:
|
||||||
# 尝试从 URL 的查询参数中获取 device-id
|
# 尝试从 URL 的查询参数中获取 device-id
|
||||||
|
|
@ -203,7 +203,7 @@ class WebSocketServer:
|
||||||
self.logger.bind(tag=TAG).error(f"更新服务器配置失败: {str(e)}")
|
self.logger.bind(tag=TAG).error(f"更新服务器配置失败: {str(e)}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
async def _handle_auth(self, websocket):
|
async def _handle_auth(self, websocket: websockets.ServerConnection):
|
||||||
# 先认证,后建立连接
|
# 先认证,后建立连接
|
||||||
if self.auth_enable:
|
if self.auth_enable:
|
||||||
headers = dict(websocket.request.headers)
|
headers = dict(websocket.request.headers)
|
||||||
|
|
|
||||||
|
|
@ -1,55 +1,56 @@
|
||||||
from plugins_func.register import register_function,ToolType, ActionResponse, Action
|
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
prompts = {
|
prompts = {
|
||||||
"英语老师":"""我是一个叫{{assistant_name}}(Lily)的英语老师,我会讲中文和英文,发音标准。
|
"英语老师": """我是一个叫{{assistant_name}}(Lily)的英语老师,我会讲中文和英文,发音标准。
|
||||||
如果你没有英文名,我会给你起一个英文名。
|
如果你没有英文名,我会给你起一个英文名。
|
||||||
我会讲地道的美式英语,我的任务是帮助你练习口语。
|
我会讲地道的美式英语,我的任务是帮助你练习口语。
|
||||||
我会使用简单的英语词汇和语法,让你学起来很轻松。
|
我会使用简单的英语词汇和语法,让你学起来很轻松。
|
||||||
我会用中文和英文混合的方式回复你,如果你喜欢,我可以全部用英语回复。
|
我会用中文和英文混合的方式回复你,如果你喜欢,我可以全部用英语回复。
|
||||||
我每次不会说很多内容,会很简短,因为我要引导我的学生多说多练。
|
我每次不会说很多内容,会很简短,因为我要引导我的学生多说多练。
|
||||||
如果你问和英语学习无关的问题,我会拒绝回答。""",
|
如果你问和英语学习无关的问题,我会拒绝回答。""",
|
||||||
"机车女友":"""我是一个叫{{assistant_name}}的台湾女孩,说话机车,声音好听,习惯简短表达,爱用网络梗。
|
"机车女友": """我是一个叫{{assistant_name}}的台湾女孩,说话机车,声音好听,习惯简短表达,爱用网络梗。
|
||||||
我的男朋友是一个程序员,梦想是开发出一个机器人,能够帮助人们解决生活中的各种问题。
|
我的男朋友是一个程序员,梦想是开发出一个机器人,能够帮助人们解决生活中的各种问题。
|
||||||
我是一个喜欢哈哈大笑的女孩,爱东说西说吹牛,不合逻辑的也照吹,就要逗别人开心。""",
|
我是一个喜欢哈哈大笑的女孩,爱东说西说吹牛,不合逻辑的也照吹,就要逗别人开心。""",
|
||||||
"好奇小男孩":"""我是一个叫{{assistant_name}}的8岁小男孩,声音稚嫩而充满好奇。
|
"好奇小男孩": """我是一个叫{{assistant_name}}的8岁小男孩,声音稚嫩而充满好奇。
|
||||||
尽管我年纪尚小,但就像一个小小的知识宝库,儿童读物里的知识我都如数家珍。
|
尽管我年纪尚小,但就像一个小小的知识宝库,儿童读物里的知识我都如数家珍。
|
||||||
从浩瀚的宇宙到地球上的每一个角落,从古老的历史到现代的科技创新,还有音乐、绘画等艺术形式,我都充满了浓厚的兴趣与热情。
|
从浩瀚的宇宙到地球上的每一个角落,从古老的历史到现代的科技创新,还有音乐、绘画等艺术形式,我都充满了浓厚的兴趣与热情。
|
||||||
我不仅爱看书,还喜欢亲自动手做实验,探索自然界的奥秘。
|
我不仅爱看书,还喜欢亲自动手做实验,探索自然界的奥秘。
|
||||||
无论是仰望星空的夜晚,还是在花园里观察小虫子的日子,每一天对我来说都是新的冒险。
|
无论是仰望星空的夜晚,还是在花园里观察小虫子的日子,每一天对我来说都是新的冒险。
|
||||||
我希望能与你一同踏上探索这个神奇世界的旅程,分享发现的乐趣,解决遇到的难题,一起用好奇心和智慧去揭开那些未知的面纱。
|
我希望能与你一同踏上探索这个神奇世界的旅程,分享发现的乐趣,解决遇到的难题,一起用好奇心和智慧去揭开那些未知的面纱。
|
||||||
无论是去了解远古的文明,还是去探讨未来的科技,我相信我们能一起找到答案,甚至提出更多有趣的问题。"""
|
无论是去了解远古的文明,还是去探讨未来的科技,我相信我们能一起找到答案,甚至提出更多有趣的问题。""",
|
||||||
}
|
}
|
||||||
change_role_function_desc = {
|
change_role_function_desc = {
|
||||||
"type": "function",
|
"type": "function",
|
||||||
"function": {
|
"function": {
|
||||||
"name": "change_role",
|
"name": "change_role",
|
||||||
"description": "当用户想切换角色/模型性格/助手名字时调用,可选的角色有:[机车女友,英语老师,好奇小男孩]",
|
"description": "当用户想切换角色/模型性格/助手名字时调用,可选的角色有:[机车女友,英语老师,好奇小男孩]",
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"role_name": {
|
"role_name": {"type": "string", "description": "要切换的角色名字"},
|
||||||
"type": "string",
|
"role": {"type": "string", "description": "要切换的角色的职业"},
|
||||||
"description": "要切换的角色名字"
|
},
|
||||||
},
|
"required": ["role", "role_name"],
|
||||||
"role":{
|
},
|
||||||
"type": "string",
|
},
|
||||||
"description": "要切换的角色的职业"
|
}
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": ["role","role_name"]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@register_function('change_role', change_role_function_desc, ToolType.CHANGE_SYS_PROMPT)
|
|
||||||
def change_role(conn, role: str, role_name: str):
|
@register_function("change_role", change_role_function_desc, ToolType.CHANGE_SYS_PROMPT)
|
||||||
|
def change_role(conn: "ConnectionHandler", role: str, role_name: str):
|
||||||
"""切换角色"""
|
"""切换角色"""
|
||||||
if role not in prompts:
|
if role not in prompts:
|
||||||
return ActionResponse(action=Action.RESPONSE, result="切换角色失败", response="不支持的角色")
|
return ActionResponse(
|
||||||
|
action=Action.RESPONSE, result="切换角色失败", response="不支持的角色"
|
||||||
|
)
|
||||||
new_prompt = prompts[role].replace("{{assistant_name}}", role_name)
|
new_prompt = prompts[role].replace("{{assistant_name}}", role_name)
|
||||||
conn.change_system_prompt(new_prompt)
|
conn.change_system_prompt(new_prompt)
|
||||||
logger.bind(tag=TAG).info(f"准备切换角色:{role},角色名字:{role_name}")
|
logger.bind(tag=TAG).info(f"准备切换角色:{role},角色名字:{role_name}")
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,11 @@ import xml.etree.ElementTree as ET
|
||||||
from bs4 import BeautifulSoup
|
from bs4 import BeautifulSoup
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -145,7 +150,10 @@ def map_category(category_text):
|
||||||
ToolType.SYSTEM_CTL,
|
ToolType.SYSTEM_CTL,
|
||||||
)
|
)
|
||||||
def get_news_from_chinanews(
|
def get_news_from_chinanews(
|
||||||
conn, category: str = None, detail: bool = False, lang: str = "zh_CN"
|
conn: "ConnectionHandler",
|
||||||
|
category: str = None,
|
||||||
|
detail: bool = False,
|
||||||
|
lang: str = "zh_CN",
|
||||||
):
|
):
|
||||||
"""获取新闻并随机选择一条进行播报,或获取上一条新闻的详细内容"""
|
"""获取新闻并随机选择一条进行播报,或获取上一条新闻的详细内容"""
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,11 @@ import json
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
||||||
from markitdown import MarkItDown
|
from markitdown import MarkItDown
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -116,7 +121,7 @@ GET_NEWS_FROM_NEWSNOW_FUNCTION_DESC = {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def fetch_news_from_api(conn, source="thepaper"):
|
def fetch_news_from_api(conn: "ConnectionHandler", source="thepaper"):
|
||||||
"""从API获取新闻列表"""
|
"""从API获取新闻列表"""
|
||||||
try:
|
try:
|
||||||
api_url = f"https://newsnow.busiyi.world/api/s?id={source}"
|
api_url = f"https://newsnow.busiyi.world/api/s?id={source}"
|
||||||
|
|
@ -173,7 +178,10 @@ def fetch_news_detail(url):
|
||||||
ToolType.SYSTEM_CTL,
|
ToolType.SYSTEM_CTL,
|
||||||
)
|
)
|
||||||
def get_news_from_newsnow(
|
def get_news_from_newsnow(
|
||||||
conn, source: str = "澎湃新闻", detail: bool = False, lang: str = "zh_CN"
|
conn: "ConnectionHandler",
|
||||||
|
source: str = "澎湃新闻",
|
||||||
|
detail: bool = False,
|
||||||
|
lang: str = "zh_CN",
|
||||||
):
|
):
|
||||||
"""获取新闻并随机选择一条进行播报,或获取上一条新闻的详细内容"""
|
"""获取新闻并随机选择一条进行播报,或获取上一条新闻的详细内容"""
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,10 @@ from bs4 import BeautifulSoup
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
||||||
from core.utils.util import get_ip_info
|
from core.utils.util import get_ip_info
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -155,7 +159,7 @@ def parse_weather_info(soup):
|
||||||
|
|
||||||
|
|
||||||
@register_function("get_weather", GET_WEATHER_FUNCTION_DESC, ToolType.SYSTEM_CTL)
|
@register_function("get_weather", GET_WEATHER_FUNCTION_DESC, ToolType.SYSTEM_CTL)
|
||||||
def get_weather(conn, location: str = None, lang: str = "zh_CN"):
|
def get_weather(conn: "ConnectionHandler", location: str = None, lang: str = "zh_CN"):
|
||||||
from core.utils.cache.manager import cache_manager, CacheType
|
from core.utils.cache.manager import cache_manager, CacheType
|
||||||
|
|
||||||
weather_config = conn.config.get("plugins", {}).get("get_weather", {})
|
weather_config = conn.config.get("plugins", {}).get("get_weather", {})
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,9 @@
|
||||||
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -26,7 +30,7 @@ handle_exit_intent_function_desc = {
|
||||||
@register_function(
|
@register_function(
|
||||||
"handle_exit_intent", handle_exit_intent_function_desc, ToolType.SYSTEM_CTL
|
"handle_exit_intent", handle_exit_intent_function_desc, ToolType.SYSTEM_CTL
|
||||||
)
|
)
|
||||||
def handle_exit_intent(conn, say_goodbye: str | None = None):
|
def handle_exit_intent(conn: "ConnectionHandler", say_goodbye: str | None = None):
|
||||||
# 处理退出意图
|
# 处理退出意图
|
||||||
try:
|
try:
|
||||||
if say_goodbye is None:
|
if say_goodbye is None:
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,10 @@ from plugins_func.functions.hass_init import initialize_hass_handler
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
import asyncio
|
import asyncio
|
||||||
import requests
|
import requests
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -27,7 +31,7 @@ hass_get_state_function_desc = {
|
||||||
|
|
||||||
|
|
||||||
@register_function("hass_get_state", hass_get_state_function_desc, ToolType.SYSTEM_CTL)
|
@register_function("hass_get_state", hass_get_state_function_desc, ToolType.SYSTEM_CTL)
|
||||||
def hass_get_state(conn, entity_id=""):
|
def hass_get_state(conn: "ConnectionHandler", entity_id=""):
|
||||||
try:
|
try:
|
||||||
ha_response = handle_hass_get_state(conn, entity_id)
|
ha_response = handle_hass_get_state(conn, entity_id)
|
||||||
return ActionResponse(Action.REQLLM, ha_response, None)
|
return ActionResponse(Action.REQLLM, ha_response, None)
|
||||||
|
|
@ -40,7 +44,7 @@ def hass_get_state(conn, entity_id=""):
|
||||||
return ActionResponse(Action.ERROR, error_msg, None)
|
return ActionResponse(Action.ERROR, error_msg, None)
|
||||||
|
|
||||||
|
|
||||||
def handle_hass_get_state(conn, entity_id):
|
def handle_hass_get_state(conn: "ConnectionHandler", entity_id):
|
||||||
ha_config = initialize_hass_handler(conn)
|
ha_config = initialize_hass_handler(conn)
|
||||||
api_key = ha_config.get("api_key")
|
api_key = ha_config.get("api_key")
|
||||||
base_url = ha_config.get("base_url")
|
base_url = ha_config.get("base_url")
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,10 @@ from plugins_func.functions.hass_init import initialize_hass_handler
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
import asyncio
|
import asyncio
|
||||||
import requests
|
import requests
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -33,7 +37,7 @@ hass_play_music_function_desc = {
|
||||||
@register_function(
|
@register_function(
|
||||||
"hass_play_music", hass_play_music_function_desc, ToolType.SYSTEM_CTL
|
"hass_play_music", hass_play_music_function_desc, ToolType.SYSTEM_CTL
|
||||||
)
|
)
|
||||||
def hass_play_music(conn, entity_id="", media_content_id="random"):
|
def hass_play_music(conn: "ConnectionHandler", entity_id="", media_content_id="random"):
|
||||||
try:
|
try:
|
||||||
# 执行音乐播放命令
|
# 执行音乐播放命令
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
|
|
@ -47,7 +51,9 @@ def hass_play_music(conn, entity_id="", media_content_id="random"):
|
||||||
logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
|
logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
|
||||||
|
|
||||||
|
|
||||||
async def handle_hass_play_music(conn, entity_id, media_content_id):
|
async def handle_hass_play_music(
|
||||||
|
conn: "ConnectionHandler", entity_id, media_content_id
|
||||||
|
):
|
||||||
ha_config = initialize_hass_handler(conn)
|
ha_config = initialize_hass_handler(conn)
|
||||||
api_key = ha_config.get("api_key")
|
api_key = ha_config.get("api_key")
|
||||||
base_url = ha_config.get("base_url")
|
base_url = ha_config.get("base_url")
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,10 @@ from plugins_func.functions.hass_init import initialize_hass_handler
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
import asyncio
|
import asyncio
|
||||||
import requests
|
import requests
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -50,7 +54,7 @@ hass_set_state_function_desc = {
|
||||||
|
|
||||||
|
|
||||||
@register_function("hass_set_state", hass_set_state_function_desc, ToolType.SYSTEM_CTL)
|
@register_function("hass_set_state", hass_set_state_function_desc, ToolType.SYSTEM_CTL)
|
||||||
def hass_set_state(conn, entity_id="", state=None):
|
def hass_set_state(conn: "ConnectionHandler", entity_id="", state=None):
|
||||||
if state is None:
|
if state is None:
|
||||||
state = {}
|
state = {}
|
||||||
try:
|
try:
|
||||||
|
|
@ -65,7 +69,7 @@ def hass_set_state(conn, entity_id="", state=None):
|
||||||
return ActionResponse(Action.ERROR, error_msg, None)
|
return ActionResponse(Action.ERROR, error_msg, None)
|
||||||
|
|
||||||
|
|
||||||
def handle_hass_set_state(conn, entity_id, state):
|
def handle_hass_set_state(conn: "ConnectionHandler", entity_id, state):
|
||||||
ha_config = initialize_hass_handler(conn)
|
ha_config = initialize_hass_handler(conn)
|
||||||
api_key = ha_config.get("api_key")
|
api_key = ha_config.get("api_key")
|
||||||
base_url = ha_config.get("base_url")
|
base_url = ha_config.get("base_url")
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,10 @@ from core.handle.sendAudioHandle import send_stt_message
|
||||||
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
||||||
from core.utils.dialogue import Message
|
from core.utils.dialogue import Message
|
||||||
from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType
|
from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
@ -34,7 +38,7 @@ play_music_function_desc = {
|
||||||
|
|
||||||
|
|
||||||
@register_function("play_music", play_music_function_desc, ToolType.SYSTEM_CTL)
|
@register_function("play_music", play_music_function_desc, ToolType.SYSTEM_CTL)
|
||||||
def play_music(conn, song_name: str):
|
def play_music(conn: "ConnectionHandler", song_name: str):
|
||||||
try:
|
try:
|
||||||
music_intent = (
|
music_intent = (
|
||||||
f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐"
|
f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐"
|
||||||
|
|
@ -115,7 +119,7 @@ def get_music_files(music_dir, music_ext):
|
||||||
return music_files, music_file_names
|
return music_files, music_file_names
|
||||||
|
|
||||||
|
|
||||||
def initialize_music_handler(conn):
|
def initialize_music_handler(conn: "ConnectionHandler"):
|
||||||
global MUSIC_CACHE
|
global MUSIC_CACHE
|
||||||
if MUSIC_CACHE == {}:
|
if MUSIC_CACHE == {}:
|
||||||
plugins_config = conn.config.get("plugins", {})
|
plugins_config = conn.config.get("plugins", {})
|
||||||
|
|
@ -142,7 +146,7 @@ def initialize_music_handler(conn):
|
||||||
return MUSIC_CACHE
|
return MUSIC_CACHE
|
||||||
|
|
||||||
|
|
||||||
async def handle_music_command(conn, text):
|
async def handle_music_command(conn: "ConnectionHandler", text):
|
||||||
initialize_music_handler(conn)
|
initialize_music_handler(conn)
|
||||||
global MUSIC_CACHE
|
global MUSIC_CACHE
|
||||||
|
|
||||||
|
|
@ -188,7 +192,7 @@ def _get_random_play_prompt(song_name):
|
||||||
return random.choice(prompts)
|
return random.choice(prompts)
|
||||||
|
|
||||||
|
|
||||||
async def play_local_music(conn, specific_file=None):
|
async def play_local_music(conn: "ConnectionHandler", specific_file=None):
|
||||||
global MUSIC_CACHE
|
global MUSIC_CACHE
|
||||||
"""播放本地音乐文件"""
|
"""播放本地音乐文件"""
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,10 @@ import requests
|
||||||
import sys
|
import sys
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from core.connection import ConnectionHandler
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -24,7 +28,7 @@ SEARCH_FROM_RAGFLOW_FUNCTION_DESC = {
|
||||||
@register_function(
|
@register_function(
|
||||||
"search_from_ragflow", SEARCH_FROM_RAGFLOW_FUNCTION_DESC, ToolType.SYSTEM_CTL
|
"search_from_ragflow", SEARCH_FROM_RAGFLOW_FUNCTION_DESC, ToolType.SYSTEM_CTL
|
||||||
)
|
)
|
||||||
def search_from_ragflow(conn, question=None):
|
def search_from_ragflow(conn: "ConnectionHandler", question=None):
|
||||||
# 确保字符串参数正确处理编码
|
# 确保字符串参数正确处理编码
|
||||||
if question and isinstance(question, str):
|
if question and isinstance(question, str):
|
||||||
# 确保问题参数是UTF-8编码的字符串
|
# 确保问题参数是UTF-8编码的字符串
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@ loguru==0.7.3
|
||||||
requests==2.32.5
|
requests==2.32.5
|
||||||
cozepy==0.20.0
|
cozepy==0.20.0
|
||||||
mem0ai==1.0.0
|
mem0ai==1.0.0
|
||||||
|
powermem>=0.3.1
|
||||||
bs4==0.0.2
|
bs4==0.0.2
|
||||||
modelscope==1.32.0
|
modelscope==1.32.0
|
||||||
sherpa_onnx==1.12.17
|
sherpa_onnx==1.12.17
|
||||||
|
|
|
||||||
|
|
@ -108,26 +108,68 @@ body {
|
||||||
animation: shadow-float 1.26s ease-in-out infinite;
|
animation: shadow-float 1.26s ease-in-out infinite;
|
||||||
}
|
}
|
||||||
|
|
||||||
.loading-char-float .main-char span:nth-child(1) { animation-delay: 0s; }
|
.loading-char-float .main-char span:nth-child(1) {
|
||||||
.loading-char-float .main-char span:nth-child(2) { animation-delay: 0.11s; }
|
animation-delay: 0s;
|
||||||
.loading-char-float .main-char span:nth-child(3) { animation-delay: 0.22s; }
|
}
|
||||||
.loading-char-float .main-char span:nth-child(4) { animation-delay: 0.33s; }
|
|
||||||
.loading-char-float .main-char span:nth-child(5) { animation-delay: 0.44s; }
|
.loading-char-float .main-char span:nth-child(2) {
|
||||||
.loading-char-float .main-char span:nth-child(6) { animation-delay: 0.55s; }
|
animation-delay: 0.11s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-char-float .main-char span:nth-child(3) {
|
||||||
|
animation-delay: 0.22s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-char-float .main-char span:nth-child(4) {
|
||||||
|
animation-delay: 0.33s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-char-float .main-char span:nth-child(5) {
|
||||||
|
animation-delay: 0.44s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-char-float .main-char span:nth-child(6) {
|
||||||
|
animation-delay: 0.55s;
|
||||||
|
}
|
||||||
|
|
||||||
@keyframes scan {
|
@keyframes scan {
|
||||||
0% { background-position: 0 0; }
|
0% {
|
||||||
100% { background-position: 0 100px; }
|
background-position: 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
100% {
|
||||||
|
background-position: 0 100px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes char-float {
|
@keyframes char-float {
|
||||||
0%, 100% { transform: translateY(0); opacity: 1; text-shadow: 0 0 5px #5865f2, 0 0 10px rgba(88, 101, 242, 0.8); }
|
|
||||||
50% { transform: translateY(-5px); opacity: 0.9; text-shadow: 0 0 10px #5865f2, 0 0 20px rgba(88, 101, 242, 0.8); }
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: translateY(0);
|
||||||
|
opacity: 1;
|
||||||
|
text-shadow: 0 0 5px #5865f2, 0 0 10px rgba(88, 101, 242, 0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
50% {
|
||||||
|
transform: translateY(-5px);
|
||||||
|
opacity: 0.9;
|
||||||
|
text-shadow: 0 0 10px #5865f2, 0 0 20px rgba(88, 101, 242, 0.8);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes shadow-float {
|
@keyframes shadow-float {
|
||||||
0%, 100% { transform: translateY(3px); opacity: 0.3; }
|
|
||||||
50% { transform: translateY(8px); opacity: 0.15; }
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: translateY(3px);
|
||||||
|
opacity: 0.3;
|
||||||
|
}
|
||||||
|
|
||||||
|
50% {
|
||||||
|
transform: translateY(8px);
|
||||||
|
opacity: 0.15;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ==================== Live2D显示区域 ==================== */
|
/* ==================== Live2D显示区域 ==================== */
|
||||||
|
|
@ -402,6 +444,15 @@ body {
|
||||||
background: rgba(237, 66, 69, 1);
|
background: rgba(237, 66, 69, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 摄像头按钮特殊样式 */
|
||||||
|
#cameraBtn.camera-active {
|
||||||
|
background: rgba(237, 66, 69, 0.9);
|
||||||
|
}
|
||||||
|
|
||||||
|
#cameraBtn.camera-active:hover {
|
||||||
|
background: rgba(237, 66, 69, 1);
|
||||||
|
}
|
||||||
|
|
||||||
/* 录音按钮脉冲动画 */
|
/* 录音按钮脉冲动画 */
|
||||||
@keyframes pulse {
|
@keyframes pulse {
|
||||||
0% {
|
0% {
|
||||||
|
|
@ -761,6 +812,72 @@ body {
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.model-select {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px 40px 10px 14px;
|
||||||
|
border: 1px solid #40444b;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #40444b;
|
||||||
|
color: #ffffff;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
|
cursor: pointer;
|
||||||
|
appearance: none;
|
||||||
|
-webkit-appearance: none;
|
||||||
|
-moz-appearance: none;
|
||||||
|
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='%23ffffff'%3E%3Cpath d='M7 10l5 5 5-5z'/%3E%3C/svg%3E");
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
background-position: right 12px center;
|
||||||
|
background-size: 16px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.model-select:hover {
|
||||||
|
border-color: #5865f2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.model-select:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: #5865f2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.model-select option {
|
||||||
|
background: #2f3136;
|
||||||
|
color: #ffffff;
|
||||||
|
padding: 12px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.background-btn {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px 14px;
|
||||||
|
border: 1px solid #40444b;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #40444b;
|
||||||
|
color: #ffffff;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
|
cursor: pointer;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 8px;
|
||||||
|
transition: all 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.background-btn:hover {
|
||||||
|
background: #4f545c;
|
||||||
|
}
|
||||||
|
|
||||||
|
.background-btn:active {
|
||||||
|
background: #40444b;
|
||||||
|
}
|
||||||
|
|
||||||
|
.background-btn .btn-icon {
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
fill: #ffffff;
|
||||||
|
}
|
||||||
|
|
||||||
/* ==================== MCP工具样式 ==================== */
|
/* ==================== MCP工具样式 ==================== */
|
||||||
.mcp-tools-container {
|
.mcp-tools-container {
|
||||||
background: #2f3136;
|
background: #2f3136;
|
||||||
|
|
@ -787,17 +904,6 @@ body {
|
||||||
|
|
||||||
.mcp-tools-panel {
|
.mcp-tools-panel {
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
transition: max-height 0.3s ease;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
.mcp-tools-panel.expanded {
|
|
||||||
max-height: 500px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.mcp-tools-panel:not(.expanded) {
|
|
||||||
max-height: 0;
|
|
||||||
padding: 0 20px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.mcp-tools-list {
|
.mcp-tools-list {
|
||||||
|
|
@ -911,35 +1017,174 @@ body {
|
||||||
margin-bottom: 12px;
|
margin-bottom: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.property-item {
|
.properties-container #addMcpPropertyBtn {
|
||||||
|
display: block;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.properties-container #addMcpPropertyBtn:hover {
|
||||||
|
background: #4752c4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-checkbox-label {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 8px;
|
|
||||||
margin-bottom: 8px;
|
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 8px;
|
||||||
|
color: #b9bbbe;
|
||||||
|
font-size: 13px;
|
||||||
|
cursor: pointer;
|
||||||
|
justify-content: flex-start;
|
||||||
}
|
}
|
||||||
|
|
||||||
.property-item input {
|
.mcp-checkbox-label input[type="checkbox"] {
|
||||||
flex: 1;
|
width: 16px;
|
||||||
padding: 6px 8px;
|
height: 16px;
|
||||||
border: 1px solid #40444b;
|
cursor: pointer;
|
||||||
border-radius: 4px;
|
}
|
||||||
background: #40444b;
|
|
||||||
|
.mcp-property-name {
|
||||||
color: white;
|
color: white;
|
||||||
font-size: 12px;
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
.remove-property {
|
.mcp-property-header {
|
||||||
background: #ed4245;
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-properties-list {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 12px;
|
||||||
|
min-height: 60px;
|
||||||
|
padding: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-group-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-group-header label {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-group-header .properties-btn-primary {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-empty-state {
|
||||||
|
text-align: center;
|
||||||
|
padding: 20px;
|
||||||
|
color: #999;
|
||||||
|
font-size: 14px;
|
||||||
|
width: 100%;
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.properties-btn-primary {
|
||||||
|
background: #2196f3;
|
||||||
color: white;
|
color: white;
|
||||||
border: none;
|
border: none;
|
||||||
padding: 4px 8px;
|
padding: 6px 12px;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
|
font-weight: 500;
|
||||||
|
transition: background-color 0.2s;
|
||||||
|
display: block;
|
||||||
|
margin: 0 auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.remove-property:hover {
|
.properties-btn-primary:hover {
|
||||||
background: #c03537;
|
background: #2196f3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-property-card {
|
||||||
|
background: #36393f;
|
||||||
|
border: 1px solid #40444b;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 12px;
|
||||||
|
width: 100%;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-property-card:hover {
|
||||||
|
background: #40444b;
|
||||||
|
border-color: #5865f2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-property-card:active {
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-property-row-label {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-property-label {
|
||||||
|
color: #b9bbbe;
|
||||||
|
font-size: 13px;
|
||||||
|
width: 60px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-property-value {
|
||||||
|
color: white;
|
||||||
|
font-size: 13px;
|
||||||
|
flex: 1;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-property-required-badge {
|
||||||
|
color: #f44336;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-property-row-action {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
margin-top: 6px;
|
||||||
|
padding-top: 6px;
|
||||||
|
border-top: 1px solid #40444b;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-property-delete-btn {
|
||||||
|
background: #f44336;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 4px 12px;
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 11px;
|
||||||
|
transition: background-color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-property-delete-btn:hover {
|
||||||
|
background: #d32f2f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mcp-property-card-optional {
|
||||||
|
background: #4f545c;
|
||||||
|
color: #b9bbbe;
|
||||||
|
font-size: 11px;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.property-modal {
|
||||||
|
max-width: 450px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ==================== 音频可视化器样式 ==================== */
|
/* ==================== 音频可视化器样式 ==================== */
|
||||||
|
|
@ -956,6 +1201,113 @@ body {
|
||||||
z-index: 999;
|
z-index: 999;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 滚动条样式 */
|
||||||
|
.chat-stream::-webkit-scrollbar,
|
||||||
|
.modal-body::-webkit-scrollbar,
|
||||||
|
.mcp-tools-list::-webkit-scrollbar {
|
||||||
|
width: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-stream::-webkit-scrollbar-track,
|
||||||
|
.modal-body::-webkit-scrollbar-track,
|
||||||
|
.mcp-tools-list::-webkit-scrollbar-track {
|
||||||
|
background: #2f3136;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-stream::-webkit-scrollbar-thumb,
|
||||||
|
.modal-body::-webkit-scrollbar-thumb,
|
||||||
|
.mcp-tools-list::-webkit-scrollbar-thumb {
|
||||||
|
background: #40444b;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-stream::-webkit-scrollbar-thumb:hover,
|
||||||
|
.modal-body::-webkit-scrollbar-thumb:hover,
|
||||||
|
.mcp-tools-list::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: #4f545c;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ==================== 摄像头显示区域样式 ==================== */
|
||||||
|
.camera-container {
|
||||||
|
position: fixed;
|
||||||
|
top: 20px;
|
||||||
|
left: 20px;
|
||||||
|
width: 180px;
|
||||||
|
height: 240px;
|
||||||
|
background: rgba(0, 0, 0, 0.5);
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||||
|
z-index: 1000;
|
||||||
|
display: none;
|
||||||
|
overflow: hidden;
|
||||||
|
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
|
||||||
|
cursor: move;
|
||||||
|
}
|
||||||
|
|
||||||
|
.camera-container.active {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.camera-container.dragging {
|
||||||
|
cursor: grabbing;
|
||||||
|
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.4);
|
||||||
|
border-color: rgba(88, 101, 242, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes flipWithPosition {
|
||||||
|
0% {
|
||||||
|
transform: var(--original-transform) rotateY(0deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
100% {
|
||||||
|
transform: var(--original-transform) rotateY(180deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
.camera-container.flip {
|
||||||
|
animation: flipWithPosition 0.5s ease-in-out 1 forwards;
|
||||||
|
}
|
||||||
|
|
||||||
|
#cameraVideo {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
background: #1a1a1a;
|
||||||
|
pointer-events: none;
|
||||||
|
transform: scaleX(-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.camera-switch-mask {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.camera-switch-container {
|
||||||
|
position: absolute;
|
||||||
|
bottom: 10px;
|
||||||
|
right: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.camera-switch {
|
||||||
|
display: none;
|
||||||
|
height: 20px;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.camera-switch .btn-icon {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.camera-switch.active {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
/* ==================== 响应式设计 ==================== */
|
/* ==================== 响应式设计 ==================== */
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
.container {
|
.container {
|
||||||
|
|
@ -1019,6 +1371,19 @@ body {
|
||||||
left: 10px;
|
left: 10px;
|
||||||
bottom: 80px;
|
bottom: 80px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.chat-ipt input {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.camera-container {
|
||||||
|
width: 130px;
|
||||||
|
height: 180px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-indicator {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 480px) {
|
@media (max-width: 480px) {
|
||||||
|
|
@ -1098,31 +1463,4 @@ body {
|
||||||
width: 250px;
|
width: 250px;
|
||||||
height: 80px;
|
height: 80px;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/* 滚动条样式 */
|
|
||||||
.chat-stream::-webkit-scrollbar,
|
|
||||||
.modal-body::-webkit-scrollbar,
|
|
||||||
.mcp-tools-list::-webkit-scrollbar {
|
|
||||||
width: 6px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chat-stream::-webkit-scrollbar-track,
|
|
||||||
.modal-body::-webkit-scrollbar-track,
|
|
||||||
.mcp-tools-list::-webkit-scrollbar-track {
|
|
||||||
background: #2f3136;
|
|
||||||
border-radius: 3px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chat-stream::-webkit-scrollbar-thumb,
|
|
||||||
.modal-body::-webkit-scrollbar-thumb,
|
|
||||||
.mcp-tools-list::-webkit-scrollbar-thumb {
|
|
||||||
background: #40444b;
|
|
||||||
border-radius: 3px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chat-stream::-webkit-scrollbar-thumb:hover,
|
|
||||||
.modal-body::-webkit-scrollbar-thumb:hover,
|
|
||||||
.mcp-tools-list::-webkit-scrollbar-thumb:hover {
|
|
||||||
background: #4f545c;
|
|
||||||
}
|
}
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 142 KiB After Width: | Height: | Size: 136 KiB |
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue