Merge pull request #4 from Craftech360-projects/translated-to-english

tranlated to english server and mqtt folders
This commit is contained in:
rahulpscraftech360 2025-08-14 10:53:44 +05:30 committed by GitHub
commit a68b8ffa18
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
143 changed files with 7811 additions and 5873 deletions

View file

@ -1,78 +1,81 @@
# MQTT+UDP 到 WebSocket 桥接服务
# MQTT+UDP to WebSocket Bridge Service
## 项目概述
## Project Overview
这是一个用于物联网设备通信的桥接服务,实现了MQTT和UDP协议到WebSocket的转换。该服务允许设备通过MQTT协议进行控制消息传输,同时通过UDP协议高效传输音频数据,并将这些数据桥接到WebSocket服务。
This is a bridge service for IoT device communication that implements conversion from MQTT and UDP protocols to WebSocket. The service allows devices to transmit control messages through MQTT protocol while efficiently transmitting audio data through UDP protocol, bridging this data to WebSocket services.
## 功能特点
## Features
- **多协议支持**: 同时支持MQTT、UDP和WebSocket协议
- **音频数据传输**: 专为音频数据流优化的传输机制
- **加密通信**: 使用AES-128-CTR加密UDP数据传输
- **会话管理**: 完整的设备会话生命周期管理
- **自动重连**: 连接断开时自动重连机制
- **心跳检测**: 定期检查连接活跃状态
- **开发/生产环境配置**: 支持不同环境的配置切换
- **Multi-protocol Support**: Simultaneous support for MQTT, UDP, and WebSocket protocols
- **Audio Data Transmission**: Transmission mechanism optimized for audio data streams
- **Encrypted Communication**: Uses AES-128-CTR encryption for UDP data transmission
- **Session Management**: Complete device session lifecycle management
- **Auto Reconnection**: Automatic reconnection mechanism when connections are lost
- **Heartbeat Detection**: Periodic checking of connection active status
- **Development/Production Environment Configuration**: Support for configuration switching between different environments
## 技术架构
## Technical Architecture
- **MQTT服务器**: 处理设备控制消息
- **UDP服务器**: 处理高效的音频数据传输
- **WebSocket客户端**: 连接到聊天服务器
- **桥接层**: 在不同协议间转换和路由消息
- **MQTT Server**: Handles device control messages
- **UDP Server**: Handles efficient audio data transmission
- **WebSocket Client**: Connects to chat servers
- **Bridge Layer**: Converts and routes messages between different protocols
## 项目结构
## Project Structure
```
├── app.js # 主应用入口
├── mqtt-protocol.js # MQTT协议实现
├── ecosystem.config.js # PM2配置文件
├── package.json # 项目依赖
├── .env # 环境变量配置
├── app.js # Main application entry point
├── mqtt-protocol.js # MQTT protocol implementation
├── ecosystem.config.js # PM2 configuration file
├── package.json # Project dependencies
├── .env # Environment variable configuration
├── utils/
│ ├── config-manager.js # 配置管理工具
│ ├── mqtt_config_v2.js # MQTT配置验证工具
│ └── weixinAlert.js # 微信告警工具
└── config/ # 配置文件目录
│ ├── config-manager.js # Configuration management tool
│ ├── mqtt_config_v2.js # MQTT configuration validation tool
│ └── weixinAlert.js # WeChat alert tool
└── config/ # Configuration file directory
```
## 依赖项
## Dependencies
- **debug**: 调试日志输出
- **dotenv**: 环境变量管理
- **ws**: WebSocket客户端
- **events**: Node.js 事件模块
- **debug**: Debug log output
- **dotenv**: Environment variable management
- **ws**: WebSocket client
- **events**: Node.js event module
## 安装要求
## Installation Requirements
- Node.js 14.x 或更高版本
- npm 或 yarn 包管理器
- PM2 (用于生产环境部署)
- Node.js 14.x or higher
- npm or yarn package manager
- PM2 (for production environment deployment)
## 安装步骤
## Installation Steps
1. Clone repository
1. 克隆仓库
```bash
git clone <仓库地址>
git clone <repository-url>
cd mqtt-websocket-bridge
```
2. 安装依赖
2. Install dependencies
```bash
npm install
```
3. 创建配置文件
3. Create configuration file
```bash
mkdir -p config
cp config/mqtt.json.example config/mqtt.json
```
4. 编辑配置文件 `config/mqtt.json`,设置适当的参数
4. Edit configuration file `config/mqtt.json` and set appropriate parameters
## 配置说明
## Configuration Instructions
配置文件 `config/mqtt.json` 需要包含以下内容:
Configuration file `config/mqtt.json` needs to contain the following content:
```json
{
@ -87,63 +90,65 @@ cp config/mqtt.json.example config/mqtt.json
}
```
## 环境变量
## Environment Variables
创建 `.env` 文件并设置以下环境变量:
Create `.env` file and set the following environment variables:
```
MQTT_PORT=1883 # MQTT服务器端口
UDP_PORT=8884 # UDP服务器端口
PUBLIC_IP=your-ip # 服务器公网IP
MQTT_PORT=1883 # MQTT server port
UDP_PORT=8884 # UDP server port
PUBLIC_IP=your-ip # Server public IP
```
## 运行服务
## Running the Service
### 开发环境
### Development Environment
```bash
# 直接运行
# Run directly
node app.js
# 调试模式运行
# Run in debug mode
DEBUG=mqtt-server node app.js
```
### 生产环境 (使用PM2)
### Production Environment (Using PM2)
```bash
# 安装PM2
# Install PM2
npm install -g pm2
# 启动服务
# Start service
pm2 start ecosystem.config.js
# 查看日志
# View logs
pm2 logs xz-mqtt
# 监控服务
# Monitor service
pm2 monit
```
服务将在以下端口启动:
- MQTT 服务器: 端口 1883 (可通过环境变量修改)
- UDP 服务器: 端口 8884 (可通过环境变量修改)
The service will start on the following ports:
## 协议说明
- MQTT Server: Port 1883 (can be modified via environment variables)
- UDP Server: Port 8884 (can be modified via environment variables)
### 设备连接流程
## Protocol Description
1. 设备通过MQTT协议连接到服务器
2. 设备发送 `hello` 消息,包含音频参数和特性
3. 服务器创建WebSocket连接到聊天服务器
4. 服务器返回UDP连接参数给设备
5. 设备通过UDP发送音频数据
6. 服务器将音频数据转发到WebSocket
7. WebSocket返回的控制消息通过MQTT发送给设备
### Device Connection Flow
### 消息格式
1. Device connects to server via MQTT protocol
2. Device sends `hello` message containing audio parameters and features
3. Server creates WebSocket connection to chat server
4. Server returns UDP connection parameters to device
5. Device sends audio data via UDP
6. Server forwards audio data to WebSocket
7. Control messages returned by WebSocket are sent to device via MQTT
### Message Format
#### Hello Message (Device -> Server)
#### Hello 消息 (设备 -> 服务器)
```json
{
"type": "hello",
@ -153,7 +158,8 @@ pm2 monit
}
```
#### Hello 响应 (服务器 -> 设备)
#### Hello Response (Server -> Device)
```json
{
"type": "hello",
@ -171,45 +177,45 @@ pm2 monit
}
```
## 安全说明
## Security Description
- UDP通信使用AES-128-CTR加密
- 每个会话使用唯一的加密密钥
- 使用序列号防止重放攻击
- 设备通过MAC地址进行身份验证
- 支持设备分组和UUID验证
- UDP communication uses AES-128-CTR encryption
- Each session uses a unique encryption key
- Uses sequence numbers to prevent replay attacks
- Device authentication via MAC address
- Supports device grouping and UUID verification
## 性能优化
## Performance Optimization
- 使用预分配的缓冲区减少内存分配
- UDP协议用于高效传输音频数据
- 定期清理不活跃的连接
- 连接数和活跃连接数监控
- 支持多聊天服务器负载均衡
- Uses pre-allocated buffers to reduce memory allocation
- UDP protocol for efficient audio data transmission
- Periodic cleanup of inactive connections
- Connection count and active connection monitoring
- Support for multi-chat server load balancing
## 故障排除
## Troubleshooting
- 检查设备MAC地址格式是否正确
- 确保UDP端口在防火墙中开放
- 启用调试模式查看详细日志
- 检查配置文件中的聊天服务器地址是否正确
- 验证设备认证信息是否正确
- Check if device MAC address format is correct
- Ensure UDP port is open in firewall
- Enable debug mode to view detailed logs
- Check if chat server address in configuration file is correct
- Verify device authentication information is correct
## 开发指南
## Development Guide
### 添加新功能
### Adding New Features
1. 修改 `mqtt-protocol.js` 以支持新的MQTT功能
2. 在 `MQTTConnection` 类中添加新的消息处理方法
3. 更新配置管理器以支持新的配置选项
4. 在 `WebSocketBridge` 类中添加新的WebSocket处理逻辑
1. Modify `mqtt-protocol.js` to support new MQTT functionality
2. Add new message handling methods in `MQTTConnection` class
3. Update configuration manager to support new configuration options
4. Add new WebSocket handling logic in `WebSocketBridge` class
### 调试技巧
### Debugging Tips
```bash
# 启用所有调试输出
# Enable all debug output
DEBUG=* node app.js
# 只启用MQTT服务器调试
# Enable only MQTT server debugging
DEBUG=mqtt-server node app.js
```

File diff suppressed because it is too large Load diff

View file

@ -1,81 +1,78 @@
#!/usr/bin/env node
/**
* MQTT签名密钥生成器
* 用于生成MQTT_SIGNATURE_KEY环境变量
*/
/**
* MQTT signature key generator
* Used to generate MQTT_SIGNATURE_KEY environment variable
*/
const crypto = require('crypto');
function generateSecureKey(length = 32) {
// 生成随机字节
// Generate random bytes
const randomBytes = crypto.randomBytes(length);
// 转换为base64字符串
// Convert to base64 string
const base64Key = randomBytes.toString('base64');
return base64Key;
}
function generateHexKey(length = 32) {
// 生成随机字节
// Generate random bytes
const randomBytes = crypto.randomBytes(length);
// 转换为十六进制字符串
// Convert to hexadecimal string
const hexKey = randomBytes.toString('hex');
return hexKey;
}
function generateUUIDKey() {
// 使用UUID v4作为密钥
// Use UUID v4 as key
const uuid = crypto.randomUUID();
return uuid;
}
console.log('='.repeat(60));
console.log('MQTT签名密钥生成器');
console.log('MQTT Signature Key Generator');
console.log('='.repeat(60));
console.log('\n1. Base64格式密钥 (推荐):');
console.log('\n1. Base64 format key (recommended):');
const base64Key = generateSecureKey();
console.log(` ${base64Key}`);
console.log(` ${base64Key}`);
console.log('\n2. 十六进制格式密钥:');
console.log('\n2. Hexadecimal format key:');
const hexKey = generateHexKey();
console.log(` ${hexKey}`);
console.log(` ${hexKey}`);
console.log('\n3. UUID格式密钥:');
console.log('\n3. UUID format key:');
const uuidKey = generateUUIDKey();
console.log(` ${uuidKey}`);
console.log(` ${uuidKey}`);
console.log('\n='.repeat(60));
console.log('使用方法:');
console.log('Usage:');
console.log('='.repeat(60));
console.log('\n在Windows PowerShell中设置环境变量:');
console.log('\nSet environment variable in Windows PowerShell:');
console.log(`$env:MQTT_SIGNATURE_KEY="${base64Key}"`);
console.log('\n在Windows CMD中设置环境变量:');
console.log('\nSet environment variable in Windows CMD:');
console.log(`set MQTT_SIGNATURE_KEY=${base64Key}`);
console.log('\n在Linux/macOS中设置环境变量:');
console.log('\nSet environment variable in Linux/macOS:');
console.log(`export MQTT_SIGNATURE_KEY="${base64Key}"`);
console.log('\n在.env文件中设置:');
console.log('\nSet in .env file:');
console.log(`MQTT_SIGNATURE_KEY=${base64Key}`);
console.log('\n='.repeat(60));
console.log('注意事项:');
console.log('Notes:');
console.log('='.repeat(60));
console.log('1. 请妥善保管生成的密钥,不要泄露给他人');
console.log('2. 在生产环境中,建议使用更长的密钥 (64字节)');
console.log('3. 密钥设置后需要重启MQTT服务器才能生效');
console.log('4. 客户端连接时需要使用相同的密钥生成密码签名');
console.log('1. Please keep the generated key secure and do not leak it to others');
console.log('2. In production environment, longer keys are recommended (64 bytes)');
console.log('3. MQTT server needs to be restarted after setting the key');
console.log('4. Clients need to use the same key to generate password signatures when connecting');
// 如果提供了命令行参数,生成指定长度的密钥
// If command line arguments are provided, generate key with specified length
if (process.argv[2]) {
const customLength = parseInt(process.argv[2]);
if (customLength > 0) {
console.log(`\n自定义长度密钥 (${customLength}字节):`);
console.log(` ${generateSecureKey(customLength)}`);
console.log(`\nCustom length key (${customLength} bytes):`);
console.log(` ${generateSecureKey(customLength)}`);
}
}
}

View file

@ -1,499 +1,513 @@
const debug = require('debug')('mqtt-server');
const EventEmitter = require('events');
const debug = require("debug")("mqtt-server");
const EventEmitter = require("events");
// MQTT 固定头部的类型
// MQTT fixed header types
const PacketType = {
CONNECT: 1,
CONNACK: 2,
PUBLISH: 3,
SUBSCRIBE: 8,
SUBACK: 9,
PINGREQ: 12,
PINGRESP: 13,
DISCONNECT: 14 // 添加 DISCONNECT
CONNECT: 1,
CONNACK: 2,
PUBLISH: 3,
SUBSCRIBE: 8,
SUBACK: 9,
PINGREQ: 12,
PINGRESP: 13,
DISCONNECT: 14, // Added DISCONNECT
};
/**
* MQTT协议处理类
* 负责MQTT协议的解析和封装,以及心跳维持
* MQTT protocol handler class
* Responsible for MQTT protocol parsing and encapsulation, as well as heartbeat maintenance
*/
class MQTTProtocol extends EventEmitter {
constructor(socket) {
super();
this.socket = socket;
constructor(socket) {
super();
this.socket = socket;
this.buffer = Buffer.alloc(0);
this.isConnected = false;
this.keepAliveInterval = 0;
this.lastActivity = Date.now();
this.setupSocketHandlers();
}
/**
* Set up Socket event handlers
*/
setupSocketHandlers() {
this.socket.on("data", (data) => {
this.lastActivity = Date.now();
this.buffer = Buffer.concat([this.buffer, data]);
this.processBuffer();
});
this.socket.on("close", () => {
this.emit("close");
});
this.socket.on("error", (err) => {
this.emit("error", err);
});
}
/**
* Process all complete messages in buffer
*/
processBuffer() {
// Continue processing data in buffer until no complete messages can be processed
while (this.buffer.length > 0) {
// At least 2 bytes needed to start parsing (1 byte fixed header + at least 1 byte remaining length)
if (this.buffer.length < 2) return;
try {
// Get message type
const firstByte = this.buffer[0];
const type = firstByte >> 4;
// Parse remaining length
const { value: remainingLength, bytesRead } =
this.decodeRemainingLength(this.buffer);
// Calculate total message length
const messageLength = 1 + bytesRead + remainingLength;
// Check if buffer has complete message
if (this.buffer.length < messageLength) {
// Message incomplete, wait for more data
return;
}
// Extract complete message
const message = this.buffer.subarray(0, messageLength);
if (!this.isConnected && type !== PacketType.CONNECT) {
debug(
"Received non-CONNECT message when not connected, closing connection"
);
this.socket.end();
return;
}
// Process based on message type
switch (type) {
case PacketType.CONNECT:
this.parseConnect(message);
break;
case PacketType.PUBLISH:
this.parsePublish(message);
break;
case PacketType.SUBSCRIBE:
this.parseSubscribe(message);
break;
case PacketType.PINGREQ:
this.parsePingReq(message);
break;
case PacketType.DISCONNECT:
this.parseDisconnect(message);
break;
default:
debug("Unhandled packet type:", type, message);
this.emit(
"protocolError",
new Error(`Unhandled packet type: ${type}`)
);
}
// Remove processed message from buffer
this.buffer = this.buffer.subarray(messageLength);
} catch (err) {
// If parsing error, might be incomplete data, wait for more data
if (err.message === "Malformed Remaining Length") {
return;
}
// Other errors might be protocol errors, clear buffer and emit error event
this.buffer = Buffer.alloc(0);
this.isConnected = false;
this.keepAliveInterval = 0;
this.lastActivity = Date.now();
this.setupSocketHandlers();
this.emit("protocolError", err);
return;
}
}
}
/**
* Parse Remaining Length field in MQTT packet
* @param {Buffer} buffer - Message buffer
* @returns {{value: number, bytesRead: number}} Contains parsed value and bytes read
*/
decodeRemainingLength(buffer) {
let multiplier = 1;
let value = 0;
let bytesRead = 0;
let digit;
do {
if (bytesRead >= 4 || bytesRead >= buffer.length - 1) {
throw new Error("Malformed Remaining Length");
}
digit = buffer[bytesRead + 1];
bytesRead++;
value += (digit & 127) * multiplier;
multiplier *= 128;
} while ((digit & 128) !== 0);
return { value, bytesRead };
}
/**
* Encode Remaining Length field in MQTT packet
* @param {number} length - Length value to encode
* @returns {{bytes: Buffer, bytesLength: number}} Contains encoded bytes and byte length
*/
encodeRemainingLength(length) {
let digit;
const bytes = Buffer.alloc(4); // Maximum 4 bytes
let bytesLength = 0;
do {
digit = length % 128;
length = Math.floor(length / 128);
// If more bytes remain, set high bit
if (length > 0) {
digit |= 0x80;
}
bytes[bytesLength++] = digit;
} while (length > 0 && bytesLength < 4);
return { bytes, bytesLength };
}
/**
* Parse CONNECT message
* @param {Buffer} message - Complete CONNECT message
*/
parseConnect(message) {
// Parse remaining length
const { value: remainingLength, bytesRead } =
this.decodeRemainingLength(message);
// Position after fixed header (MQTT fixed header first byte + Remaining Length field bytes)
const headerLength = 1 + bytesRead;
// Read protocol name length from variable header start position
const protocolLength = message.readUInt16BE(headerLength);
const protocol = message.toString(
"utf8",
headerLength + 2,
headerLength + 2 + protocolLength
);
// Update position pointer, skip protocol name
let pos = headerLength + 2 + protocolLength;
// Protocol level, 4 for MQTT 3.1.1
const protocolLevel = message[pos];
// Check protocol version
if (protocolLevel !== 4) {
// 4 represents MQTT 3.1.1
debug("Unsupported protocol version:", protocolLevel);
// Send CONNACK with unsupported protocol version return code (0x01)
this.sendConnack(1, false);
// Close connection
this.socket.end();
return;
}
/**
* 设置Socket事件处理
*/
setupSocketHandlers() {
this.socket.on('data', (data) => {
this.lastActivity = Date.now();
this.buffer = Buffer.concat([this.buffer, data]);
this.processBuffer();
});
pos += 1;
// Connection flags
const connectFlags = message[pos];
const hasUsername = (connectFlags & 0x80) !== 0;
const hasPassword = (connectFlags & 0x40) !== 0;
const cleanSession = (connectFlags & 0x02) !== 0;
pos += 1;
this.socket.on('close', () => {
this.emit('close');
});
// Keep alive time
const keepAlive = message.readUInt16BE(pos);
pos += 2;
this.socket.on('error', (err) => {
this.emit('error', err);
});
// Parse clientId
const clientIdLength = message.readUInt16BE(pos);
pos += 2;
const clientId = message.toString("utf8", pos, pos + clientIdLength);
pos += clientIdLength;
// Parse username (if exists)
let username = "";
if (hasUsername) {
const usernameLength = message.readUInt16BE(pos);
pos += 2;
username = message.toString("utf8", pos, pos + usernameLength);
pos += usernameLength;
}
/**
* 处理缓冲区中的所有完整消息
*/
processBuffer() {
// 持续处理缓冲区中的数据,直到没有完整的消息可以处理
while (this.buffer.length > 0) {
// 至少需要2个字节才能开始解析(1字节固定头部 + 至少1字节的剩余长度)
if (this.buffer.length < 2) return;
try {
// 获取消息类型
const firstByte = this.buffer[0];
const type = (firstByte >> 4);
// 解析剩余长度
const { value: remainingLength, bytesRead } = this.decodeRemainingLength(this.buffer);
// 计算整个消息的长度
const messageLength = 1 + bytesRead + remainingLength;
// 检查缓冲区中是否有完整的消息
if (this.buffer.length < messageLength) {
// 消息不完整,等待更多数据
return;
}
// 提取完整的消息
const message = this.buffer.subarray(0, messageLength);
if (!this.isConnected && type !== PacketType.CONNECT) {
debug('未连接时收到非CONNECT消息,关闭连接');
this.socket.end();
return;
}
// 根据消息类型处理
switch (type) {
case PacketType.CONNECT:
this.parseConnect(message);
break;
case PacketType.PUBLISH:
this.parsePublish(message);
break;
case PacketType.SUBSCRIBE:
this.parseSubscribe(message);
break;
case PacketType.PINGREQ:
this.parsePingReq(message);
break;
case PacketType.DISCONNECT:
this.parseDisconnect(message);
break;
default:
debug('未处理的包类型:', type, message);
this.emit('protocolError', new Error(`未处理的包类型: ${type}`));
}
// 从缓冲区中移除已处理的消息
this.buffer = this.buffer.subarray(messageLength);
} catch (err) {
// 如果解析出错,可能是数据不完整,等待更多数据
if (err.message === 'Malformed Remaining Length') {
return;
}
// 其他错误可能是协议错误,清空缓冲区并发出错误事件
this.buffer = Buffer.alloc(0);
this.emit('protocolError', err);
return;
}
}
// Parse password (if exists)
let password = "";
if (hasPassword) {
const passwordLength = message.readUInt16BE(pos);
pos += 2;
password = message.toString("utf8", pos, pos + passwordLength);
pos += passwordLength;
}
/**
* 解析MQTT报文中的Remaining Length字段
* @param {Buffer} buffer - 消息缓冲区
* @returns {{value: number, bytesRead: number}} 包含解析的值和读取的字节数
*/
decodeRemainingLength(buffer) {
let multiplier = 1;
let value = 0;
let bytesRead = 0;
let digit;
// Set heartbeat interval (1.5 times client-specified keepAlive value, in seconds)
this.keepAliveInterval = keepAlive * 1000 * 1.5;
do {
if (bytesRead >= 4 || bytesRead >= buffer.length - 1) {
throw new Error('Malformed Remaining Length');
}
digit = buffer[bytesRead + 1];
bytesRead++;
value += (digit & 127) * multiplier;
multiplier *= 128;
} while ((digit & 128) !== 0);
// Send CONNACK
this.sendConnack(0, false);
return { value, bytesRead };
// Mark as connected
this.isConnected = true;
// Emit connection event
this.emit("connect", {
clientId,
protocol,
protocolLevel,
keepAlive,
username,
password,
cleanSession,
});
}
/**
* Parse PUBLISH message
* @param {Buffer} message - Complete PUBLISH message
*/
parsePublish(message) {
// Extract QoS level from first byte (bits 1-2)
const firstByte = message[0];
const qos = (firstByte & 0x06) >> 1; // 0x06 is binary 00000110, used as mask to extract QoS bits
const dup = (firstByte & 0x08) !== 0; // 0x08 is binary 00001000, used as mask to extract DUP flag
const retain = (firstByte & 0x01) !== 0; // 0x01 is binary 00000001, used as mask to extract RETAIN flag
// Use common method to parse remaining length
const { value: remainingLength, bytesRead } =
this.decodeRemainingLength(message);
// Position after fixed header (MQTT fixed header first byte + Remaining Length field bytes)
const headerLength = 1 + bytesRead;
// Parse topic
const topicLength = message.readUInt16BE(headerLength);
const topic = message.toString(
"utf8",
headerLength + 2,
headerLength + 2 + topicLength
);
// For QoS > 0, includes message ID
let packetId = null;
let payloadStart = headerLength + 2 + topicLength;
if (qos > 0) {
packetId = message.readUInt16BE(payloadStart);
payloadStart += 2;
}
/**
* 编码MQTT报文中的Remaining Length字段
* @param {number} length - 要编码的长度值
* @returns {{bytes: Buffer, bytesLength: number}} 包含编码后的字节和字节长度
*/
encodeRemainingLength(length) {
let digit;
const bytes = Buffer.alloc(4); // 最多4个字节
let bytesLength = 0;
do {
digit = length % 128;
length = Math.floor(length / 128);
// 如果还有更多字节,设置最高位
if (length > 0) {
digit |= 0x80;
}
bytes[bytesLength++] = digit;
} while (length > 0 && bytesLength < 4);
return { bytes, bytesLength };
// Parse payload
const payload = message.slice(payloadStart).toString("utf8");
// Emit publish event
this.emit("publish", {
topic,
payload,
qos,
dup,
retain,
packetId,
});
}
/**
* Parse SUBSCRIBE message
* @param {Buffer} message - Complete SUBSCRIBE message
*/
parseSubscribe(message) {
const packetId = message.readUInt16BE(2);
const topicLength = message.readUInt16BE(4);
const topic = message.toString("utf8", 6, 6 + topicLength);
const qos = message[6 + topicLength]; // QoS value
// Emit subscribe event
this.emit("subscribe", {
packetId,
topic,
qos,
});
}
/**
* Parse PINGREQ message
* @param {Buffer} message - Complete PINGREQ message
*/
parsePingReq(message) {
debug("Received heartbeat request");
// Send PINGRESP
this.sendPingResp();
debug("Sent heartbeat response");
}
/**
* Parse DISCONNECT message
* @param {Buffer} message - Complete DISCONNECT message
*/
parseDisconnect(message) {
// Mark as disconnected
this.isConnected = false;
// Emit disconnect event
this.emit("disconnect");
// Close socket
this.socket.end();
}
/**
* Send CONNACK message
* @param {number} returnCode - Return code
* @param {boolean} sessionPresent - Session present flag
*/
sendConnack(returnCode = 0, sessionPresent = false) {
if (!this.socket.writable) return;
const packet = Buffer.from([
PacketType.CONNACK << 4,
2, // Remaining length
sessionPresent ? 1 : 0, // Connect acknowledge flags
returnCode, // Return code
]);
this.socket.write(packet);
}
/**
* Send PUBLISH message
* @param {string} topic - Topic
* @param {string} payload - Payload
* @param {number} qos - QoS level
* @param {boolean} dup - Duplicate flag
* @param {boolean} retain - Retain flag
* @param {number} packetId - Packet ID (only needed when QoS > 0)
*/
sendPublish(
topic,
payload,
qos = 0,
dup = false,
retain = false,
packetId = null
) {
if (!this.isConnected || !this.socket.writable) return;
const topicLength = Buffer.byteLength(topic);
const payloadLength = Buffer.byteLength(payload);
// Calculate remaining length
let remainingLength = 2 + topicLength + payloadLength;
// If QoS > 0, need to include packet ID
if (qos > 0 && packetId) {
remainingLength += 2;
}
/**
* 解析CONNECT消息
* @param {Buffer} message - 完整的CONNECT消息
*/
parseConnect(message) {
// 解析剩余长度
const { value: remainingLength, bytesRead } = this.decodeRemainingLength(message);
// 固定头部之后的位置 (MQTT固定头部第一个字节 + Remaining Length字段的字节)
const headerLength = 1 + bytesRead;
// 从可变头部开始位置读取协议名长度
const protocolLength = message.readUInt16BE(headerLength);
const protocol = message.toString('utf8', headerLength + 2, headerLength + 2 + protocolLength);
// 更新位置指针,跳过协议名
let pos = headerLength + 2 + protocolLength;
// 协议级别,4为MQTT 3.1.1
const protocolLevel = message[pos];
// 检查协议版本
if (protocolLevel !== 4) { // 4 表示 MQTT 3.1.1
debug('不支持的协议版本:', protocolLevel);
// 发送 CONNACK,使用不支持的协议版本的返回码 (0x01)
this.sendConnack(1, false);
// 关闭连接
this.socket.end();
return;
}
pos += 1;
// 连接标志
const connectFlags = message[pos];
const hasUsername = (connectFlags & 0x80) !== 0;
const hasPassword = (connectFlags & 0x40) !== 0;
const cleanSession = (connectFlags & 0x02) !== 0;
pos += 1;
// 保持连接时间
const keepAlive = message.readUInt16BE(pos);
pos += 2;
// 解析 clientId
const clientIdLength = message.readUInt16BE(pos);
pos += 2;
const clientId = message.toString('utf8', pos, pos + clientIdLength);
pos += clientIdLength;
// Encode variable length
const { bytes: remainingLengthBytes, bytesLength: remainingLengthSize } =
this.encodeRemainingLength(remainingLength);
// 解析 username(如果存在)
let username = '';
if (hasUsername) {
const usernameLength = message.readUInt16BE(pos);
pos += 2;
username = message.toString('utf8', pos, pos + usernameLength);
pos += usernameLength;
}
// Allocate buffer: fixed header(1 byte) + variable length field + remaining length value
const packet = Buffer.alloc(1 + remainingLengthSize + remainingLength);
// 解析 password(如果存在)
let password = '';
if (hasPassword) {
const passwordLength = message.readUInt16BE(pos);
pos += 2;
password = message.toString('utf8', pos, pos + passwordLength);
pos += passwordLength;
}
// Write fixed header
let firstByte = PacketType.PUBLISH << 4;
if (dup) firstByte |= 0x08;
if (qos > 0) firstByte |= qos << 1;
if (retain) firstByte |= 0x01;
packet[0] = firstByte;
// 设置心跳间隔(客户端指定的keepAlive值的1.5倍,单位为秒)
this.keepAliveInterval = keepAlive * 1000 * 1.5;
// 发送 CONNACK
this.sendConnack(0, false);
// 标记为已连接
this.isConnected = true;
// 发出连接事件
this.emit('connect', {
clientId,
protocol,
protocolLevel,
keepAlive,
username,
password,
cleanSession
});
// Write variable length field
remainingLengthBytes.copy(packet, 1, 0, remainingLengthSize);
// Write topic length and topic
const variableHeaderStart = 1 + remainingLengthSize;
packet.writeUInt16BE(topicLength, variableHeaderStart);
packet.write(topic, variableHeaderStart + 2);
// If QoS > 0, write packet ID
let payloadStart = variableHeaderStart + 2 + topicLength;
if (qos > 0 && packetId) {
packet.writeUInt16BE(packetId, payloadStart);
payloadStart += 2;
}
/**
* 解析PUBLISH消息
* @param {Buffer} message - 完整的PUBLISH消息
*/
parsePublish(message) {
// 从第一个字节中提取QoS级别(bits 1-2)
const firstByte = message[0];
const qos = (firstByte & 0x06) >> 1; // 0x06 是二进制 00000110,用于掩码提取QoS位
const dup = (firstByte & 0x08) !== 0; // 0x08 是二进制 00001000,用于掩码提取DUP标志
const retain = (firstByte & 0x01) !== 0; // 0x01 是二进制 00000001,用于掩码提取RETAIN标志
// 使用通用方法解析剩余长度
const { value: remainingLength, bytesRead } = this.decodeRemainingLength(message);
// 固定头部之后的位置 (MQTT固定头部第一个字节 + Remaining Length字段的字节)
const headerLength = 1 + bytesRead;
// 解析主题
const topicLength = message.readUInt16BE(headerLength);
const topic = message.toString('utf8', headerLength + 2, headerLength + 2 + topicLength);
// 对于QoS > 0,包含消息ID
let packetId = null;
let payloadStart = headerLength + 2 + topicLength;
if (qos > 0) {
packetId = message.readUInt16BE(payloadStart);
payloadStart += 2;
}
// 解析有效载荷
const payload = message.slice(payloadStart).toString('utf8');
// 发出发布事件
this.emit('publish', {
topic,
payload,
qos,
dup,
retain,
packetId
});
}
// Write payload
packet.write(payload, payloadStart);
/**
* 解析SUBSCRIBE消息
* @param {Buffer} message - 完整的SUBSCRIBE消息
*/
parseSubscribe(message) {
const packetId = message.readUInt16BE(2);
const topicLength = message.readUInt16BE(4);
const topic = message.toString('utf8', 6, 6 + topicLength);
const qos = message[6 + topicLength]; // QoS值
// 发出订阅事件
this.emit('subscribe', {
packetId,
topic,
qos
});
}
this.socket.write(packet);
this.lastActivity = Date.now();
}
/**
* 解析PINGREQ消息
* @param {Buffer} message - 完整的PINGREQ消息
*/
parsePingReq(message) {
debug('收到心跳请求');
// 发送 PINGRESP
this.sendPingResp();
debug('已发送心跳响应');
}
/**
* Send SUBACK message
* @param {number} packetId - Packet ID
* @param {number} returnCode - Return code
*/
sendSuback(packetId, returnCode = 0) {
if (!this.isConnected || !this.socket.writable) return;
/**
* 解析DISCONNECT消息
* @param {Buffer} message - 完整的DISCONNECT消息
*/
parseDisconnect(message) {
// 标记为未连接
this.isConnected = false;
// 发出断开连接事件
this.emit('disconnect');
// 关闭 socket
this.socket.end();
}
const packet = Buffer.from([
PacketType.SUBACK << 4,
3, // Remaining length
packetId >> 8, // Packet ID MSB
packetId & 0xff, // Packet ID LSB
returnCode, // Return code
]);
/**
* 发送CONNACK消息
* @param {number} returnCode - 返回码
* @param {boolean} sessionPresent - 会话存在标志
*/
sendConnack(returnCode = 0, sessionPresent = false) {
if (!this.socket.writable) return;
const packet = Buffer.from([
PacketType.CONNACK << 4,
2, // Remaining length
sessionPresent ? 1 : 0, // Connect acknowledge flags
returnCode // Return code
]);
this.socket.write(packet);
}
this.socket.write(packet);
this.lastActivity = Date.now();
}
/**
* 发送PUBLISH消息
* @param {string} topic - 主题
* @param {string} payload - 有效载荷
* @param {number} qos - QoS级别
* @param {boolean} dup - 重复标志
* @param {boolean} retain - 保留标志
* @param {number} packetId - 包ID(仅QoS > 0时需要)
*/
sendPublish(topic, payload, qos = 0, dup = false, retain = false, packetId = null) {
if (!this.isConnected || !this.socket.writable) return;
const topicLength = Buffer.byteLength(topic);
const payloadLength = Buffer.byteLength(payload);
// 计算剩余长度
let remainingLength = 2 + topicLength + payloadLength;
// 如果QoS > 0,需要包含包ID
if (qos > 0 && packetId) {
remainingLength += 2;
}
// 编码可变长度
const { bytes: remainingLengthBytes, bytesLength: remainingLengthSize } = this.encodeRemainingLength(remainingLength);
// 分配缓冲区:固定头部(1字节) + 可变长度字段 + 剩余长度值
const packet = Buffer.alloc(1 + remainingLengthSize + remainingLength);
// 写入固定头部
let firstByte = PacketType.PUBLISH << 4;
if (dup) firstByte |= 0x08;
if (qos > 0) firstByte |= (qos << 1);
if (retain) firstByte |= 0x01;
packet[0] = firstByte;
// 写入可变长度字段
remainingLengthBytes.copy(packet, 1, 0, remainingLengthSize);
// 写入主题长度和主题
const variableHeaderStart = 1 + remainingLengthSize;
packet.writeUInt16BE(topicLength, variableHeaderStart);
packet.write(topic, variableHeaderStart + 2);
// 如果QoS > 0,写入包ID
let payloadStart = variableHeaderStart + 2 + topicLength;
if (qos > 0 && packetId) {
packet.writeUInt16BE(packetId, payloadStart);
payloadStart += 2;
}
// 写入有效载荷
packet.write(payload, payloadStart);
this.socket.write(packet);
this.lastActivity = Date.now();
}
/**
* Send PINGRESP message
*/
sendPingResp() {
if (!this.isConnected || !this.socket.writable) return;
/**
* 发送SUBACK消息
* @param {number} packetId - 包ID
* @param {number} returnCode - 返回码
*/
sendSuback(packetId, returnCode = 0) {
if (!this.isConnected || !this.socket.writable) return;
const packet = Buffer.from([
PacketType.SUBACK << 4,
3, // Remaining length
packetId >> 8, // Packet ID MSB
packetId & 0xFF, // Packet ID LSB
returnCode // Return code
]);
this.socket.write(packet);
this.lastActivity = Date.now();
}
const packet = Buffer.from([
PacketType.PINGRESP << 4, // Fixed header
0, // Remaining length
]);
/**
* 发送PINGRESP消息
*/
sendPingResp() {
if (!this.isConnected || !this.socket.writable) return;
const packet = Buffer.from([
PacketType.PINGRESP << 4, // Fixed header
0 // Remaining length
]);
this.socket.write(packet);
this.lastActivity = Date.now();
}
this.socket.write(packet);
this.lastActivity = Date.now();
}
/**
* 获取上次活动时间
*/
getLastActivity() {
return this.lastActivity;
}
/**
* Get last activity time
*/
getLastActivity() {
return this.lastActivity;
}
/**
* 获取心跳间隔
*/
getKeepAliveInterval() {
return this.keepAliveInterval;
}
/**
* Get heartbeat interval
*/
getKeepAliveInterval() {
return this.keepAliveInterval;
}
/**
* 清空缓冲区
*/
clearBuffer() {
this.buffer = Buffer.alloc(0);
}
/**
* Clear buffer
*/
clearBuffer() {
this.buffer = Buffer.alloc(0);
}
/**
* 关闭连接
*/
close() {
if (this.socket.writable) {
this.socket.end();
}
/**
* Close connection
*/
close() {
if (this.socket.writable) {
this.socket.end();
}
}
}
// 导出 PacketType 和 MQTTProtocol 类
// Export PacketType and MQTTProtocol class
module.exports = {
PacketType,
MQTTProtocol
};
PacketType,
MQTTProtocol,
};

View file

@ -3,76 +3,75 @@ const path = require('path');
const EventEmitter = require('events');
class ConfigManager extends EventEmitter {
constructor(fileName) {
super();
this.config = {}; // 移除默认的 apiKeys 配置
this.configPath = path.join(__dirname, "..", "config", fileName);
this.loadConfig();
this.watchConfig();
// 添加防抖计时器变量
this.watchDebounceTimer = null;
}
loadConfig() {
try {
const data = fs.readFileSync(this.configPath, 'utf8');
const newConfig = JSON.parse(data);
// 检测配置是否发生变化
if (JSON.stringify(this.config) !== JSON.stringify(newConfig)) {
console.log('配置已更新', this.configPath);
this.config = newConfig;
// 发出配置更新事件
this.emit('configChanged', this.config);
}
} catch (error) {
console.error('加载配置出错:', error, this.configPath);
if (error.code === 'ENOENT') {
this.createEmptyConfig();
}
constructor(fileName) {
super();
this.config = {}; // Remove default apiKeys configuration
this.configPath = path.join(__dirname, "..", "config", fileName);
this.loadConfig();
this.watchConfig();
// Add debounce timer variable
this.watchDebounceTimer = null;
}
}
createEmptyConfig() {
try {
const dir = path.dirname(this.configPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const defaultConfig = {}; // 空配置对象
fs.writeFileSync(this.configPath, JSON.stringify(defaultConfig, null, 2));
console.log('已创建空配置文件', this.configPath);
} catch (error) {
console.error('创建空配置文件出错:', error, this.configPath);
}
}
watchConfig() {
fs.watch(path.dirname(this.configPath), (eventType, filename) => {
if (filename === path.basename(this.configPath) && eventType === 'change') {
// 清除之前的计时器
if (this.watchDebounceTimer) {
clearTimeout(this.watchDebounceTimer);
loadConfig() {
try {
const data = fs.readFileSync(this.configPath, 'utf8');
const newConfig = JSON.parse(data);
// Check if configuration has changed
if (JSON.stringify(this.config) !== JSON.stringify(newConfig)) {
console.log('Configuration updated', this.configPath);
this.config = newConfig;
// Emit configuration update event
this.emit('configChanged', this.config);
}
} catch (error) {
console.error('Error loading configuration:', error, this.configPath);
if (error.code === 'ENOENT') {
this.createEmptyConfig();
}
}
// 设置新的计时器,300ms 后执行
this.watchDebounceTimer = setTimeout(() => {
this.loadConfig();
}, 300);
}
});
}
}
// 获取配置的方法
getConfig() {
return this.config;
}
createEmptyConfig() {
try {
const dir = path.dirname(this.configPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const defaultConfig = {}; // Empty configuration object
fs.writeFileSync(this.configPath, JSON.stringify(defaultConfig, null, 2));
console.log('Created empty configuration file', this.configPath);
} catch (error) {
console.error('Error creating empty configuration file:', error, this.configPath);
}
}
// 获取特定配置项的方法
get(key) {
return this.config[key];
}
watchConfig() {
fs.watch(path.dirname(this.configPath), (eventType, filename) => {
if (filename === path.basename(this.configPath) && eventType === 'change') {
// Clear previous timer
if (this.watchDebounceTimer) {
clearTimeout(this.watchDebounceTimer);
}
// Set new timer, execute after 300ms
this.watchDebounceTimer = setTimeout(() => {
this.loadConfig();
}, 300);
}
});
}
// Method to get configuration
getConfig() {
return this.config;
}
// Method to get specific configuration item
get(key) {
return this.config[key];
}
}
module.exports = {
ConfigManager
};
};

View file

@ -1,103 +1,116 @@
require('dotenv').config();
const crypto = require('crypto');
require("dotenv").config();
const crypto = require("crypto");
function generatePasswordSignature(content, secretKey) {
// Create an HMAC object using SHA256 and the secretKey
const hmac = crypto.createHmac('sha256', secretKey);
// Update the HMAC object with the clientId
hmac.update(content);
// Generate the HMAC digest in binary format
const binarySignature = hmac.digest();
// Encode the binary signature to Base64
const base64Signature = binarySignature.toString('base64');
return base64Signature;
// Create an HMAC object using SHA256 and the secretKey
const hmac = crypto.createHmac("sha256", secretKey);
// Update the HMAC object with the clientId
hmac.update(content);
// Generate the HMAC digest in binary format
const binarySignature = hmac.digest();
// Encode the binary signature to Base64
const base64Signature = binarySignature.toString("base64");
return base64Signature;
}
function validateMqttCredentials(clientId, username, password) {
// 验证密码签名
const signatureKey = process.env.MQTT_SIGNATURE_KEY;
if (signatureKey) {
const expectedSignature = generatePasswordSignature(clientId + '|' + username, signatureKey);
if (password !== expectedSignature) {
throw new Error('密码签名验证失败');
}
} else {
console.warn('缺少MQTT_SIGNATURE_KEY环境变量,跳过密码签名验证');
// Validate password signature
const signatureKey = process.env.MQTT_SIGNATURE_KEY;
if (signatureKey) {
const expectedSignature = generatePasswordSignature(
clientId + "|" + username,
signatureKey
);
if (password !== expectedSignature) {
throw new Error("Password signature validation failed");
}
} else {
console.warn(
"Missing MQTT_SIGNATURE_KEY environment variable, skipping password signature validation"
);
}
// 验证clientId
if (!clientId || typeof clientId !== 'string') {
throw new Error('clientId必须是非空字符串');
}
// 验证clientId格式(必须包含@@@分隔符)
const clientIdParts = clientId.split('@@@');
// 新版本 MQTT 参数
if (clientIdParts.length !== 3) {
throw new Error('clientId格式错误,必须包含@@@分隔符');
}
// 验证username
if (!username || typeof username !== 'string') {
throw new Error('username必须是非空字符串');
}
// 尝试解码username(应该是base64编码的JSON)
let userData;
try {
const decodedUsername = Buffer.from(username, 'base64').toString();
userData = JSON.parse(decodedUsername);
} catch (error) {
throw new Error('username不是有效的base64编码JSON');
}
// 解析clientId中的信息
const [groupId, macAddress, uuid] = clientIdParts;
// 如果验证成功,返回解析后的有用信息
return {
groupId,
macAddress: macAddress.replace(/_/g, ':'),
uuid,
userData
};
// Validate clientId
if (!clientId || typeof clientId !== "string") {
throw new Error("clientId must be a non-empty string");
}
// Validate clientId format (must contain @@@ separator)
const clientIdParts = clientId.split("@@@");
// New version MQTT parameters
if (clientIdParts.length !== 3) {
throw new Error("clientId format error, must contain @@@ separator");
}
// Validate username
if (!username || typeof username !== "string") {
throw new Error("username must be a non-empty string");
}
// Try to decode username (should be base64 encoded JSON)
let userData;
try {
const decodedUsername = Buffer.from(username, "base64").toString();
userData = JSON.parse(decodedUsername);
} catch (error) {
throw new Error("username is not valid base64 encoded JSON");
}
// Parse information from clientId
const [groupId, macAddress, uuid] = clientIdParts;
// If validation succeeds, return parsed useful information
return {
groupId,
macAddress: macAddress.replace(/_/g, ":"),
uuid,
userData,
};
}
function generateMqttConfig(groupId, macAddress, uuid, userData) {
const endpoint = process.env.MQTT_ENDPOINT;
const signatureKey = process.env.MQTT_SIGNATURE_KEY;
if (!signatureKey) {
console.warn('No signature key, skip generating MQTT config');
return;
}
const deviceIdNoColon = macAddress.replace(/:/g, '_');
const clientId = `${groupId}@@@${deviceIdNoColon}@@@${uuid}`;
const username = Buffer.from(JSON.stringify(userData)).toString('base64');
const password = generatePasswordSignature(clientId + '|' + username, signatureKey);
return {
endpoint,
port: 8883,
client_id: clientId,
username,
password,
publish_topic: 'device-server',
subscribe_topic: 'null' // 旧版本固件不返回此字段会出错
}
const endpoint = process.env.MQTT_ENDPOINT;
const signatureKey = process.env.MQTT_SIGNATURE_KEY;
if (!signatureKey) {
console.warn("No signature key, skip generating MQTT config");
return;
}
const deviceIdNoColon = macAddress.replace(/:/g, "_");
const clientId = `${groupId}@@@${deviceIdNoColon}@@@${uuid}`;
const username = Buffer.from(JSON.stringify(userData)).toString("base64");
const password = generatePasswordSignature(
clientId + "|" + username,
signatureKey
);
return {
endpoint,
port: 8883,
client_id: clientId,
username,
password,
publish_topic: "device-server",
subscribe_topic: "null", // Old version firmware will error if this field is not returned
};
}
module.exports = {
generateMqttConfig,
validateMqttCredentials
}
generateMqttConfig,
validateMqttCredentials,
};
if (require.main === module) {
const config = generateMqttConfig('GID_test', '11:22:33:44:55:66', '36c98363-3656-43cb-a00f-8bced2391a90', { ip: '222.222.222.222' });
console.log('config', config);
const credentials = validateMqttCredentials(config.client_id, config.username, config.password);
console.log('credentials', credentials);
const config = generateMqttConfig(
"GID_test",
"11:22:33:44:55:66",
"36c98363-3656-43cb-a00f-8bced2391a90",
{ ip: "222.222.222.222" }
);
console.log("config", config);
const credentials = validateMqttCredentials(
config.client_id,
config.username,
config.password
);
console.log("credentials", credentials);
}

View file

@ -1,239 +1,258 @@
# MQTT网关转发功能测试指南
# MQTT Gateway Forwarding Function Test Guide
本文档说明如何测试MQTT网关的转发功能是否配置成功。
This document explains how to test whether the MQTT gateway forwarding function is configured successfully.
## 快速测试
## Quick Test
### 1. 基础连接测试
### 1. Basic Connection Test
运行快速测试脚本:
Run the quick test script:
```bash
node quick-test.js
```
这个脚本会:
- ✅ 检查配置文件
- ✅ 测试MQTT服务器连接(端口1883)
- ✅ 测试WebSocket后端服务连接
- ✅ 显示测试结果和建议
This script will:
### 2. 完整功能测试
- ✅ Check configuration file
- ✅ Test MQTT server connection (port 1883)
- ✅ Test WebSocket backend service connection
- ✅ Display test results and recommendations
运行完整测试脚本:
### 2. Complete Function Test
Run the complete test script:
```bash
node test-mqtt.js
```
这个脚本会:
- 🔗 连接到MQTT服务器
- 🔐 使用配置的MAC地址进行认证
- 📝 订阅回复主题
- 📤 发送hello消息测试WebSocket转发
- 📥 等待并显示服务器响应
- 🧪 发送其他测试消息
This script will:
## 手动测试步骤
- 🔗 Connect to MQTT server
- 🔐 Authenticate using configured MAC address
- 📝 Subscribe to reply topic
- 📤 Send hello message to test WebSocket forwarding
- 📥 Wait for and display server response
- 🧪 Send other test messages
### 1. 启动MQTT网关
## Manual Test Steps
### 1. Start MQTT Gateway
```bash
node app.js
```
应该看到类似输出:
You should see similar output:
```
MQTT 服务器启动在端口 1883
UDP 服务器启动在端口 1883
连接数: 0, 活跃数: 0
MQTT server started on port 1883
UDP server started on port 1883
Connections: 0, Active: 0
```
### 2. 检查配置文件
### 2. Check Configuration File
确认 `config/mqtt.json` 配置正确:
Confirm that `config/mqtt.json` is configured correctly:
```json
{
"production": {
"chat_servers": [
"ws://192.168.68.66:8000/xiaozhi/v1/"
]
},
"development": {
"chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"],
"mac_addresss": ["d8:43:ae:3e:4b:5a"]
},
"debug": false
"production": {
"chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"]
},
"development": {
"chat_servers": ["ws://192.168.68.66:8000/xiaozhi/v1/"],
"mac_addresss": ["d8:43:ae:3e:4b:5a"]
},
"debug": false
}
```
### 3. 使用MQTT客户端工具测试
### 3. Test Using MQTT Client Tools
#### 使用mosquitto客户端:
#### Using mosquitto client:
**Connection test:**
**连接测试:**
```bash
mosquitto_pub -h localhost -p 1883 -t "test/topic" -m "hello"
```
**订阅测试:**
**Subscription test:**
```bash
mosquitto_sub -h localhost -p 1883 -t "devices/p2p/d8_43_ae_3e_4b_5a"
```
#### 使用MQTT.fx或其他GUI工具:
#### Using MQTT.fx or other GUI tools:
1. **连接设置:**
- 服务器:localhost
- 端口:1883
- 客户端ID:`GID_test@@@d8_43_ae_3e_4b_5a`
- 用户名:test_user
- 密码:test_password
1. **Connection settings:**
- Server: localhost
- Port: 1883
- Client ID: `GID_test@@@d8_43_ae_3e_4b_5a`
- Username: test_user
- Password: test_password
2. **Publish test message:**
- Topic: `test/topic`
- Message:
2. **发布测试消息:**
- 主题:`test/topic`
- 消息:
```json
{
"type": "hello",
"version": 3,
"transport": "mqtt",
"audio_params": {
"sample_rate": 16000,
"channels": 1,
"format": "opus"
},
"features": ["tts", "asr"]
"type": "hello",
"version": 3,
"transport": "mqtt",
"audio_params": {
"sample_rate": 16000,
"channels": 1,
"format": "opus"
},
"features": ["tts", "asr"]
}
```
3. **订阅回复主题:**
- 主题:`devices/p2p/d8_43_ae_3e_4b_5a`
3. **Subscribe to reply topic:**
- Topic: `devices/p2p/d8_43_ae_3e_4b_5a`
## 测试结果判断
## Test Result Assessment
### ✅ 成功指标
### ✅ Success Indicators
1. **MQTT connection successful:**
1. **MQTT连接成功:**
```
✓ 成功连接到MQTT服务器 localhost:1883
✓ MQTT连接成功
✓ Successfully connected to MQTT server localhost:1883
✓ MQTT connection successful
```
2. **WebSocket转发成功:**
2. **WebSocket forwarding successful:**
```
✓ WebSocket服务器连接成功
✓ 收到PUBLISH消息
✓ WebSocket server connection successful
✓ Received PUBLISH message
```
3. **服务器日志正常:**
3. **Server logs normal:**
```
客户端连接: { clientId: 'GID_test@@@d8_43_ae_3e_4b_5a', ... }
收到发布消息: { topic: 'test/topic', payload: '...', qos: 0 }
Client connected: { clientId: 'GID_test@@@d8_43_ae_3e_4b_5a', ... }
Received publish message: { topic: 'test/topic', payload: '...', qos: 0 }
```
### ❌ 常见问题
### ❌ Common Issues
1. **MQTT服务器连接失败:**
```
✗ 连接错误: connect ECONNREFUSED 127.0.0.1:1883
```
**解决方案:** 确保运行 `node app.js` 启动MQTT网关
1. **MQTT server connection failed:**
2. **WebSocket连接失败:**
```
✗ WebSocket服务器连接失败: connect ECONNREFUSED
✗ Connection error: connect ECONNREFUSED 127.0.0.1:1883
```
**解决方案:** 检查WebSocket后端服务是否运行,网络是否可达
3. **认证失败:**
```
无效的 clientId: xxx
```
**解决方案:** 检查客户端ID格式是否为 `GID_test@@@mac_address`
**Solution:** Ensure running `node app.js` to start MQTT gateway
2. **WebSocket connection failed:**
4. **MAC地址不匹配:**
```
未找到 xx:xx:xx:xx:xx:xx 的聊天服务器
✗ WebSocket server connection failed: connect ECONNREFUSED
```
**解决方案:** 确认MAC地址在配置文件的 `mac_addresss` 列表中
## 调试技巧
**Solution:** Check if WebSocket backend service is running and network is reachable
### 1. 开启调试模式
3. **Authentication failed:**
```
Invalid clientId: xxx
```
**Solution:** Check if client ID format is `GID_test@@@mac_address`
4. **MAC address mismatch:**
```
Chat server not found for xx:xx:xx:xx:xx:xx
```
**Solution:** Confirm MAC address is in the `mac_addresss` list in configuration file
## Debugging Tips
### 1. Enable Debug Mode
Modify `config/mqtt.json`:
修改 `config/mqtt.json`:
```json
{
"debug": true
"debug": true
}
```
或设置环境变量:
Or set environment variable:
```bash
DEBUG=mqtt-server node app.js
```
### 2. 查看详细日志
### 2. View Detailed Logs
Debug mode will display detailed connection and message processing information:
调试模式下会显示详细的连接和消息处理信息:
```
mqtt-server 客户端连接: { clientId: '...', username: '...', ... }
mqtt-server 收到发布消息: { topic: '...', payload: '...', qos: 0 }
mqtt-server 发送消息到 devices/p2p/...: {...}
mqtt-server Client connected: { clientId: '...', username: '...', ... }
mqtt-server Received publish message: { topic: '...', payload: '...', qos: 0 }
mqtt-server Sending message to devices/p2p/...: {...}
```
### 3. 网络连通性测试
### 3. Network Connectivity Test
**Test WebSocket server:**
**测试WebSocket服务器:**
```bash
curl -I http://192.168.68.66:8000/xiaozhi/v1/
```
**测试MQTT端口:**
**Test MQTT port:**
```bash
telnet localhost 1883
```
## 性能测试
## Performance Testing
### 并发连接测试
### Concurrent Connection Test
可以修改测试脚本创建多个并发连接:
You can modify the test script to create multiple concurrent connections:
```javascript
// 创建多个测试客户端
// Create multiple test clients
const clients = [];
for (let i = 0; i < 10; i++) {
const client = new MQTTTestClient();
clients.push(client);
// 连接和测试...
const client = new MQTTTestClient();
clients.push(client);
// Connect and test...
}
```
### 消息吞吐量测试
### Message Throughput Test
发送大量消息测试转发性能:
Send large number of messages to test forwarding performance:
```javascript
// 发送100条消息
// Send 100 messages
for (let i = 0; i < 100; i++) {
client.publish('test/topic', `测试消息 ${i}`);
client.publish("test/topic", `Test message ${i}`);
}
```
## 故障排除清单
## Troubleshooting Checklist
- [ ] MQTT网关服务是否运行 (`node app.js`)
- [ ] 端口1883是否被占用
- [ ] 配置文件格式是否正确
- [ ] WebSocket后端服务是否运行
- [ ] 网络连接是否正常
- [ ] MAC地址是否在配置的白名单中
- [ ] 客户端ID格式是否正确
- [ ] 防火墙是否阻止连接
- [ ] Is MQTT gateway service running (`node app.js`)
- [ ] Is port 1883 occupied
- [ ] Is configuration file format correct
- [ ] Is WebSocket backend service running
- [ ] Is network connection normal
- [ ] Is MAC address in configured whitelist
- [ ] Is client ID format correct
- [ ] Is firewall blocking connections
## 总结
## Summary
通过以上测试方法,你可以全面验证MQTT网关的转发功能是否配置成功。建议先运行快速测试,如果有问题再进行详细的手动测试和调试。
Through the above testing methods, you can comprehensively verify whether the MQTT gateway forwarding function is configured successfully. It is recommended to run the quick test first, and if there are issues, proceed with detailed manual testing and debugging.

View file

@ -13,12 +13,11 @@ from core.utils.util import check_ffmpeg_installed
TAG = __name__
logger = setup_logging()
async def wait_for_exit() -> None:
"""
阻塞直到收到 Ctrl‑C / SIGTERM。
- Unix: 使用 add_signal_handler
- Windows: 依赖 KeyboardInterrupt
Block until receiving Ctrl-C / SIGTERM.
- Unix: Use add_signal_handler
- Windows: Rely on KeyboardInterrupt
"""
loop = asyncio.get_running_loop()
stop_event = asyncio.Event()
@ -28,114 +27,116 @@ async def wait_for_exit() -> None:
loop.add_signal_handler(sig, stop_event.set)
await stop_event.wait()
else:
# Windows:await一个永远pending的fut,
# 让 KeyboardInterrupt 冒泡到 asyncio.run,以此消除遗留普通线程导致进程退出阻塞的问题
# Windows: await a forever pending future,
# let KeyboardInterrupt bubble up to asyncio.run, to eliminate process exit blocking caused by legacy normal threads
try:
await asyncio.Future()
except KeyboardInterrupt: # Ctrl‑C
except KeyboardInterrupt: # Ctrl-C
pass
async def monitor_stdin():
"""监控标准输入,消费回车键"""
"""Monitor standard input, consume enter key presses"""
while True:
await ainput() # 异步等待输入,消费回车
await ainput() # Asynchronously wait for input, consume enter
async def main():
check_ffmpeg_installed()
config = load_config()
# 默认使用manager-api的secret作为auth_key
# 如果secret为空,则生成随机密钥
# auth_key用于jwt认证,比如视觉分析接口的jwt认证
# Default to using manager-api's secret as auth_key
# If secret is empty, generate random key
# auth_key is used for jwt authentication, such as jwt authentication for vision analysis interface
auth_key = config.get("manager-api", {}).get("secret", "")
if not auth_key or len(auth_key) == 0 or "你" in auth_key:
auth_key = str(uuid.uuid4().hex)
config["server"]["auth_key"] = auth_key
logger.bind(tag=TAG).info(f"Generated auth_key: {auth_key}")
config["server"]["auth_key"] = auth_key
logger.bind(tag=TAG).info(f"Generated auth_key: {auth_key}")
# 添加 stdin 监控任务
# Add stdin monitoring task
stdin_task = asyncio.create_task(monitor_stdin())
# 启动 WebSocket 服务器
# Start WebSocket server
ws_server = WebSocketServer(config)
ws_task = asyncio.create_task(ws_server.start())
# 启动 Simple http 服务器
# Start Simple http server
ota_server = SimpleHttpServer(config)
ota_task = asyncio.create_task(ota_server.start())
read_config_from_api = config.get("read_config_from_api", False)
port = int(config["server"].get("http_port", 8003))
if not read_config_from_api:
logger.bind(tag=TAG).info(
"OTA接口是\t\thttp://{}:{}/xiaozhi/ota/",
"OTA interface is\t\thttp://{}:{}/xiaozhi/ota/",
get_local_ip(),
port,
)
mcp_endpoint = config.get("mcp_endpoint", None)
if mcp_endpoint is not None and "你" not in mcp_endpoint:
# 校验MCP接入点格式
if validate_mcp_endpoint(mcp_endpoint):
logger.bind(tag=TAG).info("mcp接入点是\t{}", mcp_endpoint)
# 将mcp计入点地址转成调用点
mcp_endpoint = mcp_endpoint.replace("/mcp/", "/call/")
config["mcp_endpoint"] = mcp_endpoint
else:
logger.bind(tag=TAG).error("mcp接入点不符合规范")
config["mcp_endpoint"] = "你的接入点 websocket地址"
mcp_endpoint = config.get("mcp_endpoint", None)
if mcp_endpoint is not None and "你" not in mcp_endpoint:
# Validate MCP endpoint format
if validate_mcp_endpoint(mcp_endpoint):
logger.bind(tag=TAG).info("MCP endpoint is\t{}", mcp_endpoint)
# Convert mcp endpoint address to call endpoint
mcp_endpoint = mcp_endpoint.replace("/mcp/", "/call/")
config["mcp_endpoint"] = mcp_endpoint
else:
logger.bind(tag=TAG).error("MCP endpoint does not conform to specifications")
config["mcp_endpoint"] = "Your endpoint websocket address"
logger.bind(tag=TAG).info(
"视觉分析接口是\thttp://{}:{}/mcp/vision/explain",
"Vision analysis interface is\thttp://{}:{}/mcp/vision/explain",
get_local_ip(),
port,
)
# 获取WebSocket配置,使用安全的默认值
# Get WebSocket configuration, use safe default values
websocket_port = 8000
server_config = config.get("server", {})
if isinstance(server_config, dict):
websocket_port = int(server_config.get("port", 8000))
logger.bind(tag=TAG).info(
"Websocket地址是\tws://{}:{}/xiaozhi/v1/",
"Websocket address is\tws://{}:{}/xiaozhi/v1/",
get_local_ip(),
websocket_port,
)
logger.bind(tag=TAG).info(
"=======上面的地址是websocket协议地址,请勿用浏览器访问======="
"=======The above address is websocket protocol address, please do not access with browser======="
)
logger.bind(tag=TAG).info(
"如想测试websocket请用谷歌浏览器打开test目录下的test_page.html"
"If you want to test websocket please use Google Chrome to open test_page.html in test directory"
)
logger.bind(tag=TAG).info(
"=============================================================\n"
)
try:
await wait_for_exit() # 阻塞直到收到退出信号
await wait_for_exit() # Block until receiving exit signal
except asyncio.CancelledError:
print("任务被取消,清理资源中...")
print("Task was cancelled, cleaning up resources...")
finally:
# 取消所有任务(关键修复点)
# Cancel all tasks (critical fix point)
stdin_task.cancel()
ws_task.cancel()
if ota_task:
ota_task.cancel()
# 等待任务终止(必须加超时)
# Wait for task termination (must add timeout)
await asyncio.wait(
[stdin_task, ws_task, ota_task] if ota_task else [stdin_task, ws_task],
timeout=3.0,
return_when=asyncio.ALL_COMPLETED,
)
print("服务器已关闭,程序退出。")
print("Server has been closed, program exiting.")
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("手动中断,程序终止。")
print("Manual interruption, program terminated.")

View file

@ -19,9 +19,9 @@ import opuslib
# --- Configuration ---
SERVER_IP = "192.168.1.101" # !!! UPDATE with your server's local IP address !!!
SERVER_IP = "192.168.1.254" # !!! UPDATE with your server's local IP address !!!
OTA_PORT = 8003
MQTT_BROKER_HOST = "192.168.1.101" # MQTT gateway IP
MQTT_BROKER_HOST = "192.168.1.254" # MQTT gateway IP
MQTT_BROKER_PORT = 1883
# DEVICE_MAC is now dynamically generated for uniqueness
PLAYBACK_BUFFER_MIN_FRAMES = 3 # Minimum frames to have in buffer to continue playback

View file

@ -3,63 +3,62 @@ import yaml
from collections.abc import Mapping
from config.manage_api_client import init_service, get_server_config, get_agent_models
def get_project_dir():
"""获取项目根目录"""
"""Get project root directory"""
return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/"
def read_config(config_path):
with open(config_path, "r", encoding="utf-8") as file:
config = yaml.safe_load(file)
return config
def load_config():
"""加载配置文件"""
"""Load configuration file"""
from core.utils.cache.manager import cache_manager, CacheType
# 检查缓存
# Check cache
cached_config = cache_manager.get(CacheType.CONFIG, "main_config")
if cached_config is not None:
return cached_config
default_config_path = get_project_dir() + "config.yaml"
custom_config_path = get_project_dir() + "data/.config.yaml"
# 加载默认配置
# Load default configuration
default_config = read_config(default_config_path)
custom_config = read_config(custom_config_path)
if custom_config.get("manager-api", {}).get("url"):
config = get_config_from_api(custom_config)
else:
# 合并配置
# Merge configurations
config = merge_configs(default_config, custom_config)
# 初始化目录
# Initialize directories
ensure_directories(config)
# 缓存配置
# Cache configuration
cache_manager.set(CacheType.CONFIG, "main_config", config)
return config
def get_config_from_api(config):
"""从Java API获取配置"""
# 初始化API客户端
"""Get configuration from Java API"""
# Initialize API client
init_service(config)
# 获取服务器配置
# Get server configuration
config_data = get_server_config()
if config_data is None:
raise Exception("Failed to fetch server config from API")
config_data["read_config_from_api"] = True
config_data["manager-api"] = {
"url": config["manager-api"].get("url", ""),
"secret": config["manager-api"].get("secret", ""),
}
# server的配置以本地为准
# Use local server configuration as priority
if config.get("server"):
config_data["server"] = {
"ip": config["server"].get("ip", ""),
@ -68,23 +67,23 @@ def get_config_from_api(config):
"vision_explain": config["server"].get("vision_explain", ""),
"auth_key": config["server"].get("auth_key", ""),
}
return config_data
def get_private_config_from_api(config, device_id, client_id):
"""从Java API获取私有配置"""
"""Get private configuration from Java API"""
return get_agent_models(device_id, client_id, config["selected_module"])
def ensure_directories(config):
"""确保所有配置路径存在"""
"""Ensure all configuration paths exist"""
dirs_to_create = set()
project_dir = get_project_dir() # 获取项目根目录
# 日志文件目录
project_dir = get_project_dir() # Get project root directory
# Log file directory
log_dir = config.get("log", {}).get("log_dir", "tmp")
dirs_to_create.add(os.path.join(project_dir, log_dir))
# ASR/TTS模块输出目录
# ASR/TTS module output directories
for module in ["ASR", "TTS"]:
if config.get(module) is None:
continue
@ -92,49 +91,48 @@ def ensure_directories(config):
output_dir = provider.get("output_dir", "")
if output_dir:
dirs_to_create.add(output_dir)
# 根据selected_module创建模型目录
# Create model directories based on selected_module
selected_modules = config.get("selected_module", {})
for module_type in ["ASR", "LLM", "TTS"]:
selected_provider = selected_modules.get(module_type)
if not selected_provider:
continue
if config.get(module) is None:
if config.get(module_type) is None:
continue
if config.get(selected_provider) is None:
continue
provider_config = config.get(module_type, {}).get(selected_provider, {})
output_dir = provider_config.get("output_dir")
if output_dir:
full_model_dir = os.path.join(project_dir, output_dir)
dirs_to_create.add(full_model_dir)
# 统一创建目录(保留原data目录创建)
# Create directories uniformly (keep original data directory creation)
for dir_path in dirs_to_create:
try:
os.makedirs(dir_path, exist_ok=True)
except PermissionError:
print(f"警告:无法创建目录 {dir_path},请检查写入权限")
print(f"Warning: Cannot create directory {dir_path}, please check write permissions")
def merge_configs(default_config, custom_config):
"""
递归合并配置,custom_config优先级更高
Recursively merge configurations, custom_config has higher priority
Args:
default_config: 默认配置
custom_config: 用户自定义配置
default_config: Default configuration
custom_config: User custom configuration
Returns:
合并后的配置
Merged configuration
"""
if not isinstance(default_config, Mapping) or not isinstance(
custom_config, Mapping
):
return custom_config
merged = dict(default_config)
for key, value in custom_config.items():
if (
key in merged
@ -144,5 +142,5 @@ def merge_configs(default_config, custom_config):
merged[key] = merge_configs(merged[key], value)
else:
merged[key] = value
return merged
return merged

View file

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

View file

@ -15,7 +15,8 @@ class DeviceNotFoundException(Exception):
class DeviceBindException(Exception):
def __init__(self, bind_code):
self.bind_code = bind_code
super().__init__(f"设备绑定异常,绑定码: {bind_code}")
super().__init__(
f"Device binding exception, binding code: {bind_code}")
class ManageApiClient:
@ -24,7 +25,7 @@ class ManageApiClient:
_secret = None
def __new__(cls, config):
"""单例模式确保全局唯一实例,并支持传入配置参数"""
"""Singleton pattern to ensure a globally unique instance, supporting configuration parameters"""
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._init_client(config)
@ -32,23 +33,25 @@ class ManageApiClient:
@classmethod
def _init_client(cls, config):
"""初始化持久化连接池"""
"""Initialize persistent connection pool"""
cls.config = config.get("manager-api")
if not cls.config:
raise Exception("manager-api配置错误")
raise Exception("manager-api configuration error")
if not cls.config.get("url") or not cls.config.get("secret"):
raise Exception("manager-api的url或secret配置错误")
raise Exception("manager-api url or secret configuration error")
if "你" in cls.config.get("secret"):
raise Exception("请先配置manager-api的secret")
raise Exception("Please configure the manager-api secret first")
cls._secret = cls.config.get("secret")
cls.max_retries = cls.config.get("max_retries", 6) # 最大重试次数
cls.retry_delay = cls.config.get("retry_delay", 10) # 初始重试延迟(秒)
# NOTE(goody): 2025/4/16 http相关资源统一管理,后续可以增加线程池或者超时
# 后续也可以统一配置apiToken之类的走通用的Auth
cls.max_retries = cls.config.get(
"max_retries", 6) # Maximum retry count
# Initial retry delay (seconds)
cls.retry_delay = cls.config.get("retry_delay", 10)
# NOTE(goody): 2025/4/16 Unified management of http-related resources, can add thread pools or timeouts later
# Later can also unify configuration of apiToken and other common Auth
cls._client = httpx.Client(
base_url=cls.config.get("url"),
headers={
@ -56,39 +59,42 @@ class ManageApiClient:
"Accept": "application/json",
"Authorization": "Bearer " + cls._secret,
},
timeout=cls.config.get("timeout", 30), # 默认超时时间30秒
# Default timeout 30 seconds
timeout=cls.config.get("timeout", 30),
)
@classmethod
def _request(cls, method: str, endpoint: str, **kwargs) -> Dict:
"""发送单次HTTP请求并处理响应"""
"""Send a single HTTP request and handle response"""
endpoint = endpoint.lstrip("/")
response = cls._client.request(method, endpoint, **kwargs)
response.raise_for_status()
result = response.json()
# 处理API返回的业务错误
# Handle business errors returned by API
if result.get("code") == 10041:
raise DeviceNotFoundException(result.get("msg"))
elif result.get("code") == 10042:
raise DeviceBindException(result.get("msg"))
elif result.get("code") != 0:
raise Exception(f"API返回错误: {result.get('msg', '未知错误')}")
raise Exception(
f"API returned error: {result.get('msg', 'Unknown error')}")
# 返回成功数据
# Return successful data
return result.get("data") if result.get("code") == 0 else None
@classmethod
def _should_retry(cls, exception: Exception) -> bool:
"""判断异常是否应该重试"""
# 网络连接相关错误
"""Determine if exception should be retried"""
# Network connection related errors
if isinstance(
exception, (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError)
exception, (httpx.ConnectError,
httpx.TimeoutException, httpx.NetworkError)
):
return True
# HTTP状态码错误
# HTTP status code errors
if isinstance(exception, httpx.HTTPStatusError):
status_code = exception.response.status_code
return status_code in [408, 429, 500, 502, 503, 504]
@ -97,43 +103,43 @@ class ManageApiClient:
@classmethod
def _execute_request(cls, method: str, endpoint: str, **kwargs) -> Dict:
"""带重试机制的请求执行器"""
"""Request executor with retry mechanism"""
retry_count = 0
while retry_count <= cls.max_retries:
try:
# 执行请求
# Execute request
return cls._request(method, endpoint, **kwargs)
except Exception as e:
# 判断是否应该重试
# Determine if should retry
if retry_count < cls.max_retries and cls._should_retry(e):
retry_count += 1
print(
f"{method} {endpoint} 请求失败,将在 {cls.retry_delay:.1f} 秒后进行第 {retry_count} 次重试"
f"{method} {endpoint} request failed, will retry attempt {retry_count} after {cls.retry_delay:.1f} seconds"
)
time.sleep(cls.retry_delay)
continue
else:
# 不重试,直接抛出异常
# Don't retry, throw exception directly
raise
@classmethod
def safe_close(cls):
"""安全关闭连接池"""
"""Safely close connection pool"""
if cls._client:
cls._client.close()
cls._instance = None
def get_server_config() -> Optional[Dict]:
"""获取服务器基础配置"""
"""Get server basic configuration"""
return ManageApiClient._instance._execute_request("POST", "/config/server-base")
def get_agent_models(
mac_address: str, client_id: str, selected_module: Dict
) -> Optional[Dict]:
"""获取代理模型配置"""
"""Get agent model configuration"""
return ManageApiClient._instance._execute_request(
"POST",
"/config/agent-models",
@ -155,14 +161,14 @@ def save_mem_local_short(mac_address: str, short_momery: str) -> Optional[Dict]:
},
)
except Exception as e:
print(f"存储短期记忆到服务器失败: {e}")
print(f"Failed to save short-term memory to server: {e}")
return None
def report(
mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time
) -> Optional[Dict]:
"""带熔断的业务方法示例"""
"""Business method example with circuit breaker"""
if not content or not ManageApiClient._instance:
return None
try:
@ -181,7 +187,7 @@ def report(
},
)
except Exception as e:
print(f"TTS上报失败: {e}")
print(f"TTS reporting failed: {e}")
return None

View file

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

View file

@ -8,7 +8,7 @@ class BaseHandler:
self.logger = setup_logging()
def _add_cors_headers(self, response):
"""添加CORS头信息"""
"""Add CORS header information"""
response.headers["Access-Control-Allow-Headers"] = (
"client-id, content-type, device-id"
)

View file

@ -1,130 +1,3 @@
# import json
# import time
# from aiohttp import web
# from core.utils.util import get_local_ip
# from core.api.base_handler import BaseHandler
# TAG = __name__
# class OTAHandler(BaseHandler):
# def __init__(self, config: dict):
# super().__init__(config)
# def _get_websocket_url(self, local_ip: str, port: int) -> str:
# """获取websocket地址
# Args:
# local_ip: 本地IP地址
# port: 端口号
# Returns:
# str: websocket地址
# """
# server_config = self.config["server"]
# websocket_config = server_config.get("websocket", "")
# if "你的" not in websocket_config:
# return websocket_config
# else:
# return f"ws://{local_ip}:{port}/xiaozhi/v1/"
# async def handle_post(self, request):
# """处理 OTA POST 请求"""
# try:
# data = await request.text()
# self.logger.bind(tag=TAG).debug(f"OTA请求方法: {request.method}")
# self.logger.bind(tag=TAG).debug(f"OTA请求头: {request.headers}")
# self.logger.bind(tag=TAG).debug(f"OTA请求数据: {data}")
# device_id = request.headers.get("device-id", "")
# if device_id:
# self.logger.bind(tag=TAG).info(f"OTA请求设备ID: {device_id}")
# else:
# raise Exception("OTA请求设备ID为空")
# data_json = json.loads(data)
# server_config = self.config["server"]
# port = int(server_config.get("port", 8000))
# local_ip = get_local_ip()
# return_json = {
# "server_time": {
# "timestamp": int(round(time.time() * 1000)),
# "timezone_offset": server_config.get("timezone_offset", 8) * 60,
# },
# "firmware": {
# "version": data_json["application"].get("version", "1.0.0"),
# "url": "",
# },
# "websocket": {
# "url": self._get_websocket_url(local_ip, port),
# },
# }
# # Add MQTT gateway configuration if enabled
# mqtt_config = server_config.get("mqtt_gateway", {})
# if mqtt_config.get("enabled", False):
# return_json["mqtt_gateway"] = {
# "broker": mqtt_config.get("broker", local_ip),
# "port": mqtt_config.get("port", 1883),
# "udp_port": mqtt_config.get("udp_port", 8884)
# }
# # Also add MQTT credentials section for client authentication
# import base64
# import hmac
# import hashlib
# client_id = f"GID_test@@@{device_id}@@@{data_json.get('client_id', 'default-client')}"
# # Create username (base64 encoded JSON) - must match client format
# username_data = {"ip": "192.168.1.100"} # Placeholder IP
# username = base64.b64encode(json.dumps(username_data).encode()).decode()
# # Generate password using HMAC (must match gateway's signature key)
# secret_key = "test-signature-key-12345" # Must match MQTT_SIGNATURE_KEY in gateway's .env
# content = f"{client_id}|{username}"
# password = base64.b64encode(hmac.new(secret_key.encode(), content.encode(), hashlib.sha256).digest()).decode()
# return_json["mqtt"] = {
# "client_id": client_id,
# "username": username,
# "password": password
# }
# response = web.Response(
# text=json.dumps(return_json, separators=(",", ":")),
# content_type="application/json",
# )
# except Exception as e:
# return_json = {"success": False, "message": "request error."}
# response = web.Response(
# text=json.dumps(return_json, separators=(",", ":")),
# content_type="application/json",
# )
# finally:
# self._add_cors_headers(response)
# return response
# async def handle_get(self, request):
# """处理 OTA GET 请求"""
# try:
# server_config = self.config["server"]
# local_ip = get_local_ip()
# port = int(server_config.get("port", 8000))
# websocket_url = self._get_websocket_url(local_ip, port)
# message = f"OTA接口运行正常,向设备发送的websocket地址是:{websocket_url}"
# response = web.Response(text=message, content_type="text/plain")
# except Exception as e:
# self.logger.bind(tag=TAG).error(f"OTA GET请求异常: {e}")
# response = web.Response(text="OTA接口异常", content_type="text/plain")
# finally:
# self._add_cors_headers(response)
# return response
import json
import time
import uuid
@ -150,17 +23,18 @@ class OTAHandler(BaseHandler):
def __init__(self, config: dict):
super().__init__(config)
# Load MQTT signature key from environment or config
self.mqtt_signature_key = os.getenv('MQTT_SIGNATURE_KEY', 'test-signature-key-12345')
self.mqtt_signature_key = os.getenv(
'MQTT_SIGNATURE_KEY', 'test-signature-key-12345')
def _get_websocket_url(self, local_ip: str, port: int) -> str:
"""获取websocket地址
"""Get websocket address
Args:
local_ip: 本地IP地址
port: 端口号
local_ip: Local IP address
port: Port number
Returns:
str: websocket地址
str: websocket address
"""
server_config = self.config["server"]
websocket_config = server_config.get("websocket", "")
@ -171,35 +45,36 @@ class OTAHandler(BaseHandler):
return f"ws://{local_ip}:{port}/xiaozhi/v1/"
def _generate_mqtt_credentials(self, device_id: str, client_ip: str) -> dict:
"""生成MQTT凭据
"""Generate MQTT credentials
Args:
device_id: 设备ID (MAC地址格式)
client_ip: 客户端IP地址
device_id: Device ID (MAC address format)
client_ip: Client IP address
Returns:
dict: MQTT凭据信息
dict: MQTT credential information
"""
# Convert MAC address format (remove colons, use underscores)
mac_address = device_id.replace(":", "_")
# Generate UUID for this session
client_uuid = str(uuid.uuid4())
# Create client ID in format: GID_test@@@mac_address@@@uuid
group_id = "GID_test"
client_id = f"{group_id}@@@{mac_address}@@@{client_uuid}"
# Create user data and encode as base64 JSON
user_data = {"ip": client_ip}
username = base64.b64encode(json.dumps(user_data).encode()).decode()
# Generate password signature
content = f"{client_id}|{username}"
password = base64.b64encode(
hmac.new(self.mqtt_signature_key.encode(), content.encode(), hashlib.sha256).digest()
hmac.new(self.mqtt_signature_key.encode(),
content.encode(), hashlib.sha256).digest()
).decode()
return {
"client_id": client_id,
"username": username,
@ -207,25 +82,29 @@ class OTAHandler(BaseHandler):
}
async def handle_post(self, request):
"""处理 OTA POST 请求"""
"""Handle OTA POST request"""
try:
data = await request.text()
self.logger.bind(tag=TAG).debug(f"OTA请求方法: {request.method}")
self.logger.bind(tag=TAG).debug(f"OTA请求头: {request.headers}")
self.logger.bind(tag=TAG).debug(f"OTA请求数据: {data}")
self.logger.bind(tag=TAG).debug(
f"OTA request method: {request.method}")
self.logger.bind(tag=TAG).debug(
f"OTA request headers: {request.headers}")
self.logger.bind(tag=TAG).debug(f"OTA request data: {data}")
device_id = request.headers.get("device-id", "")
if device_id:
self.logger.bind(tag=TAG).info(f"OTA请求设备ID: {device_id}")
self.logger.bind(tag=TAG).info(
f"OTA request device ID: {device_id}")
else:
raise Exception("OTA请求设备ID为空")
raise Exception("OTA request device ID is empty")
data_json = json.loads(data)
# Get client IP address
client_ip = request.remote
if request.headers.get('X-Forwarded-For'):
client_ip = request.headers.get('X-Forwarded-For').split(',')[0].strip()
client_ip = request.headers.get(
'X-Forwarded-For').split(',')[0].strip()
elif request.headers.get('X-Real-IP'):
client_ip = request.headers.get('X-Real-IP')
@ -239,12 +118,13 @@ class OTAHandler(BaseHandler):
mqtt_broker = mqtt_config.get("broker", local_ip)
mqtt_port = mqtt_config.get("port", 1883)
udp_port = mqtt_config.get("udp_port", 8884)
# Generate MQTT credentials if MQTT is enabled
mqtt_credentials = None
if mqtt_enabled:
mqtt_credentials = self._generate_mqtt_credentials(device_id, client_ip)
mqtt_credentials = self._generate_mqtt_credentials(
device_id, client_ip)
return_json = {
"server_time": {
"timestamp": int(round(time.time() * 1000)),
@ -258,7 +138,7 @@ class OTAHandler(BaseHandler):
"url": self._get_websocket_url(local_ip, port),
},
}
# Add MQTT credentials in the new format if enabled
if mqtt_enabled and mqtt_credentials:
return_json["mqtt"] = {
@ -290,13 +170,13 @@ class OTAHandler(BaseHandler):
"frame_duration": 60
}
})
response = web.Response(
text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json",
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"OTA POST请求异常: {e}")
self.logger.bind(tag=TAG).error(f"OTA POST request exception: {e}")
return_json = {"success": False, "message": "request error."}
response = web.Response(
text=json.dumps(return_json, separators=(",", ":")),
@ -307,35 +187,37 @@ class OTAHandler(BaseHandler):
return response
async def handle_get(self, request):
"""处理 OTA GET 请求"""
"""Handle OTA GET request"""
try:
server_config = self.config["server"]
local_ip = get_local_ip()
port = int(server_config.get("port", 8000))
http_port = server_config.get("http_port", 8003)
websocket_url = self._get_websocket_url(local_ip, port)
# Get MQTT gateway configuration
mqtt_config = server_config.get("mqtt_gateway", {})
mqtt_enabled = mqtt_config.get("enabled", False)
mqtt_broker = mqtt_config.get("broker", local_ip)
mqtt_port = mqtt_config.get("port", 1883)
udp_port = mqtt_config.get("udp_port", 8884)
message = f"""OTA接口运行正常
服务器配置信息:
- WebSocket地址: {websocket_url}
- HTTP端口: {http_port}
- WebSocket端口: {port}
- MQTT网关: {'启用' if mqtt_enabled else '禁用'}
- MQTT代理: {mqtt_broker}:{mqtt_port}
- UDP端口: {udp_port}
- 服务器IP: {local_ip}"""
response = web.Response(text=message, content_type="text/plain; charset=utf-8")
message = f"""OTA interface running normally
Server configuration information:
- WebSocket address: {websocket_url}
- HTTP port: {http_port}
- WebSocket port: {port}
- MQTT gateway: {'Enabled' if mqtt_enabled else 'Disabled'}
- MQTT broker: {mqtt_broker}:{mqtt_port}
- UDP port: {udp_port}
- Server IP: {local_ip}"""
response = web.Response(
text=message, content_type="text/plain; charset=utf-8")
except Exception as e:
self.logger.bind(tag=TAG).error(f"OTA GET请求异常: {e}")
response = web.Response(text="OTA接口异常", content_type="text/plain")
self.logger.bind(tag=TAG).error(f"OTA GET request exception: {e}")
response = web.Response(
text="OTA interface exception", content_type="text/plain")
finally:
self._add_cors_headers(response)
return response

View file

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

View file

@ -1,54 +1,54 @@
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
class AuthenticationError(Exception):
"""认证异常"""
"""Authentication exception"""
pass
class AuthMiddleware:
def __init__(self, config):
self.config = config
self.auth_config = config["server"].get("auth", {})
# 构建token查找表
# Build token lookup table
self.tokens = {
item["token"]: item["name"]
for item in self.auth_config.get("tokens", [])
}
# 设备白名单
# Device whitelist
self.allowed_devices = set(
self.auth_config.get("allowed_devices", [])
)
async def authenticate(self, headers):
"""验证连接请求"""
# 检查是否启用认证
"""Verify connection request"""
# Check if authentication is enabled
if not self.auth_config.get("enabled", False):
return True
# 检查设备是否在白名单中
# Check if device is in whitelist
device_id = headers.get("device-id", "")
if self.allowed_devices and device_id in self.allowed_devices:
return True
# 验证Authorization header
# Verify Authorization header
auth_header = headers.get("authorization", "")
if not auth_header.startswith("Bearer "):
logger.bind(tag=TAG).error("Missing or invalid Authorization header")
raise AuthenticationError("Missing or invalid Authorization header")
token = auth_header.split(" ")[1]
if token not in self.tokens:
logger.bind(tag=TAG).error(f"Invalid token: {token}")
raise AuthenticationError("Invalid token")
logger.bind(tag=TAG).info(f"Authentication successful - Device: {device_id}, Token: {self.tokens[token]}")
return True
def get_token_name(self, token):
"""获取token对应的设备名称"""
return self.tokens.get(token)
"""Get device name corresponding to token"""
return self.tokens.get(token)

View file

@ -65,12 +65,13 @@ class ConnectionHandler:
self.config = copy.deepcopy(config)
self.session_id = str(uuid.uuid4())
self.logger = setup_logging()
self.server = server # 保存server实例的引用
self.server = server # Save a reference to the server instance
self.auth = AuthMiddleware(config)
self.need_bind = False
self.bind_code = None
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.headers = None
@ -82,24 +83,24 @@ class ConnectionHandler:
self.chat_history_conf = 0
self.audio_format = "opus"
# 客户端状态相关
# Client state related
self.client_abort = False
self.client_is_speaking = False
self.client_listen_mode = "auto"
# 线程任务相关
# Thread task related
self.loop = asyncio.get_event_loop()
self.stop_event = threading.Event()
self.executor = ThreadPoolExecutor(max_workers=5)
# 添加上报线程池
# Add reporting thread pool
self.report_queue = queue.Queue()
self.report_thread = None
# 未来可以通过修改此处,调节asr的上报和tts的上报,目前默认都开启
# This can be modified in the future to adjust ASR and TTS reporting. Currently, both are enabled by default.
self.report_asr_enable = self.read_config_from_api
self.report_tts_enable = self.read_config_from_api
# 依赖的组件
# Dependent components
self.vad = None
self.asr = None
self.tts = None
@ -109,33 +110,34 @@ class ConnectionHandler:
self.memory = _memory
self.intent = _intent
# 为每个连接单独管理声纹识别
# Manage voiceprint recognition separately for each connection
self.voiceprint_provider = None
# vad相关变量
# VAD related variables
self.client_audio_buffer = bytearray()
self.client_have_voice = False
self.last_activity_time = 0.0 # 统一的活动时间戳(毫秒)
# Unified activity timestamp (milliseconds)
self.last_activity_time = 0.0
self.client_voice_stop = False
self.client_voice_window = deque(maxlen=5)
self.last_is_voice = False
# asr相关变量
# 因为实际部署时可能会用到公共的本地ASR,不能把变量暴露给公共ASR
# 所以涉及到ASR的变量,需要在这里定义,属于connection的私有变量
# ASR related variables
# Since a public local ASR might be used in actual deployment, variables cannot be exposed to the public ASR.
# Therefore, variables related to ASR need to be defined here as private variables of the connection.
self.asr_audio = []
self.asr_audio_queue = queue.Queue()
# llm相关变量
# LLM related variables
self.llm_finish_task = True
self.dialogue = Dialogue()
# tts相关变量
# TTS related variables
self.sentence_id = None
# 处理TTS响应没有文本返回
# Handle cases where TTS response has no text
self.tts_MessageText = ""
# iot相关变量
# IoT related variables
self.iot_descriptors = {}
self.func_handler = None
@ -145,35 +147,36 @@ class ConnectionHandler:
if len(cmd) > self.max_cmd_length:
self.max_cmd_length = len(cmd)
# 是否在聊天结束后关闭连接
# Whether to close the connection after the chat ends
self.close_after_chat = False
self.load_function_plugin = False
self.intent_type = "nointent"
self.timeout_seconds = (
int(self.config.get("close_connection_no_voice_time", 120)) + 60
) # 在原来第一道关闭的基础上加60秒,进行二道关闭
) # Add 60 seconds to the original first-level close for a second-level close
self.timeout_task = None
# {"mcp":true} 表示启用MCP功能
# {"mcp":true} indicates that the MCP function is enabled
self.features = None
# 初始化提示词管理器
# Initialize prompt manager
self.prompt_manager = PromptManager(config, self.logger)
async def handle_connection(self, ws):
try:
# 获取并验证headers
# Get and validate headers
self.headers = dict(ws.request.headers)
if self.headers.get("device-id", None) is None:
# 尝试从 URL 的查询参数中获取 device-id
# Try to get device-id from the URL's query parameters
from urllib.parse import parse_qs, urlparse
# 从 WebSocket 请求中获取路径
# Get the path from the WebSocket request
request_path = ws.request.path
if not request_path:
self.logger.bind(tag=TAG).error("无法获取请求路径")
self.logger.bind(tag=TAG).error(
"Unable to get request path")
return
parsed_url = urlparse(request_path)
query_params = parse_qs(parsed_url.query)
@ -181,7 +184,7 @@ class ConnectionHandler:
self.headers["device-id"] = query_params["device-id"][0]
self.headers["client-id"] = query_params["client-id"][0]
else:
await ws.send("端口正常,如需测试连接,请使用test_page.html")
await ws.send("Port is normal. To test the connection, please use test_page.html")
await self.close(ws)
return
real_ip = self.headers.get("x-real-ip") or self.headers.get(
@ -195,89 +198,92 @@ class ConnectionHandler:
f"{self.client_ip} conn - Headers: {self.headers}"
)
# 进行认证
# Perform authentication
await self.auth.authenticate(self.headers)
# 认证通过,继续处理
# Authentication passed, continue processing
self.websocket = ws
self.device_id = self.headers.get("device-id", None)
# 初始化活动时间戳
# Initialize activity timestamp
self.last_activity_time = time.time() * 1000
# 启动超时检查任务
# Start timeout check task
self.timeout_task = asyncio.create_task(self._check_timeout())
self.welcome_msg = self.config["xiaozhi"]
self.welcome_msg["session_id"] = self.session_id
# 获取差异化配置
# Get differential configuration
self._initialize_private_config()
# 异步初始化
# Asynchronous initialization
self.executor.submit(self._initialize_components)
try:
async for message in self.websocket:
await self._route_message(message)
except websockets.exceptions.ConnectionClosed:
self.logger.bind(tag=TAG).info("客户端断开连接")
self.logger.bind(tag=TAG).info("Client disconnected")
except AuthenticationError as e:
self.logger.bind(tag=TAG).error(f"Authentication failed: {str(e)}")
return
except Exception as e:
stack_trace = traceback.format_exc()
self.logger.bind(tag=TAG).error(f"Connection error: {str(e)}-{stack_trace}")
self.logger.bind(tag=TAG).error(
f"Connection error: {str(e)}-{stack_trace}")
return
finally:
try:
await self._save_and_close(ws)
except Exception as final_error:
self.logger.bind(tag=TAG).error(f"最终清理时出错: {final_error}")
# 确保即使保存记忆失败,也要关闭连接
self.logger.bind(tag=TAG).error(
f"Error during final cleanup: {final_error}")
# Ensure the connection is closed even if saving memory fails
try:
await self.close(ws)
except Exception as close_error:
self.logger.bind(tag=TAG).error(
f"强制关闭连接时出错: {close_error}"
f"Error during forced connection closure: {close_error}"
)
async def _save_and_close(self, ws):
"""保存记忆并关闭连接"""
"""Save memory and close the connection"""
try:
if self.memory:
# 使用线程池异步保存记忆
# Use a thread pool to save memory asynchronously
def save_memory_task():
try:
# 创建新事件循环(避免与主循环冲突)
# Create a new event loop (to avoid conflicts with the main loop)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(
self.memory.save_memory(self.dialogue.dialogue)
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}")
self.logger.bind(tag=TAG).error(
f"Failed to save memory: {e}")
finally:
try:
loop.close()
except Exception:
pass
# 启动线程保存记忆,不等待完成
# Start a thread to save memory, do not wait for completion
threading.Thread(target=save_memory_task, daemon=True).start()
except Exception as e:
self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}")
self.logger.bind(tag=TAG).error(f"Failed to save memory: {e}")
finally:
# 立即关闭连接,不等待记忆保存完成
# Close the connection immediately, do not wait for memory saving to complete
try:
await self.close(ws)
except Exception as close_error:
self.logger.bind(tag=TAG).error(
f"保存记忆后关闭连接失败: {close_error}"
f"Failed to close connection after saving memory: {close_error}"
)
async def _route_message(self, message):
"""消息路由"""
"""Message routing"""
if isinstance(message, str):
await handleTextMessage(self, message)
elif isinstance(message, bytes):
@ -288,28 +294,29 @@ class ConnectionHandler:
self.asr_audio_queue.put(message)
async def handle_restart(self, message):
"""处理服务器重启请求"""
"""Handle server restart request"""
try:
self.logger.bind(tag=TAG).info("收到服务器重启指令,准备执行...")
self.logger.bind(tag=TAG).info(
"Received server restart command, preparing to execute...")
# 发送确认响应
# Send confirmation response
await self.websocket.send(
json.dumps(
{
"type": "server",
"status": "success",
"message": "服务器重启中...",
"message": "Server restarting...",
"content": {"action": "restart"},
}
)
)
# 异步执行重启操作
# Asynchronously execute the restart operation
def restart_server():
"""实际执行重启的方法"""
"""The actual method to execute the restart"""
time.sleep(1)
self.logger.bind(tag=TAG).info("执行服务器重启...")
self.logger.bind(tag=TAG).info("Executing server restart...")
subprocess.Popen(
[sys.executable, "app.py"],
stdin=sys.stdin,
@ -319,11 +326,11 @@ class ConnectionHandler:
)
os._exit(0)
# 使用线程执行重启避免阻塞事件循环
# Use a thread to execute the restart to avoid blocking the event loop
threading.Thread(target=restart_server, daemon=True).start()
except Exception as e:
self.logger.bind(tag=TAG).error(f"重启失败: {str(e)}")
self.logger.bind(tag=TAG).error(f"Restart failed: {str(e)}")
await self.websocket.send(
json.dumps(
{
@ -342,60 +349,62 @@ class ConnectionHandler:
)
self.logger = create_connection_logger(self.selected_module_str)
"""初始化组件"""
"""Initialize components"""
if self.config.get("prompt") is not None:
user_prompt = self.config["prompt"]
# 使用快速提示词进行初始化
# Use a quick prompt for initialization
prompt = self.prompt_manager.get_quick_prompt(user_prompt)
self.change_system_prompt(prompt)
self.logger.bind(tag=TAG).info(
f"快速初始化组件: prompt成功 {prompt[:50]}..."
f"Quickly initialized component: prompt successful {prompt[:50]}..."
)
"""初始化本地组件"""
"""Initialize local components"""
if self.vad is None:
self.vad = self._vad
if self.asr is None:
self.asr = self._initialize_asr()
# 初始化声纹识别
# Initialize voiceprint recognition
self._initialize_voiceprint()
# 打开语音识别通道
# Open speech recognition channel
asyncio.run_coroutine_threadsafe(
self.asr.open_audio_channels(self), self.loop
)
if self.tts is None:
self.tts = self._initialize_tts()
# 打开语音合成通道
# Open speech synthesis channel
asyncio.run_coroutine_threadsafe(
self.tts.open_audio_channels(self), self.loop
)
"""加载记忆"""
"""Load memory"""
self._initialize_memory()
"""加载意图识别"""
"""Load intent recognition"""
self._initialize_intent()
"""初始化上报线程"""
"""Initialize reporting thread"""
self._init_report_threads()
"""更新系统提示词"""
"""Update system prompt"""
self._init_prompt_enhancement()
except Exception as e:
self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}")
self.logger.bind(tag=TAG).error(
f"Failed to instantiate components: {e}")
def _init_prompt_enhancement(self):
# 更新上下文信息
# Update context information
self.prompt_manager.update_context_info(self, self.client_ip)
enhanced_prompt = self.prompt_manager.build_enhanced_prompt(
self.config["prompt"], self.device_id, self.client_ip
)
if enhanced_prompt:
self.change_system_prompt(enhanced_prompt)
self.logger.bind(tag=TAG).info("系统提示词已增强更新")
self.logger.bind(tag=TAG).info(
"System prompt has been enhanced and updated")
def _init_report_threads(self):
"""初始化ASR和TTS上报线程"""
"""Initialize ASR and TTS reporting threads"""
if not self.read_config_from_api or self.need_bind:
return
if self.chat_history_conf == 0:
@ -405,10 +414,10 @@ class ConnectionHandler:
target=self._report_worker, daemon=True
)
self.report_thread.start()
self.logger.bind(tag=TAG).info("TTS上报线程已启动")
self.logger.bind(tag=TAG).info("TTS reporting thread started")
def _initialize_tts(self):
"""初始化TTS"""
"""Initialize TTS"""
tts = None
if not self.need_bind:
tts = initialize_tts(self.config)
@ -419,35 +428,39 @@ class ConnectionHandler:
return tts
def _initialize_asr(self):
"""初始化ASR"""
"""Initialize ASR"""
if self._asr.interface_type == InterfaceType.LOCAL:
# 如果公共ASR是本地服务,则直接返回
# 因为本地一个实例ASR,可以被多个连接共享
# If the public ASR is a local service, return directly
# Because one local ASR instance can be shared by multiple connections
asr = self._asr
else:
# 如果公共ASR是远程服务,则初始化一个新实例
# 因为远程ASR,涉及到websocket连接和接收线程,需要每个连接一个实例
# If the public ASR is a remote service, initialize a new instance
# Because a remote ASR involves a WebSocket connection and a receiving thread, each connection needs its own instance
asr = initialize_asr(self.config)
return asr
def _initialize_voiceprint(self):
"""为当前连接初始化声纹识别"""
"""Initialize voiceprint recognition for the current connection"""
try:
voiceprint_config = self.config.get("voiceprint", {})
if voiceprint_config:
self.voiceprint_provider = VoiceprintProvider(voiceprint_config)
self.logger.bind(tag=TAG).info("声纹识别功能已在连接时动态启用")
self.voiceprint_provider = VoiceprintProvider(
voiceprint_config)
self.logger.bind(tag=TAG).info(
"Voiceprint recognition function dynamically enabled on connection")
else:
self.logger.bind(tag=TAG).info("声纹识别功能未启用或配置不完整")
self.logger.bind(tag=TAG).info(
"Voiceprint recognition function not enabled or configuration is incomplete")
except Exception as e:
self.logger.bind(tag=TAG).warning(f"声纹识别初始化失败: {str(e)}")
self.logger.bind(tag=TAG).warning(
f"Voiceprint recognition initialization failed: {str(e)}")
def _initialize_private_config(self):
"""如果是从配置文件获取,则进行二次实例化"""
"""If getting from the configuration file, perform a second instantiation"""
if not self.read_config_from_api:
return
"""从接口获取差异化的配置进行二次实例化,非全量重新实例化"""
"""Get differential configuration from the interface for a second instantiation, not a full re-instantiation"""
try:
begin_time = time.time()
private_config = get_private_config_from_api(
@ -455,9 +468,10 @@ class ConnectionHandler:
self.headers.get("device-id"),
self.headers.get("client-id", self.headers.get("device-id")),
)
private_config["delete_audio"] = bool(self.config.get("delete_audio", True))
private_config["delete_audio"] = bool(
self.config.get("delete_audio", True))
self.logger.bind(tag=TAG).info(
f"{time.time() - begin_time} 秒,获取差异化配置成功: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}"
f"{time.time() - begin_time} seconds, successfully obtained differential configuration: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}"
)
except DeviceNotFoundException as e:
self.need_bind = True
@ -468,7 +482,8 @@ class ConnectionHandler:
private_config = {}
except Exception as e:
self.need_bind = True
self.logger.bind(tag=TAG).error(f"获取差异化配置失败: {e}")
self.logger.bind(tag=TAG).error(
f"Failed to get differential configuration: {e}")
private_config = {}
init_llm, init_tts, init_memory, init_intent = (
@ -517,9 +532,10 @@ class ConnectionHandler:
if private_config.get("Intent", None) is not None:
init_intent = True
self.config["Intent"] = private_config["Intent"]
model_intent = private_config.get("selected_module", {}).get("Intent", {})
model_intent = private_config.get(
"selected_module", {}).get("Intent", {})
self.config["selected_module"]["Intent"] = model_intent
# 加载插件配置
# Load plugin configuration
if model_intent != "Intent_nointent":
plugin_from_server = private_config.get("plugins", {})
for plugin, config_str in plugin_from_server.items():
@ -527,16 +543,17 @@ class ConnectionHandler:
self.config["plugins"] = plugin_from_server
self.config["Intent"][self.config["selected_module"]["Intent"]][
"functions"
] = plugin_from_server.keys()
] = list(plugin_from_server.keys())
if private_config.get("prompt", None) is not None:
self.config["prompt"] = private_config["prompt"]
# 获取声纹信息
# Get voiceprint information
if private_config.get("voiceprint", None) is not None:
self.config["voiceprint"] = private_config["voiceprint"]
if private_config.get("summaryMemory", None) is not None:
self.config["summaryMemory"] = private_config["summaryMemory"]
if private_config.get("device_max_output_size", None) is not None:
self.max_output_size = int(private_config["device_max_output_size"])
self.max_output_size = int(
private_config["device_max_output_size"])
if private_config.get("chat_history_conf", None) is not None:
self.chat_history_conf = int(private_config["chat_history_conf"])
if private_config.get("mcp_endpoint", None) is not None:
@ -553,7 +570,8 @@ class ConnectionHandler:
init_intent,
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}")
self.logger.bind(tag=TAG).error(
f"Failed to initialize components: {e}")
modules = {}
if modules.get("tts", None) is not None:
self.tts = modules["tts"]
@ -571,7 +589,7 @@ class ConnectionHandler:
def _initialize_memory(self):
if self.memory is None:
return
"""初始化记忆模块"""
"""Initialize memory module"""
self.memory.init_memory(
role_id=self.device_id,
llm=self.llm,
@ -579,36 +597,38 @@ class ConnectionHandler:
save_to_file=not self.read_config_from_api,
)
# 获取记忆总结配置
# Get memory summary configuration
memory_config = self.config["Memory"]
memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]][
"type"
]
# 如果使用 nomen,直接返回
# If using nomem, return directly
if memory_type == "nomem":
return
# 使用 mem_local_short 模式
# Use mem_local_short mode
elif memory_type == "mem_local_short":
memory_llm_name = memory_config[self.config["selected_module"]["Memory"]][
"llm"
]
if memory_llm_name and memory_llm_name in self.config["LLM"]:
# 如果配置了专用LLM,则创建独立的LLM实例
# If a dedicated LLM is configured, create an independent LLM instance
from core.utils import llm as llm_utils
memory_llm_config = self.config["LLM"][memory_llm_name]
memory_llm_type = memory_llm_config.get("type", memory_llm_name)
memory_llm_type = memory_llm_config.get(
"type", memory_llm_name)
memory_llm = llm_utils.create_instance(
memory_llm_type, memory_llm_config
)
self.logger.bind(tag=TAG).info(
f"为记忆总结创建了专用LLM: {memory_llm_name}, 类型: {memory_llm_type}"
f"Created a dedicated LLM for memory summary: {memory_llm_name}, type: {memory_llm_type}"
)
self.memory.set_llm(memory_llm)
else:
# 否则使用主LLM
# Otherwise use main LLM
self.memory.set_llm(self.llm)
self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型")
self.logger.bind(tag=TAG).info(
"Using main LLM as intent recognition model")
def _initialize_intent(self):
if self.intent is None:
@ -618,60 +638,63 @@ class ConnectionHandler:
]["type"]
if self.intent_type == "function_call" or self.intent_type == "intent_llm":
self.load_function_plugin = True
"""初始化意图识别模块"""
# 获取意图识别配置
"""Initialize intent recognition module"""
# Get intent recognition configuration
intent_config = self.config["Intent"]
intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]][
"type"
]
# 如果使用 nointent,直接返回
# If using nointent, return directly
if intent_type == "nointent":
return
# 使用 intent_llm 模式
# Use intent_llm mode
elif intent_type == "intent_llm":
intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][
"llm"
]
if intent_llm_name and intent_llm_name in self.config["LLM"]:
# 如果配置了专用LLM,则创建独立的LLM实例
# If a dedicated LLM is configured, create an independent LLM instance
from core.utils import llm as llm_utils
intent_llm_config = self.config["LLM"][intent_llm_name]
intent_llm_type = intent_llm_config.get("type", intent_llm_name)
intent_llm_type = intent_llm_config.get(
"type", intent_llm_name)
intent_llm = llm_utils.create_instance(
intent_llm_type, intent_llm_config
)
self.logger.bind(tag=TAG).info(
f"为意图识别创建了专用LLM: {intent_llm_name}, 类型: {intent_llm_type}"
f"Created a dedicated LLM for intent recognition: {intent_llm_name}, type: {intent_llm_type}"
)
self.intent.set_llm(intent_llm)
else:
# 否则使用主LLM
# Otherwise use main LLM
self.intent.set_llm(self.llm)
self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型")
self.logger.bind(tag=TAG).info(
"Using main LLM as intent recognition model")
"""加载统一工具处理器"""
"""Load unified tool handler"""
self.func_handler = UnifiedToolHandler(self)
# 异步初始化工具处理器
# Asynchronously initialize tool handler
if hasattr(self, "loop") and self.loop:
asyncio.run_coroutine_threadsafe(self.func_handler._initialize(), self.loop)
asyncio.run_coroutine_threadsafe(
self.func_handler._initialize(), self.loop)
def change_system_prompt(self, prompt):
self.prompt = prompt
# 更新系统prompt至上下文
# Update system prompt in the context
self.dialogue.update_system_message(self.prompt)
def chat(self, query, tool_call=False, depth=0):
self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}")
self.logger.bind(tag=TAG).info(f"LLM received user message: {query}")
self.llm_finish_task = False
if not tool_call:
self.dialogue.put(Message(role="user", content=query))
# 为最顶层时新建会话ID和发送FIRST请求
# Create a new session ID and send a FIRST request for the top-level call
if depth == 0:
self.sentence_id = str(uuid.uuid4().hex)
self.tts.tts_text_queue.put(
@ -689,7 +712,7 @@ class ConnectionHandler:
response_message = []
try:
# 使用带记忆的对话
# Use dialogue with memory
memory_str = None
if self.memory is not None:
future = asyncio.run_coroutine_threadsafe(
@ -698,7 +721,7 @@ class ConnectionHandler:
memory_str = future.result()
if self.intent_type == "function_call" and functions is not None:
# 使用支持functions的streaming接口
# Use streaming interface that supports functions
llm_responses = self.llm.response_with_functions(
self.session_id,
self.dialogue.get_llm_dialogue_with_memory(
@ -714,10 +737,11 @@ class ConnectionHandler:
),
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}")
self.logger.bind(tag=TAG).error(
f"LLM processing error for '{query}': {e}")
return None
# 处理流式响应
# Handle streaming response
tool_call_flag = False
function_name = None
function_id = None
@ -751,7 +775,7 @@ class ConnectionHandler:
else:
content = response
# 在llm回复中获取情绪表情,一轮对话只在开头获取一次
# Get emotion from LLM reply, only once at the beginning of a conversation turn
if emotion_flag and content is not None and content.strip():
asyncio.run_coroutine_threadsafe(
textUtils.get_emotion(self, content),
@ -770,7 +794,7 @@ class ConnectionHandler:
content_detail=content,
)
)
# 处理function call
# Handle function call
if tool_call_flag:
bHasError = False
if function_id is None:
@ -794,11 +818,12 @@ class ConnectionHandler:
f"function call error: {content_arguments}"
)
if not bHasError:
# 如需要大模型先处理一轮,添加相关处理后的日志情况
# If the LLM needs to process a turn first, add relevant processed log information
if len(response_message) > 0:
text_buff = "".join(response_message)
self.tts_MessageText = text_buff
self.dialogue.put(Message(role="assistant", content=text_buff))
self.dialogue.put(
Message(role="assistant", content=text_buff))
response_message.clear()
self.logger.bind(tag=TAG).debug(
f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}"
@ -809,16 +834,17 @@ class ConnectionHandler:
"arguments": function_arguments,
}
# 使用统一工具处理器处理所有工具调用
# Use unified tool handler to process all tool calls
result = asyncio.run_coroutine_threadsafe(
self.func_handler.handle_llm_function_call(
self, function_call_data
),
self.loop,
).result()
self._handle_function_result(result, function_call_data, depth=depth)
self._handle_function_result(
result, function_call_data, depth=depth)
# 存储对话内容
# Store dialogue content
if len(response_message) > 0:
text_buff = "".join(response_message)
self.tts_MessageText = text_buff
@ -832,7 +858,7 @@ class ConnectionHandler:
)
)
self.llm_finish_task = True
# 使用lambda延迟计算,只有在DEBUG级别时才执行get_llm_dialogue()
# Use lambda for delayed calculation, get_llm_dialogue() is only executed at DEBUG level
self.logger.bind(tag=TAG).debug(
lambda: json.dumps(
self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False
@ -842,11 +868,12 @@ class ConnectionHandler:
return True
def _handle_function_result(self, result, function_call_data, depth):
if result.action == Action.RESPONSE: # 直接回复前端
if result.action == Action.RESPONSE: # Respond directly to the front-end
text = result.response
self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text)
self.tts.tts_one_sentence(
self, ContentType.TEXT, content_detail=text)
self.dialogue.put(Message(role="assistant", content=text))
elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复
elif result.action == Action.REQLLM: # Request LLM to generate a reply after calling the function
text = result.result
if text is not None and len(text) > 0:
function_id = function_call_data["id"]
@ -881,53 +908,57 @@ class ConnectionHandler:
self.chat(text, tool_call=True, depth=depth + 1)
elif result.action == Action.NOTFOUND or result.action == Action.ERROR:
text = result.response if result.response else result.result
self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text)
self.tts.tts_one_sentence(
self, ContentType.TEXT, content_detail=text)
self.dialogue.put(Message(role="assistant", content=text))
else:
pass
def _report_worker(self):
"""聊天记录上报工作线程"""
"""Chat history reporting worker thread"""
while not self.stop_event.is_set():
try:
# 从队列获取数据,设置超时以便定期检查停止事件
# Get data from the queue, set a timeout to periodically check the stop event
item = self.report_queue.get(timeout=1)
if item is None: # 检测毒丸对象
if item is None: # Detect the poison pill object
break
try:
# 检查线程池状态
# Check the thread pool status
if self.executor is None:
continue
# 提交任务到线程池
# Submit the task to the thread pool
self.executor.submit(self._process_report, *item)
except Exception as e:
self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}")
self.logger.bind(tag=TAG).error(
f"Chat history reporting thread exception: {e}")
except queue.Empty:
continue
except Exception as e:
self.logger.bind(tag=TAG).error(f"聊天记录上报工作线程异常: {e}")
self.logger.bind(tag=TAG).error(
f"Chat history reporting worker thread exception: {e}")
self.logger.bind(tag=TAG).info("聊天记录上报线程已退出")
self.logger.bind(tag=TAG).info("Chat history reporting thread exited")
def _process_report(self, type, text, audio_data, report_time):
"""处理上报任务"""
"""Process the reporting task"""
try:
# 执行上报(传入二进制数据)
# Execute the report (pass binary data)
report(self, type, text, audio_data, report_time)
except Exception as e:
self.logger.bind(tag=TAG).error(f"上报处理异常: {e}")
self.logger.bind(tag=TAG).error(
f"Report processing exception: {e}")
finally:
# 标记任务完成
# Mark the task as done
self.report_queue.task_done()
def clearSpeakStatus(self):
self.client_is_speaking = False
self.logger.bind(tag=TAG).debug(f"清除服务端讲话状态")
self.logger.bind(tag=TAG).debug(f"Cleared server speaking status")
async def close(self, ws=None):
"""资源清理方法"""
"""Resource cleanup method"""
try:
# 取消超时任务
# Cancel the timeout task
if self.timeout_task and not self.timeout_task.done():
self.timeout_task.cancel()
try:
@ -936,36 +967,36 @@ class ConnectionHandler:
pass
self.timeout_task = None
# 清理工具处理器资源
# Clean up tool handler resources
if hasattr(self, "func_handler") and self.func_handler:
try:
await self.func_handler.cleanup()
except Exception as cleanup_error:
self.logger.bind(tag=TAG).error(
f"清理工具处理器时出错: {cleanup_error}"
f"Error cleaning up tool handler: {cleanup_error}"
)
# 触发停止事件
# Trigger the stop event
if self.stop_event:
self.stop_event.set()
# 清空任务队列
# Clear task queues
self.clear_queues()
# 关闭WebSocket连接
# Close the WebSocket connection
try:
if ws:
# 安全地检查WebSocket状态并关闭
# Safely check WebSocket state and close
try:
if hasattr(ws, "closed") and not ws.closed:
await ws.close()
elif hasattr(ws, "state") and ws.state.name != "CLOSED":
await ws.close()
else:
# 如果没有closed属性,直接尝试关闭
# If no closed attribute, try to close directly
await ws.close()
except Exception:
# 如果关闭失败,忽略错误
# If closing fails, ignore the error
pass
elif self.websocket:
try:
@ -980,43 +1011,45 @@ class ConnectionHandler:
):
await self.websocket.close()
else:
# 如果没有closed属性,直接尝试关闭
# If no closed attribute, try to close directly
await self.websocket.close()
except Exception:
# 如果关闭失败,忽略错误
# If closing fails, ignore the error
pass
except Exception as ws_error:
self.logger.bind(tag=TAG).error(f"关闭WebSocket连接时出错: {ws_error}")
self.logger.bind(tag=TAG).error(
f"Error closing WebSocket connection: {ws_error}")
if self.tts:
await self.tts.close()
# 最后关闭线程池(避免阻塞)
# Finally close thread pool (avoid blocking)
if self.executor:
try:
self.executor.shutdown(wait=False)
except Exception as executor_error:
self.logger.bind(tag=TAG).error(
f"关闭线程池时出错: {executor_error}"
f"Error shutting down thread pool: {executor_error}"
)
self.executor = None
self.logger.bind(tag=TAG).info("连接资源已释放")
self.logger.bind(tag=TAG).info("Connection resources released")
except Exception as e:
self.logger.bind(tag=TAG).error(f"关闭连接时出错: {e}")
self.logger.bind(tag=TAG).error(
f"Error occurred while closing connection: {e}")
finally:
# 确保停止事件被设置
# Ensure the stop event is set
if self.stop_event:
self.stop_event.set()
def clear_queues(self):
"""清空所有任务队列"""
"""Clear all task queues"""
if self.tts:
self.logger.bind(tag=TAG).debug(
f"开始清理: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
f"Starting cleanup: TTS queue size={self.tts.tts_text_queue.qsize()}, audio queue size={self.tts.tts_audio_queue.qsize()}"
)
# 使用非阻塞方式清空队列
# Use non-blocking method to clear queues
for q in [
self.tts.tts_text_queue,
self.tts.tts_audio_queue,
@ -1031,7 +1064,7 @@ class ConnectionHandler:
break
self.logger.bind(tag=TAG).debug(
f"清理结束: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
f"Cleanup completed: TTS queue size={self.tts.tts_text_queue.qsize()}, audio queue size={self.tts.tts_audio_queue.qsize()}"
)
def reset_vad_states(self):
@ -1052,10 +1085,10 @@ class ConnectionHandler:
self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}")
async def _check_timeout(self):
"""检查连接超时"""
"""Check for connection timeout"""
try:
while not self.stop_event.is_set():
# 检查是否超时(只有在时间戳已初始化的情况下)
# Check for timeout (only if the timestamp has been initialized)
if self.last_activity_time > 0.0:
current_time = time.time() * 1000
if (
@ -1063,20 +1096,21 @@ class ConnectionHandler:
> self.timeout_seconds * 1000
):
if not self.stop_event.is_set():
self.logger.bind(tag=TAG).info("连接超时,准备关闭")
# 设置停止事件,防止重复处理
self.logger.bind(tag=TAG).info(
"Connection timed out, preparing to close")
# Set the stop event to prevent duplicate processing
self.stop_event.set()
# 使用 try-except 包装关闭操作,确保不会因为异常而阻塞
# Use try-except to wrap the close operation, ensuring no blocking due to exceptions
try:
await self.close(self.websocket)
except Exception as close_error:
self.logger.bind(tag=TAG).error(
f"超时关闭连接时出错: {close_error}"
f"Error closing connection on timeout: {close_error}"
)
break
# 每10秒检查一次,避免过于频繁
# Check every 10 seconds to avoid being too frequent
await asyncio.sleep(10)
except Exception as e:
self.logger.bind(tag=TAG).error(f"超时检查任务出错: {e}")
self.logger.bind(tag=TAG).error(f"Timeout check task error: {e}")
finally:
self.logger.bind(tag=TAG).info("超时检查任务已退出")
self.logger.bind(tag=TAG).info("Timeout check task has exited")

View file

@ -5,12 +5,12 @@ TAG = __name__
async def handleAbortMessage(conn):
conn.logger.bind(tag=TAG).info("Abort message received")
# 设置成打断状态,会自动打断llm、tts任务
# Set to interrupt state, will automatically interrupt llm and tts tasks
conn.client_abort = True
conn.clear_queues()
# 打断客户端说话状态
# Interrupt client speaking state
await conn.websocket.send(
json.dumps({"type": "tts", "state": "stop", "session_id": conn.session_id})
)
conn.clearSpeakStatus()
conn.logger.bind(tag=TAG).info("Abort message received-end")
conn.logger.bind(tag=TAG).info("Abort message received-end")

View file

@ -21,39 +21,39 @@ WAKEUP_CONFIG = {
"words": ["你好", "你好啊", "嘿,你好", "嗨"],
}
# 创建全局的唤醒词配置管理器
# Create global wakeup words configuration manager
wakeup_words_config = WakeupWordsConfig()
# 用于防止并发调用wakeupWordsResponse的锁
# Lock to prevent concurrent calls to wakeupWordsResponse
_wakeup_response_lock = asyncio.Lock()
async def handleHelloMessage(conn, msg_json):
"""处理hello消息"""
"""Handle hello message"""
audio_params = msg_json.get("audio_params")
if audio_params:
format = audio_params.get("format")
conn.logger.bind(tag=TAG).info(f"客户端音频格式: {format}")
conn.logger.bind(tag=TAG).info(f"Client audio format: {format}")
conn.audio_format = format
conn.welcome_msg["audio_params"] = audio_params
features = msg_json.get("features")
if features:
conn.logger.bind(tag=TAG).info(f"客户端特性: {features}")
conn.logger.bind(tag=TAG).info(f"Client features: {features}")
conn.features = features
# Handle both list and dictionary formats for features
has_mcp = False
if isinstance(features, list):
has_mcp = "mcp" in features
elif isinstance(features, dict):
has_mcp = features.get("mcp", False)
if has_mcp:
conn.logger.bind(tag=TAG).info("客户端支持MCP")
conn.logger.bind(tag=TAG).info("Client supports MCP")
conn.mcp_client = MCPClient()
# 发送初始化
# Send initialization
asyncio.create_task(send_mcp_initialize_message(conn))
# 发送mcp消息,获取tools列表
# Send mcp message to get tools list
asyncio.create_task(send_mcp_tools_list_request(conn))
await conn.websocket.send(json.dumps(conn.welcome_msg))
@ -74,12 +74,12 @@ async def checkWakeupWords(conn, text):
conn.just_woken_up = True
await send_stt_message(conn, text)
# 获取当前音色
# Get current voice
voice = getattr(conn.tts, "voice", "default")
if not voice:
voice = "default"
# 获取唤醒词回复配置
# Get wakeup words reply configuration
response = wakeup_words_config.get_wakeup_response(voice)
if not response or not response.get("file_path"):
response = {
@ -89,18 +89,19 @@ async def checkWakeupWords(conn, text):
"text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",
}
# 播放唤醒词回复
# Play wakeup words reply
conn.client_abort = False
opus_packets, _ = audio_to_data(response.get("file_path"))
conn.logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}")
conn.logger.bind(tag=TAG).info(
f"Playing wakeup words reply: {response.get('text')}")
await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
await sendAudioMessage(conn, SentenceType.LAST, [], None)
# 补充对话
# Add to dialogue
conn.dialogue.put(Message(role="assistant", content=response.get("text")))
# 检查是否需要更新唤醒词回复
# Check if wakeup words reply needs to be updated
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
if not _wakeup_response_lock.locked():
asyncio.create_task(wakeupWordsResponse(conn))
@ -112,38 +113,38 @@ async def wakeupWordsResponse(conn):
return
try:
# 尝试获取锁,如果获取不到就返回
# Try to acquire lock, return if cannot acquire
if not await _wakeup_response_lock.acquire():
return
# 生成唤醒词回复
# Generate wakeup words reply
wakeup_word = random.choice(WAKEUP_CONFIG["words"])
question = (
"此刻用户正在和你说```"
"The user is currently saying ```"
+ wakeup_word
+ "```。\n请你根据以上用户的内容进行20-30字回复。要符合系统设置的角色情感和态度,不要像机器人一样说话。\n"
+ "请勿对这条内容本身进行任何解释和回应,请勿返回表情符号,仅返回对用户的内容的回复。"
+ "``` to you.\nPlease reply to the user's content above in 20-30 words. It should match the role's emotions and attitude set in the system, don't talk like a robot.\n"
+ "Please do not explain or respond to this content itself, do not return emojis, only return a reply to the user's content."
)
result = conn.llm.response_no_stream(conn.config["prompt"], question)
if not result or len(result) == 0:
return
# 生成TTS音频
# Generate TTS audio
tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
if not tts_result:
return
# 获取当前音色
# Get current voice
voice = getattr(conn.tts, "voice", "default")
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000)
file_path = wakeup_words_config.generate_file_path(voice)
with open(file_path, "wb") as f:
f.write(wav_bytes)
# 更新配置
# Update configuration
wakeup_words_config.update_wakeup_response(voice, file_path, result)
finally:
# 确保在任何情况下都释放锁
# Ensure lock is released in any case
if _wakeup_response_lock.locked():
_wakeup_response_lock.release()

View file

@ -13,44 +13,47 @@ TAG = __name__
async def handle_user_intent(conn, text):
# 预处理输入文本,处理可能的JSON格式
# Preprocess input text, handle possible JSON format
try:
if text.strip().startswith('{') and text.strip().endswith('}'):
parsed_data = json.loads(text)
if isinstance(parsed_data, dict) and "content" in parsed_data:
text = parsed_data["content"] # 提取content用于意图分析
conn.current_speaker = parsed_data.get("speaker") # 保留说话人信息
# Extract content for intent analysis
text = parsed_data["content"]
conn.current_speaker = parsed_data.get(
"speaker") # Preserve speaker information
except (json.JSONDecodeError, TypeError):
pass
# 检查是否有明确的退出命令
# Check if there is an explicit exit command
filtered_text = remove_punctuation_and_length(text)[1]
if await check_direct_exit(conn, filtered_text):
return True
# 检查是否是唤醒词
# Check if it's a wake-up word
if await checkWakeupWords(conn, filtered_text):
return True
if conn.intent_type == "function_call":
# 使用支持function calling的聊天方法,不再进行意图分析
# Use chat method that supports function calling, no longer perform intent analysis
return False
# 使用LLM进行意图分析
# Use LLM for intent analysis
intent_result = await analyze_intent_with_llm(conn, text)
if not intent_result:
return False
# 会话开始时生成sentence_id
# Generate sentence_id at the beginning of the conversation
conn.sentence_id = str(uuid.uuid4().hex)
# 处理各种意图
# Handle various intents
return await process_intent_result(conn, intent_result, text)
async def check_direct_exit(conn, text):
"""检查是否有明确的退出命令"""
"""Check if there is an explicit exit command"""
_, text = remove_punctuation_and_length(text)
cmd_exit = conn.cmd_exit
for cmd in cmd_exit:
if text == cmd:
conn.logger.bind(tag=TAG).info(f"识别到明确的退出命令: {text}")
conn.logger.bind(tag=TAG).info(
f"Recognized explicit exit command: {text}")
await send_stt_message(conn, text)
await conn.close()
return True
@ -58,33 +61,34 @@ async def check_direct_exit(conn, text):
async def analyze_intent_with_llm(conn, text):
"""使用LLM分析用户意图"""
"""Use LLM to analyze user intent"""
if not hasattr(conn, "intent") or not conn.intent:
conn.logger.bind(tag=TAG).warning("意图识别服务未初始化")
conn.logger.bind(tag=TAG).warning(
"Intent recognition service not initialized")
return None
# 对话历史记录
# Conversation history records
dialogue = conn.dialogue
try:
intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
return intent_result
except Exception as e:
conn.logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}")
conn.logger.bind(tag=TAG).error(f"Intent recognition failed: {str(e)}")
return None
async def process_intent_result(conn, intent_result, original_text):
"""处理意图识别结果"""
"""Process intent recognition results"""
try:
# 尝试将结果解析为JSON
# Try to parse the result as JSON
intent_data = json.loads(intent_result)
# 检查是否有function_call
# Check if there is a function_call
if "function_call" in intent_data:
# 直接从意图识别获取了function_call
# Directly obtained function_call from intent recognition
conn.logger.bind(tag=TAG).debug(
f"检测到function_call格式的意图结果: {intent_data['function_call']['name']}"
f"Detected function_call format intent result: {intent_data['function_call']['name']}"
)
function_name = intent_data["function_call"]["name"]
if function_name == "continue_chat":
@ -95,7 +99,7 @@ async def process_intent_result(conn, intent_result, original_text):
function_args = intent_data["function_call"]["arguments"]
if function_args is None:
function_args = {}
# 确保参数是字符串格式的JSON
# Ensure parameters are in string format JSON
if isinstance(function_args, dict):
function_args = json.dumps(function_args)
@ -108,11 +112,11 @@ async def process_intent_result(conn, intent_result, original_text):
await send_stt_message(conn, original_text)
conn.client_abort = False
# 使用executor执行函数调用和结果处理
# Use executor to execute function calls and result processing
def process_function_call():
conn.dialogue.put(Message(role="user", content=original_text))
# 使用统一工具处理器处理所有工具调用
# Use unified tool handler to process all tool calls
try:
result = asyncio.run_coroutine_threadsafe(
conn.func_handler.handle_llm_function_call(
@ -121,20 +125,21 @@ async def process_intent_result(conn, intent_result, original_text):
conn.loop,
).result()
except Exception as e:
conn.logger.bind(tag=TAG).error(f"工具调用失败: {e}")
conn.logger.bind(tag=TAG).error(f"Tool call failed: {e}")
result = ActionResponse(
action=Action.ERROR, result=str(e), response=str(e)
)
if result:
if result.action == Action.RESPONSE: # 直接回复前端
if result.action == Action.RESPONSE: # Directly reply to frontend
text = result.response
if text is not None:
speak_txt(conn, text)
elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复
elif result.action == Action.REQLLM: # Call function then request LLM to generate reply
text = result.result
conn.dialogue.put(Message(role="tool", content=text))
llm_result = conn.intent.replyResult(text, original_text)
llm_result = conn.intent.replyResult(
text, original_text)
if llm_result is None:
llm_result = text
speak_txt(conn, llm_result)
@ -147,19 +152,19 @@ async def process_intent_result(conn, intent_result, original_text):
speak_txt(conn, text)
elif function_name != "play_music":
# For backward compatibility with original code
# 获取当前最新的文本索引
# Get the current latest text index
text = result.response
if text is None:
text = result.result
if text is not None:
speak_txt(conn, text)
# 将函数执行放在线程池中
# Put function execution in thread pool
conn.executor.submit(process_function_call)
return True
return False
except json.JSONDecodeError as e:
conn.logger.bind(tag=TAG).error(f"处理意图结果时出错: {e}")
conn.logger.bind(tag=TAG).error(f"Error processing intent result: {e}")
return False
@ -179,4 +184,4 @@ def speak_txt(conn, text):
content_type=ContentType.ACTION,
)
)
conn.dialogue.put(Message(role="assistant", content=text))
conn.dialogue.put(Message(role="assistant", content=text))

View file

@ -12,53 +12,55 @@ TAG = __name__
async def handleAudioMessage(conn, audio):
# 当前片段是否有人说话
# Whether the current segment has someone speaking
have_voice = conn.vad.is_vad(conn, audio)
# 如果设备刚刚被唤醒,短暂忽略VAD检测
# If the device was just woken up, briefly ignore VAD detection
if have_voice and hasattr(conn, "just_woken_up") and conn.just_woken_up:
have_voice = False
# 设置一个短暂延迟后恢复VAD检测
# Set a brief delay before resuming VAD detection
conn.asr_audio.clear()
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
if have_voice:
if conn.client_is_speaking:
await handleAbortMessage(conn)
# 设备长时间空闲检测,用于say goodbye
# Device long-term idle detection, used for say goodbye
await no_voice_close_connect(conn, have_voice)
# 接收音频
# Receive audio
await conn.asr.receive_audio(conn, audio, have_voice)
async def resume_vad_detection(conn):
# 等待2秒后恢复VAD检测
# Wait 2 seconds before resuming VAD detection
await asyncio.sleep(1)
conn.just_woken_up = False
async def startToChat(conn, text):
# 检查输入是否是JSON格式(包含说话人信息)
# Check if input is in JSON format (containing speaker information)
speaker_name = None
actual_text = text
try:
# 尝试解析JSON格式的输入
# Try to parse JSON format input
if text.strip().startswith('{') and text.strip().endswith('}'):
data = json.loads(text)
if 'speaker' in data and 'content' in data:
speaker_name = data['speaker']
actual_text = data['content']
conn.logger.bind(tag=TAG).info(f"解析到说话人信息: {speaker_name}")
# 直接使用JSON格式的文本,不解析
conn.logger.bind(tag=TAG).info(
f"Parsed speaker information: {speaker_name}")
# Use JSON format text directly, do not parse
actual_text = text
except (json.JSONDecodeError, KeyError):
# 如果解析失败,继续使用原始文本
# If parsing fails, continue using original text
pass
# 保存说话人信息到连接对象
# Save speaker information to connection object
if speaker_name:
conn.current_speaker = speaker_name
else:
@ -68,7 +70,7 @@ async def startToChat(conn, text):
await check_bind_device(conn)
return
# 如果当日的输出字数大于限定的字数
# If the daily output word count exceeds the limit
if conn.max_output_size > 0:
if check_device_output_limit(
conn.headers.get("device-id"), conn.max_output_size
@ -78,14 +80,14 @@ async def startToChat(conn, text):
if conn.client_is_speaking:
await handleAbortMessage(conn)
# 首先进行意图分析,使用实际文本内容
# First perform intent analysis, using actual text content
intent_handled = await handle_user_intent(conn, actual_text)
if intent_handled:
# 如果意图已被处理,不再进行聊天
# If intent has been handled, no longer proceed with chat
return
# 意图未被处理,继续常规聊天流程,使用实际文本内容
# Intent not handled, continue with regular chat flow, using actual text content
await send_stt_message(conn, actual_text)
conn.executor.submit(conn.chat, actual_text)
@ -94,7 +96,7 @@ async def no_voice_close_connect(conn, have_voice):
if have_voice:
conn.last_activity_time = time.time() * 1000
return
# 只有在已经初始化过时间戳的情况下才进行超时检查
# Only perform timeout check when timestamp has been initialized
if conn.last_activity_time > 0.0:
no_voice_time = time.time() * 1000 - conn.last_activity_time
close_connection_no_voice_time = int(
@ -108,17 +110,18 @@ async def no_voice_close_connect(conn, have_voice):
conn.client_abort = False
end_prompt = conn.config.get("end_prompt", {})
if end_prompt and end_prompt.get("enable", True) is False:
conn.logger.bind(tag=TAG).info("结束对话,无需发送结束提示语")
conn.logger.bind(tag=TAG).info(
"End conversation, no need to send ending prompt")
await conn.close()
return
prompt = end_prompt.get("prompt")
if not prompt:
prompt = "请你以```时间过得真快```未来头,用富有感情、依依不舍的话来结束这场对话吧。!"
prompt = "Please use ```time flies so fast``` as the opening, and use emotionally rich, reluctant words to end this conversation!"
await startToChat(conn, prompt)
async def max_out_size(conn):
text = "不好意思,我现在有点事情要忙,明天这个时候我们再聊,约好了哦!明天不见不散,拜拜!"
text = "Sorry, I have some things to deal with now. Let's chat again at this time tomorrow. It's a promise! See you tomorrow, goodbye!"
await send_stt_message(conn, text)
file_path = "config/assets/max_output_size.wav"
opus_packets, _ = audio_to_data(file_path)
@ -128,35 +131,38 @@ async def max_out_size(conn):
async def check_bind_device(conn):
if conn.bind_code:
# 确保bind_code是6位数字
# Ensure bind_code is a 6-digit number
if len(conn.bind_code) != 6:
conn.logger.bind(tag=TAG).error(f"无效的绑定码格式: {conn.bind_code}")
text = "绑定码格式错误,请检查配置。"
conn.logger.bind(tag=TAG).error(
f"Invalid binding code format: {conn.bind_code}")
text = "Binding code format error, please check configuration."
await send_stt_message(conn, text)
return
text = f"请登录控制面板,输入{conn.bind_code},绑定设备。"
text = f"Please log into the control panel and enter {conn.bind_code} to bind the device."
await send_stt_message(conn, text)
# 播放提示音
# Play notification sound
music_path = "config/assets/bind_code.wav"
opus_packets, _ = audio_to_data(music_path)
conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text))
# 逐个播放数字
for i in range(6): # 确保只播放6位数字
# Play digits one by one
for i in range(6): # Ensure only 6 digits are played
try:
digit = conn.bind_code[i]
num_path = f"config/assets/bind_code/{digit}.wav"
num_packets, _ = audio_to_data(num_path)
conn.tts.tts_audio_queue.put((SentenceType.MIDDLE, num_packets, None))
conn.tts.tts_audio_queue.put(
(SentenceType.MIDDLE, num_packets, None))
except Exception as e:
conn.logger.bind(tag=TAG).error(f"播放数字音频失败: {e}")
conn.logger.bind(tag=TAG).error(
f"Failed to play digit audio: {e}")
continue
conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None))
else:
text = f"没有找到该设备的版本信息,请正确配置 OTA地址,然后重新编译固件。"
text = f"Version information for this device was not found. Please configure the OTA address correctly and then recompile the firmware."
await send_stt_message(conn, text)
music_path = "config/assets/bind_not_found.wav"
opus_packets, _ = audio_to_data(music_path)
conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))

View file

@ -1,12 +1,12 @@
"""
TTS上报功能已集成到ConnectionHandler类中。
TTS reporting functionality has been integrated into the ConnectionHandler class.
上报功能包括:
1. 每个连接对象拥有自己的上报队列和处理线程
2. 上报线程的生命周期与连接对象绑定
3. 使用ConnectionHandler.enqueue_tts_report方法进行上报
Reporting functionality includes:
1. Each connection object has its own reporting queue and processing thread
2. The reporting thread's lifecycle is bound to the connection object
3. Use ConnectionHandler.enqueue_tts_report method for reporting
具体实现请参考core/connection.py中的相关代码。
For specific implementation, please refer to the relevant code in core/connection.py.
"""
import time
@ -19,21 +19,21 @@ TAG = __name__
def report(conn, type, text, opus_data, report_time):
"""执行聊天记录上报操作
"""Execute chat history reporting operation
Args:
conn: 连接对象
type: 上报类型,1为用户,2为智能体
text: 合成文本
opus_data: opus音频数据
report_time: 上报时间
conn: Connection object
type: Report type, 1 for user, 2 for agent
text: Synthesized text
opus_data: Opus audio data
report_time: Report time
"""
try:
if opus_data:
audio_data = opus_to_wav(conn, opus_data)
else:
audio_data = None
# 执行上报
# Execute reporting
manage_report(
mac_address=conn.device_id,
session_id=conn.session_id,
@ -43,20 +43,20 @@ def report(conn, type, text, opus_data, report_time):
report_time=report_time,
)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"聊天记录上报失败: {e}")
conn.logger.bind(tag=TAG).error(f"Chat history reporting failed: {e}")
def opus_to_wav(conn, opus_data):
"""将Opus数据转换为WAV格式的字节流
"""Convert Opus data to WAV format byte stream
Args:
output_dir: 输出目录(保留参数以保持接口兼容)
opus_data: opus音频数据
output_dir: Output directory (parameter retained for interface compatibility)
opus_data: Opus audio data
Returns:
bytes: WAV格式的音频数据
bytes: WAV format audio data
"""
decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道
decoder = opuslib_next.Decoder(16000, 1) # 16kHz, mono
pcm_data = []
for opus_packet in opus_data:
@ -64,16 +64,16 @@ def opus_to_wav(conn, opus_data):
pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms
pcm_data.append(pcm_frame)
except opuslib_next.OpusError as e:
conn.logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True)
conn.logger.bind(tag=TAG).error(f"Opus decoding error: {e}", exc_info=True)
if not pcm_data:
raise ValueError("没有有效的PCM数据")
raise ValueError("No valid PCM data")
# 创建WAV文件头
# Create WAV file header
pcm_data_bytes = b"".join(pcm_data)
num_samples = len(pcm_data_bytes) // 2 # 16-bit samples
# WAV文件头
# WAV file header
wav_header = bytearray()
wav_header.extend(b"RIFF") # ChunkID
wav_header.extend((36 + len(pcm_data_bytes)).to_bytes(4, "little")) # ChunkSize
@ -89,7 +89,7 @@ def opus_to_wav(conn, opus_data):
wav_header.extend(b"data") # Subchunk2ID
wav_header.extend(len(pcm_data_bytes).to_bytes(4, "little")) # Subchunk2Size
# 返回完整的WAV数据
# Return complete WAV data
return bytes(wav_header) + pcm_data_bytes
@ -98,27 +98,27 @@ def enqueue_tts_report(conn, text, opus_data):
return
if conn.chat_history_conf == 0:
return
"""将TTS数据加入上报队列
"""Add TTS data to reporting queue
Args:
conn: 连接对象
text: 合成文本
opus_data: opus音频数据
conn: Connection object
text: Synthesized text
opus_data: Opus audio data
"""
try:
# 使用连接对象的队列,传入文本和二进制数据而非文件路径
# Use connection object's queue, pass text and binary data instead of file path
if conn.chat_history_conf == 2:
conn.report_queue.put((2, text, opus_data, int(time.time())))
conn.logger.bind(tag=TAG).debug(
f"TTS数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} "
f"TTS data added to reporting queue: {conn.device_id}, audio size: {len(opus_data)} "
)
else:
conn.report_queue.put((2, text, None, int(time.time())))
conn.logger.bind(tag=TAG).debug(
f"TTS数据已加入上报队列: {conn.device_id}, 不上报音频"
f"TTS data added to reporting queue: {conn.device_id}, no audio reporting"
)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"加入TTS上报队列失败: {text}, {e}")
conn.logger.bind(tag=TAG).error(f"Failed to add TTS to reporting queue: {text}, {e}")
def enqueue_asr_report(conn, text, opus_data):
@ -126,24 +126,24 @@ def enqueue_asr_report(conn, text, opus_data):
return
if conn.chat_history_conf == 0:
return
"""将ASR数据加入上报队列
"""Add ASR data to reporting queue
Args:
conn: 连接对象
text: 合成文本
opus_data: opus音频数据
conn: Connection object
text: Synthesized text
opus_data: Opus audio data
"""
try:
# 使用连接对象的队列,传入文本和二进制数据而非文件路径
# Use connection object's queue, pass text and binary data instead of file path
if conn.chat_history_conf == 2:
conn.report_queue.put((1, text, opus_data, int(time.time())))
conn.logger.bind(tag=TAG).debug(
f"ASR数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} "
f"ASR data added to reporting queue: {conn.device_id}, audio size: {len(opus_data)} "
)
else:
conn.report_queue.put((1, text, None, int(time.time())))
conn.logger.bind(tag=TAG).debug(
f"ASR数据已加入上报队列: {conn.device_id}, 不上报音频"
f"ASR data added to reporting queue: {conn.device_id}, no audio reporting"
)
except Exception as e:
conn.logger.bind(tag=TAG).debug(f"加入ASR上报队列失败: {text}, {e}")
conn.logger.bind(tag=TAG).debug(f"Failed to add ASR to reporting queue: {text}, {e}")

View file

@ -8,12 +8,13 @@ TAG = __name__
async def sendAudioMessage(conn, sentenceType, audios, text):
# 发送句子开始消息
conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}")
# Send sentence start message
conn.logger.bind(tag=TAG).info(
f"Send audio message: {sentenceType}, {text}")
pre_buffer = False
if conn.tts.tts_audio_first_sentence:
conn.logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
conn.logger.bind(tag=TAG).info(f"Send first audio segment: {text}")
conn.tts.tts_audio_first_sentence = False
pre_buffer = True
@ -21,7 +22,7 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
await sendAudio(conn, audios, pre_buffer)
# 发送结束消息(如果是最后一个文本)
# Send end message (if it's the last text)
if conn.llm_finish_task and sentenceType == SentenceType.LAST:
await send_tts_message(conn, "stop", None)
conn.client_is_speaking = False
@ -29,16 +30,17 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
await conn.close()
# 播放音频
# Play audio
async def sendAudio(conn, audios, pre_buffer=True):
if audios is None or len(audios) == 0:
return
# 流控参数优化
frame_duration = 60 # 帧时长(毫秒),匹配 Opus 编码
# Flow control parameter optimization
# Frame duration (milliseconds), matching Opus encoding
frame_duration = 60
start_time = time.perf_counter()
play_position = 0
# 仅当第一句话时执行预缓冲
# Execute pre-buffering only for the first sentence
if pre_buffer:
pre_buffer_frames = min(3, len(audios))
for i in range(pre_buffer_frames):
@ -47,15 +49,15 @@ async def sendAudio(conn, audios, pre_buffer=True):
else:
remaining_audios = audios
# 播放剩余音频帧
# Play remaining audio frames
for opus_packet in remaining_audios:
if conn.client_abort:
break
# 重置没有声音的状态
# Reset no-voice state
conn.last_activity_time = time.time() * 1000
# 计算预期发送时间
# Calculate expected send time
expected_time = start_time + (play_position / 1000)
current_time = time.perf_counter()
delay = expected_time - current_time
@ -68,14 +70,14 @@ async def sendAudio(conn, audios, pre_buffer=True):
async def send_tts_message(conn, state, text=None):
"""发送 TTS 状态消息"""
"""Send TTS status message"""
message = {"type": "tts", "state": state, "session_id": conn.session_id}
if text is not None:
message["text"] = textUtils.check_emoji(text)
# TTS播放结束
# TTS playback ended
if state == "stop":
# 播放提示音
# Play notification sound
tts_notify = conn.config.get("enable_stop_tts_notify", False)
if tts_notify:
stop_tts_notify_voice = conn.config.get(
@ -83,10 +85,10 @@ async def send_tts_message(conn, state, text=None):
)
audios, _ = conn.tts.audio_to_opus_data(stop_tts_notify_voice)
await sendAudio(conn, audios)
# 清除服务端讲话状态
# Clear server speaking status
conn.clearSpeakStatus()
# 发送消息到客户端
# Send message to client
await conn.websocket.send(json.dumps(message))
@ -96,26 +98,27 @@ async def send_stt_message(conn, text):
await send_tts_message(conn, "start")
return
"""发送 STT 状态消息"""
# 解析JSON格式,提取实际的用户说话内容
"""Send STT status message"""
# Parse JSON format, extract actual user speech content
display_text = text
try:
# 尝试解析JSON格式
# Try to parse JSON format
if text.strip().startswith('{') and text.strip().endswith('}'):
parsed_data = json.loads(text)
if isinstance(parsed_data, dict) and "content" in parsed_data:
# 如果是包含说话人信息的JSON格式,只显示content部分
# If it's JSON format containing speaker information, only display the content part
display_text = parsed_data["content"]
# 保存说话人信息到conn对象
# Save speaker information to conn object
if "speaker" in parsed_data:
conn.current_speaker = parsed_data["speaker"]
except (json.JSONDecodeError, TypeError):
# 如果不是JSON格式,直接使用原始文本
# If it's not JSON format, use original text directly
display_text = text
stt_text = textUtils.get_string_no_punctuation_or_emoji(display_text)
await conn.websocket.send(
json.dumps({"type": "stt", "text": stt_text, "session_id": conn.session_id})
json.dumps({"type": "stt", "text": stt_text,
"session_id": conn.session_id})
)
conn.client_is_speaking = True
await send_tts_message(conn, "start")
await send_tts_message(conn, "start")

View file

@ -14,25 +14,28 @@ TAG = __name__
async def handleTextMessage(conn, message):
"""处理文本消息"""
"""Handle text messages"""
try:
msg_json = json.loads(message)
if isinstance(msg_json, int):
conn.logger.bind(tag=TAG).info(f"收到文本消息:{message}")
conn.logger.bind(tag=TAG).info(f"Received text message: {message}")
await conn.websocket.send(message)
return
if msg_json["type"] == "hello":
conn.logger.bind(tag=TAG).info(f"收到hello消息:{message}")
conn.logger.bind(tag=TAG).info(
f"Received hello message: {message}")
await handleHelloMessage(conn, msg_json)
elif msg_json["type"] == "abort":
conn.logger.bind(tag=TAG).info(f"收到abort消息:{message}")
conn.logger.bind(tag=TAG).info(
f"Received abort message: {message}")
await handleAbortMessage(conn)
elif msg_json["type"] == "listen":
conn.logger.bind(tag=TAG).info(f"收到listen消息:{message}")
conn.logger.bind(tag=TAG).info(
f"Received listen message: {message}")
if "mode" in msg_json:
conn.client_listen_mode = msg_json["mode"]
conn.logger.bind(tag=TAG).debug(
f"客户端拾音模式:{conn.client_listen_mode}"
f"Client audio capture mode: {conn.client_listen_mode}"
)
if msg_json["state"] == "start":
conn.client_have_voice = True
@ -47,77 +50,81 @@ async def handleTextMessage(conn, message):
conn.asr_audio.clear()
if "text" in msg_json:
conn.last_activity_time = time.time() * 1000
original_text = msg_json["text"] # 保留原始文本
original_text = msg_json["text"] # Preserve original text
filtered_len, filtered_text = remove_punctuation_and_length(
original_text
)
# 识别是否是唤醒词
is_wakeup_words = filtered_text in conn.config.get("wakeup_words")
# 是否开启唤醒词回复
# Identify if it's a wake-up word
is_wakeup_words = filtered_text in conn.config.get(
"wakeup_words")
# Whether wake-up word reply is enabled
enable_greeting = conn.config.get("enable_greeting", True)
if is_wakeup_words and not enable_greeting:
# 如果是唤醒词,且关闭了唤醒词回复,就不用回答
# If it's a wake-up word and wake-up word reply is disabled, no need to respond
await send_stt_message(conn, original_text)
await send_tts_message(conn, "stop", None)
conn.client_is_speaking = False
elif is_wakeup_words:
conn.just_woken_up = True
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
enqueue_asr_report(conn, "嘿,你好呀", [])
await startToChat(conn, "嘿,你好呀")
# Report plain text data (reuse ASR reporting function, but provide no audio data)
enqueue_asr_report(conn, "Hey, hello there", [])
await startToChat(conn, "Hey, hello there")
else:
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
# Report plain text data (reuse ASR reporting function, but provide no audio data)
enqueue_asr_report(conn, original_text, [])
# 否则需要LLM对文字内容进行答复
# Otherwise, need LLM to respond to text content
await startToChat(conn, original_text)
elif msg_json["type"] == "iot":
conn.logger.bind(tag=TAG).info(f"收到iot消息:{message}")
conn.logger.bind(tag=TAG).info(f"Received iot message: {message}")
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:
asyncio.create_task(handleIotStatus(conn, msg_json["states"]))
elif msg_json["type"] == "mcp":
conn.logger.bind(tag=TAG).info(f"收到mcp消息:{message[:100]}")
conn.logger.bind(tag=TAG).info(
f"Received mcp message: {message[:100]}")
if "payload" in msg_json:
asyncio.create_task(
handle_mcp_message(conn, conn.mcp_client, msg_json["payload"])
handle_mcp_message(conn, conn.mcp_client,
msg_json["payload"])
)
elif msg_json["type"] == "server":
# 记录日志时过滤敏感信息
# Filter sensitive information when logging
conn.logger.bind(tag=TAG).info(
f"收到服务器消息:{filter_sensitive_info(msg_json)}"
f"Received server message: {filter_sensitive_info(msg_json)}"
)
# 如果配置是从API读取的,则需要验证secret
# If configuration is read from API, need to verify secret
if not conn.read_config_from_api:
return
# 获取post请求的secret
# Get secret from post request
post_secret = msg_json.get("content", {}).get("secret", "")
secret = conn.config["manager-api"].get("secret", "")
# 如果secret不匹配,则返回
# If secret doesn't match, return
if post_secret != secret:
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
"message": "服务器密钥验证失败",
"message": "Server secret verification failed",
}
)
)
return
# 动态更新配置
# Dynamically update configuration
if msg_json["action"] == "update_config":
try:
# 更新WebSocketServer的配置
# Update WebSocketServer configuration
if not conn.server:
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
"message": "无法获取服务器实例",
"message": "Cannot get server instance",
"content": {"action": "update_config"},
}
)
@ -130,40 +137,42 @@ async def handleTextMessage(conn, message):
{
"type": "server",
"status": "error",
"message": "更新服务器配置失败",
"message": "Failed to update server configuration",
"content": {"action": "update_config"},
}
)
)
return
# 发送成功响应
# Send success response
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "success",
"message": "配置更新成功",
"message": "Configuration updated successfully",
"content": {"action": "update_config"},
}
)
)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"更新配置失败: {str(e)}")
conn.logger.bind(tag=TAG).error(
f"Failed to update configuration: {str(e)}")
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
"message": f"更新配置失败: {str(e)}",
"message": f"Failed to update configuration: {str(e)}",
"content": {"action": "update_config"},
}
)
)
# 重启服务器
# Restart server
elif msg_json["action"] == "restart":
await conn.handle_restart(msg_json)
else:
conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}")
conn.logger.bind(tag=TAG).error(
f"Received unknown type message: {message}")
except json.JSONDecodeError:
await conn.websocket.send(message)
await conn.websocket.send(message)

View file

@ -15,19 +15,18 @@ class SimpleHttpServer:
self.vision_handler = VisionHandler(config)
def _get_websocket_url(self, local_ip: str, port: int) -> str:
"""获取websocket地址
"""Get websocket address
Args:
local_ip: 本地IP地址
port: 端口号
local_ip: Local IP address
port: Port number
Returns:
str: websocket地址
str: websocket address
"""
server_config = self.config["server"]
websocket_config = server_config.get("websocket")
if websocket_config and "你" not in websocket_config:
if websocket_config and "you" not in websocket_config:
return websocket_config
else:
return f"ws://{local_ip}:{port}/xiaozhi/v1/"
@ -39,43 +38,52 @@ class SimpleHttpServer:
if port:
try:
self.logger.bind(tag=TAG).info(f"Starting HTTP server on {host}:{port}")
self.logger.bind(tag=TAG).info(
f"Starting HTTP server on {host}:{port}")
app = web.Application()
read_config_from_api = server_config.get("read_config_from_api", False)
self.logger.bind(tag=TAG).info(f"read_config_from_api: {read_config_from_api}")
read_config_from_api = server_config.get(
"read_config_from_api", False)
self.logger.bind(tag=TAG).info(
f"read_config_from_api: {read_config_from_api}")
if not read_config_from_api:
# 如果没有开启智控台,只是单模块运行,就需要再添加简单OTA接口,用于下发websocket接口
# If smart control panel is not enabled, just running single module, need to add simple OTA interface for delivering websocket interface
self.logger.bind(tag=TAG).info("Adding OTA routes")
app.add_routes(
[
web.get("/xiaozhi/ota/", self.ota_handler.handle_get),
web.post("/xiaozhi/ota/", self.ota_handler.handle_post),
web.options("/xiaozhi/ota/", self.ota_handler.handle_post),
]
)
# 添加路由
self.logger.bind(tag=TAG).info("Adding vision routes")
app.add_routes(
[
web.get("/mcp/vision/explain", self.vision_handler.handle_get),
web.post("/mcp/vision/explain", self.vision_handler.handle_post),
web.options("/mcp/vision/explain", self.vision_handler.handle_post),
]
)
app.add_routes([
web.get("/xiaozhi/ota/", self.ota_handler.handle_get),
web.post("/xiaozhi/ota/",
self.ota_handler.handle_post),
web.options("/xiaozhi/ota/",
self.ota_handler.handle_post),
])
# 运行服务
# Add routes
self.logger.bind(tag=TAG).info("Adding vision routes")
app.add_routes([
web.get("/mcp/vision/explain",
self.vision_handler.handle_get),
web.post("/mcp/vision/explain",
self.vision_handler.handle_post),
web.options("/mcp/vision/explain",
self.vision_handler.handle_post),
])
# Run service
self.logger.bind(tag=TAG).info("Setting up HTTP server runner")
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, host, port)
await site.start()
self.logger.bind(tag=TAG).info(f"HTTP server started successfully on {host}:{port}")
# 保持服务运行
self.logger.bind(tag=TAG).info(
f"HTTP server started successfully on {host}:{port}")
# Keep service running
while True:
await asyncio.sleep(3600) # 每隔 1 小时检查一次
await asyncio.sleep(3600) # Check every hour
except Exception as e:
self.logger.bind(tag=TAG).error(f"Failed to start HTTP server: {e}")
self.logger.bind(tag=TAG).error(
f"Failed to start HTTP server: {e}")
raise

View file

@ -1,15 +1,16 @@
import http.client
import json
import asyncio
from typing import Optional, Tuple, List
import os
import time
import uuid
import hmac
import hashlib
import base64
import hashlib
import asyncio
import requests
import websockets
import opuslib_next
import random
from typing import Optional, Tuple, List
from urllib import parse
import time
from datetime import datetime
from config.logger import setup_logging
from core.providers.asr.base import ASRProviderBase
@ -18,20 +19,19 @@ from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
class AccessToken:
@staticmethod
def _encode_text(text):
encoded_text = parse.quote_plus(text)
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
@staticmethod
def _encode_dict(dic):
keys = dic.keys()
dic_sorted = [(key, dic[key]) for key in sorted(keys)]
encoded_text = parse.urlencode(dic_sorted)
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
@staticmethod
def create_token(access_key_id, access_key_secret):
parameters = {
@ -45,204 +45,301 @@ class AccessToken:
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"Version": "2019-02-28",
}
# 构造规范化的请求字符串
query_string = AccessToken._encode_dict(parameters)
# print('规范化的请求字符串: %s' % query_string)
# 构造待签名字符串
string_to_sign = (
"GET"
+ "&"
+ AccessToken._encode_text("/")
+ "&"
+ AccessToken._encode_text(query_string)
"GET" + "&" + AccessToken._encode_text("/") + "&" + AccessToken._encode_text(query_string)
)
# print('待签名的字符串: %s' % string_to_sign)
# 计算签名
secreted_string = hmac.new(
bytes(access_key_secret + "&", encoding="utf-8"),
bytes(string_to_sign, encoding="utf-8"),
hashlib.sha1,
).digest()
signature = base64.b64encode(secreted_string)
# print('签名: %s' % signature)
# 进行URL编码
signature = AccessToken._encode_text(signature)
# print('URL编码后的签名: %s' % signature)
# 调用服务
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
signature,
query_string,
)
# print('url: %s' % full_url)
# 提交HTTP GET请求
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (signature, query_string)
response = requests.get(full_url)
if response.ok:
root_obj = response.json()
key = "Token"
if key in root_obj:
token = root_obj[key]["Id"]
expire_time = root_obj[key]["ExpireTime"]
return token, expire_time
# print(response.text)
if "Token" in root_obj:
return root_obj["Token"]["Id"], root_obj["Token"]["ExpireTime"]
return None, None
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
def __init__(self, config, delete_audio_file):
super().__init__()
self.interface_type = InterfaceType.NON_STREAM
"""阿里云ASR初始化"""
# 新增空值判断逻辑
self.interface_type = InterfaceType.STREAM
self.config = config
self.text = ""
self.decoder = opuslib_next.Decoder(16000, 1)
self.asr_ws = None
self.forward_task = None
self.is_processing = False
self.server_ready = False # Server ready status
# Basic configuration
self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret")
self.app_key = config.get("appkey")
self.host = "nls-gateway-cn-shanghai.aliyuncs.com"
self.base_url = f"https://{self.host}/stream/v1/asr"
self.sample_rate = 16000
self.format = "wav"
self.appkey = config.get("appkey")
self.token = config.get("token")
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
# If configured as internal address (containing -internal.aliyuncs.com), use ws protocol, default is wss protocol
if "-internal." in self.host:
self.ws_url = f"ws://{self.host}/ws/v1"
else:
# Default use wss protocol
self.ws_url = f"wss://{self.host}/ws/v1"
self.max_sentence_silence = config.get("max_sentence_silence")
self.output_dir = config.get("output_dir", "./audio_output")
self.delete_audio_file = delete_audio_file
self.expire_time = None
# Token management
if self.access_key_id and self.access_key_secret:
# 使用密钥对生成临时token
self._refresh_token()
else:
# 直接使用预生成的长期token
self.token = config.get("token")
self.expire_time = None
# 确保输出目录存在
os.makedirs(self.output_dir, exist_ok=True)
elif not self.token:
raise ValueError("Must provide access_key_id+access_key_secret or directly provide token")
def _refresh_token(self):
"""刷新Token并记录过期时间"""
if self.access_key_id and self.access_key_secret:
self.token, expire_time_str = AccessToken.create_token(
self.access_key_id, self.access_key_secret
)
if not expire_time_str:
raise ValueError("无法获取有效的Token过期时间")
try:
# 统一转换为字符串处理
expire_str = str(expire_time_str).strip()
if expire_str.isdigit():
expire_time = datetime.fromtimestamp(int(expire_str))
else:
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
self.expire_time = expire_time.timestamp() - 60
except Exception as e:
raise ValueError(f"无效的过期时间格式: {expire_str}") from e
else:
self.expire_time = None
"""Refresh Token"""
self.token, expire_time_str = AccessToken.create_token(self.access_key_id, self.access_key_secret)
if not self.token:
raise ValueError("无法获取有效的访问Token")
raise ValueError("Unable to get valid access Token")
try:
expire_str = str(expire_time_str).strip()
if expire_str.isdigit():
expire_time = datetime.fromtimestamp(int(expire_str))
else:
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
self.expire_time = expire_time.timestamp() - 60
except:
self.expire_time = None
def _is_token_expired(self):
"""检查Token是否过期"""
if not self.expire_time:
return False # 长期Token不过期
# 新增调试日志
# current_time = time.time()
# remaining = self.expire_time - current_time
# print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | "
# f"过期时间 {datetime.fromtimestamp(self.expire_time)} | "
# f"剩余 {remaining:.2f}秒")
return time.time() > self.expire_time
def _construct_request_url(self) -> str:
"""构造请求URL,包含参数"""
request = f"{self.base_url}?appkey={self.app_key}"
request += f"&format={self.format}"
request += f"&sample_rate={self.sample_rate}"
request += "&enable_punctuation_prediction=true"
request += "&enable_inverse_text_normalization=true"
request += "&enable_voice_detection=false"
return request
async def _send_request(self, pcm_data: bytes) -> Optional[str]:
"""发送请求到阿里云ASR服务"""
try:
# 设置HTTP头
headers = {
"X-NLS-Token": self.token,
"Content-type": "application/octet-stream",
"Content-Length": str(len(pcm_data)),
}
# 创建连接并发送请求
conn = http.client.HTTPSConnection(self.host)
request_url = self._construct_request_url()
loop = asyncio.get_event_loop()
await loop.run_in_executor(
None,
lambda: conn.request(
method="POST", url=request_url, body=pcm_data, headers=headers
),
)
# 获取响应
response = await loop.run_in_executor(None, conn.getresponse)
body = await loop.run_in_executor(None, response.read)
conn.close()
# 解析响应
"""Check if Token has expired"""
return self.expire_time and time.time() > self.expire_time
async def open_audio_channels(self, conn):
await super().open_audio_channels(conn)
async def receive_audio(self, conn, audio, audio_have_voice):
# Initialize audio cache
if not hasattr(conn, 'asr_audio_for_voiceprint'):
conn.asr_audio_for_voiceprint = []
# Store audio data
if audio:
conn.asr_audio_for_voiceprint.append(audio)
conn.asr_audio.append(audio)
conn.asr_audio = conn.asr_audio[-10:]
# Only establish connection when there is voice and no connection exists
if audio_have_voice and not self.is_processing:
try:
body_json = json.loads(body)
status = body_json.get("status")
if status == 20000000:
result = body_json.get("result", "")
logger.bind(tag=TAG).debug(f"ASR结果: {result}")
return result
else:
logger.bind(tag=TAG).error(f"ASR失败,状态码: {status}")
return None
except ValueError:
logger.bind(tag=TAG).error("响应不是JSON格式")
return None
except Exception as e:
logger.bind(tag=TAG).error(f"ASR请求失败: {e}", exc_info=True)
return None
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
await self._start_recognition(conn)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to start recognition: {str(e)}")
await self._cleanup(conn)
return
if self.asr_ws and self.is_processing and self.server_ready:
try:
pcm_frame = self.decoder.decode(audio, 960)
await self.asr_ws.send(pcm_frame)
except Exception as e:
logger.bind(tag=TAG).warning(f"Failed to send audio: {str(e)}")
await self._cleanup(conn)
async def _start_recognition(self, conn):
"""Start recognition session"""
if self._is_token_expired():
logger.warning("Token已过期,正在自动刷新...")
self._refresh_token()
file_path = None
# Establish connection
headers = {"X-NLS-Token": self.token}
self.asr_ws = await websockets.connect(
self.ws_url,
additional_headers=headers,
max_size=1000000000,
ping_interval=None,
ping_timeout=None,
close_timeout=5,
)
self.is_processing = True
self.server_ready = False # Reset server ready status
self.forward_task = asyncio.create_task(self._forward_results(conn))
# Send start request
start_request = {
"header": {
"namespace": "SpeechTranscriber",
"name": "StartTranscription",
"status": 20000000,
"message_id": ''.join(random.choices('0123456789abcdef', k=32)),
"task_id": ''.join(random.choices('0123456789abcdef', k=32)),
"status_text": "Gateway:SUCCESS:Success.",
"appkey": self.appkey
},
"payload": {
"format": "pcm",
"sample_rate": 16000,
"enable_intermediate_result": True,
"enable_punctuation_prediction": True,
"enable_inverse_text_normalization": True,
"max_sentence_silence": self.max_sentence_silence,
"enable_voice_detection": False,
}
}
await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False))
logger.bind(tag=TAG).info("Start request sent, waiting for server ready...")
async def _forward_results(self, conn):
"""Forward recognition results"""
try:
# 解码Opus为PCM
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件
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)
if text:
return text, file_path
return "", file_path
while self.asr_ws and not conn.stop_event.is_set():
try:
response = await asyncio.wait_for(self.asr_ws.recv(), timeout=1.0)
result = json.loads(response)
header = result.get("header", {})
payload = result.get("payload", {})
message_name = header.get("name", "")
status = header.get("status", 0)
if status != 20000000:
if status in [40000004, 40010004]: # Connection timeout or client disconnect
logger.bind(tag=TAG).warning(f"Connection issue, status code: {status}")
break
elif status in [40270002, 40270003]: # Audio issue
logger.bind(tag=TAG).warning(f"Audio processing issue, status code: {status}")
continue
else:
logger.bind(tag=TAG).error(f"Recognition error, status code: {status}, message: {header.get('status_text', '')}")
continue
# Receiving TranscriptionStarted means server is ready to receive audio data
if message_name == "TranscriptionStarted":
self.server_ready = True
logger.bind(tag=TAG).info("Server ready, starting to send cached audio...")
# Send cached audio
if conn.asr_audio:
for cached_audio in conn.asr_audio[-10:]:
try:
pcm_frame = self.decoder.decode(cached_audio, 960)
await self.asr_ws.send(pcm_frame)
except Exception as e:
logger.bind(tag=TAG).warning(f"Failed to send cached audio: {e}")
break
continue
if message_name == "TranscriptionResultChanged":
# Intermediate result
text = payload.get("result", "")
if text:
self.text = text
elif message_name == "SentenceEnd":
# Final result
text = payload.get("result", "")
if text:
self.text = text
conn.reset_vad_states()
# Pass cached audio data
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
await self.handle_voice_stop(conn, audio_data)
# Clear cache
conn.asr_audio_for_voiceprint = []
break
elif message_name == "TranscriptionCompleted":
# Recognition completed
self.is_processing = False
break
except asyncio.TimeoutError:
continue
except websockets.exceptions.ConnectionClosed:
break
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to process result: {str(e)}")
break
except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
return "", file_path
logger.bind(tag=TAG).error(f"Result forwarding failed: {str(e)}")
finally:
await self._cleanup(conn)
async def _cleanup(self, conn):
"""Clean up resources"""
logger.bind(tag=TAG).info(f"Starting ASR session cleanup | Current status: processing={self.is_processing}, server_ready={self.server_ready}")
# Clear connection audio cache
if conn and hasattr(conn, 'asr_audio_for_voiceprint'):
conn.asr_audio_for_voiceprint = []
# Determine if stop request needs to be sent
should_stop = self.is_processing or self.server_ready
# Send stop recognition request
if self.asr_ws and should_stop:
try:
stop_msg = {
"header": {
"namespace": "SpeechTranscriber",
"name": "StopTranscription",
"status": 20000000,
"message_id": ''.join(random.choices('0123456789abcdef', k=32)),
"status_text": "Client:Stop",
"appkey": self.appkey
}
}
logger.bind(tag=TAG).info("Sending ASR termination request")
await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False))
await asyncio.sleep(0.1)
logger.bind(tag=TAG).info("ASR termination request sent")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to send ASR termination request: {e}")
# Status reset (after termination request is sent)
self.is_processing = False
self.server_ready = False
logger.bind(tag=TAG).info("ASR status reset")
# Clean up task
if self.forward_task and not self.forward_task.done():
self.forward_task.cancel()
try:
await asyncio.wait_for(self.forward_task, timeout=1.0)
except Exception as e:
logger.bind(tag=TAG).debug(f"forward_task cancel exception: {e}")
finally:
self.forward_task = None
# Close connection
if self.asr_ws:
try:
logger.bind(tag=TAG).debug("Closing WebSocket connection")
await asyncio.wait_for(self.asr_ws.close(), timeout=2.0)
logger.bind(tag=TAG).debug("WebSocket connection closed")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to close WebSocket connection: {e}")
finally:
self.asr_ws = None
logger.bind(tag=TAG).info("ASR session cleanup completed")
async def speech_to_text(self, opus_data, session_id, audio_format):
"""Get recognition result"""
result = self.text
self.text = ""
return result, None
async def close(self):
"""Close resources"""
await self._cleanup()

View file

@ -48,7 +48,9 @@ class AccessToken:
}
query_string = AccessToken._encode_dict(parameters)
string_to_sign = (
"GET" + "&" + AccessToken._encode_text("/") + "&" + AccessToken._encode_text(query_string)
"GET" + "&" +
AccessToken._encode_text("/") + "&" +
AccessToken._encode_text(query_string)
)
secreted_string = hmac.new(
bytes(access_key_secret + "&", encoding="utf-8"),
@ -57,7 +59,8 @@ class AccessToken:
).digest()
signature = base64.b64encode(secreted_string)
signature = AccessToken._encode_text(signature)
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (signature, query_string)
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
signature, query_string)
response = requests.get(full_url)
if response.ok:
root_obj = response.json()
@ -76,19 +79,19 @@ class ASRProvider(ASRProviderBase):
self.asr_ws = None
self.forward_task = None
self.is_processing = False
self.server_ready = False # 服务器准备状态
self.server_ready = False # Server ready status
# 基础配置
# Basic configuration
self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret")
self.appkey = config.get("appkey")
self.token = config.get("token")
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
# 如果配置的是内网地址(包含-internal.aliyuncs.com),则使用ws协议,默认是wss协议
# If configured with internal address (contains -internal.aliyuncs.com), use ws protocol, default is wss protocol
if "-internal." in self.host:
self.ws_url = f"ws://{self.host}/ws/v1"
else:
# 默认使用wss协议
# Default to wss protocol
self.ws_url = f"wss://{self.host}/ws/v1"
self.max_sentence_silence = config.get("max_sentence_silence")
@ -96,53 +99,57 @@ class ASRProvider(ASRProviderBase):
self.delete_audio_file = delete_audio_file
self.expire_time = None
# Token管理
# Token management
if self.access_key_id and self.access_key_secret:
self._refresh_token()
elif not self.token:
raise ValueError("必须提供access_key_id+access_key_secret或者直接提供token")
raise ValueError(
"Must provide access_key_id+access_key_secret or provide token directly")
def _refresh_token(self):
"""刷新Token"""
self.token, expire_time_str = AccessToken.create_token(self.access_key_id, self.access_key_secret)
"""Refresh Token"""
self.token, expire_time_str = AccessToken.create_token(
self.access_key_id, self.access_key_secret)
if not self.token:
raise ValueError("无法获取有效的访问Token")
raise ValueError("Unable to obtain valid access Token")
try:
expire_str = str(expire_time_str).strip()
if expire_str.isdigit():
expire_time = datetime.fromtimestamp(int(expire_str))
else:
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
expire_time = datetime.strptime(
expire_str, "%Y-%m-%dT%H:%M:%SZ")
self.expire_time = expire_time.timestamp() - 60
except:
self.expire_time = None
def _is_token_expired(self):
"""检查Token是否过期"""
"""Check if Token is expired"""
return self.expire_time and time.time() > self.expire_time
async def open_audio_channels(self, conn):
await super().open_audio_channels(conn)
async def receive_audio(self, conn, audio, audio_have_voice):
# 初始化音频缓存
# Initialize audio cache
if not hasattr(conn, 'asr_audio_for_voiceprint'):
conn.asr_audio_for_voiceprint = []
# 存储音频数据
# Store audio data
if audio:
conn.asr_audio_for_voiceprint.append(audio)
conn.asr_audio.append(audio)
conn.asr_audio = conn.asr_audio[-10:]
# 只在有声音且没有连接时建立连接
# Only establish connection when there is voice and no existing connection
if audio_have_voice and not self.is_processing:
try:
await self._start_recognition(conn)
except Exception as e:
logger.bind(tag=TAG).error(f"开始识别失败: {str(e)}")
logger.bind(tag=TAG).error(
f"Failed to start recognition: {str(e)}")
await self._cleanup(conn)
return
@ -151,15 +158,15 @@ class ASRProvider(ASRProviderBase):
pcm_frame = self.decoder.decode(audio, 960)
await self.asr_ws.send(pcm_frame)
except Exception as e:
logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}")
logger.bind(tag=TAG).warning(f"Failed to send audio: {str(e)}")
await self._cleanup(conn)
async def _start_recognition(self, conn):
"""开始识别会话"""
"""Start recognition session"""
if self._is_token_expired():
self._refresh_token()
# 建立连接
# Establish connection
headers = {"X-NLS-Token": self.token}
self.asr_ws = await websockets.connect(
self.ws_url,
@ -169,12 +176,12 @@ class ASRProvider(ASRProviderBase):
ping_timeout=None,
close_timeout=5,
)
self.is_processing = True
self.server_ready = False # 重置服务器准备状态
self.server_ready = False # Reset server ready status
self.forward_task = asyncio.create_task(self._forward_results(conn))
# 发送开始请求
# Send start request
start_request = {
"header": {
"namespace": "SpeechTranscriber",
@ -196,95 +203,106 @@ class ASRProvider(ASRProviderBase):
}
}
await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False))
logger.bind(tag=TAG).info("已发送开始请求,等待服务器准备...")
logger.bind(tag=TAG).info(
"Start request sent, waiting for server to be ready...")
async def _forward_results(self, conn):
"""转发识别结果"""
"""Forward recognition results"""
try:
while self.asr_ws and not conn.stop_event.is_set():
try:
response = await asyncio.wait_for(self.asr_ws.recv(), timeout=1.0)
result = json.loads(response)
header = result.get("header", {})
payload = result.get("payload", {})
message_name = header.get("name", "")
status = header.get("status", 0)
if status != 20000000:
if status in [40000004, 40010004]: # 连接超时或客户端断开
logger.bind(tag=TAG).warning(f"连接问题,状态码: {status}")
# Connection timeout or client disconnect
if status in [40000004, 40010004]:
logger.bind(tag=TAG).warning(
f"Connection issue, status code: {status}")
break
elif status in [40270002, 40270003]: # 音频问题
logger.bind(tag=TAG).warning(f"音频处理问题,状态码: {status}")
elif status in [40270002, 40270003]: # Audio issues
logger.bind(tag=TAG).warning(
f"Audio processing issue, status code: {status}")
continue
else:
logger.bind(tag=TAG).error(f"识别错误,状态码: {status}, 消息: {header.get('status_text', '')}")
logger.bind(tag=TAG).error(
f"Recognition error, status code: {status}, message: {header.get('status_text', '')}")
continue
# 收到TranscriptionStarted表示服务器准备好接收音频数据
# TranscriptionStarted indicates server is ready to receive audio data
if message_name == "TranscriptionStarted":
self.server_ready = True
logger.bind(tag=TAG).info("服务器已准备,开始发送缓存音频...")
# 发送缓存音频
logger.bind(tag=TAG).info(
"Server is ready, starting to send cached audio...")
# Send cached audio
if conn.asr_audio:
for cached_audio in conn.asr_audio[-10:]:
try:
pcm_frame = self.decoder.decode(cached_audio, 960)
pcm_frame = self.decoder.decode(
cached_audio, 960)
await self.asr_ws.send(pcm_frame)
except Exception as e:
logger.bind(tag=TAG).warning(f"发送缓存音频失败: {e}")
logger.bind(tag=TAG).warning(
f"Failed to send cached audio: {e}")
break
continue
if message_name == "TranscriptionResultChanged":
# 中间结果
# Intermediate result
text = payload.get("result", "")
if text:
self.text = text
elif message_name == "SentenceEnd":
# 最终结果
# Final result
text = payload.get("result", "")
if text:
self.text = text
conn.reset_vad_states()
# 传递缓存的音频数据
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
# Pass cached audio data
audio_data = getattr(
conn, 'asr_audio_for_voiceprint', [])
await self.handle_voice_stop(conn, audio_data)
# 清空缓存
# Clear cache
conn.asr_audio_for_voiceprint = []
break
elif message_name == "TranscriptionCompleted":
# 识别完成
# Recognition completed
self.is_processing = False
break
except asyncio.TimeoutError:
continue
except websockets.exceptions.ConnectionClosed:
break
except Exception as e:
logger.bind(tag=TAG).error(f"处理结果失败: {str(e)}")
logger.bind(tag=TAG).error(
f"Failed to process result: {str(e)}")
break
except Exception as e:
logger.bind(tag=TAG).error(f"结果转发失败: {str(e)}")
logger.bind(tag=TAG).error(f"Result forwarding failed: {str(e)}")
finally:
await self._cleanup(conn)
async def _cleanup(self, conn):
"""清理资源"""
logger.bind(tag=TAG).info(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}")
# 清理连接的音频缓存
"""Clean up resources"""
logger.bind(tag=TAG).info(
f"Starting ASR session cleanup | Current status: processing={self.is_processing}, server_ready={self.server_ready}")
# Clean up connection's audio cache
if conn and hasattr(conn, 'asr_audio_for_voiceprint'):
conn.asr_audio_for_voiceprint = []
# 判断是否需要发送终止请求
# Determine if stop request needs to be sent
should_stop = self.is_processing or self.server_ready
# 发送停止识别请求
# Send stop recognition request
if self.asr_ws and should_stop:
try:
stop_msg = {
@ -297,47 +315,50 @@ class ASRProvider(ASRProviderBase):
"appkey": self.appkey
}
}
logger.bind(tag=TAG).info("正在发送ASR终止请求")
logger.bind(tag=TAG).info("Sending ASR termination request")
await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False))
await asyncio.sleep(0.1)
logger.bind(tag=TAG).info("ASR终止请求已发送")
logger.bind(tag=TAG).info("ASR termination request sent")
except Exception as e:
logger.bind(tag=TAG).error(f"ASR终止请求发送失败: {e}")
# 状态重置(在终止请求发送后)
logger.bind(tag=TAG).error(
f"ASR termination request failed to send: {e}")
# Status reset (after termination request is sent)
self.is_processing = False
self.server_ready = False
logger.bind(tag=TAG).info("ASR状态已重置")
logger.bind(tag=TAG).info("ASR status has been reset")
# 清理任务
# Clean up tasks
if self.forward_task and not self.forward_task.done():
self.forward_task.cancel()
try:
await asyncio.wait_for(self.forward_task, timeout=1.0)
except Exception as e:
logger.bind(tag=TAG).debug(f"forward_task取消异常: {e}")
logger.bind(tag=TAG).debug(
f"forward_task cancellation exception: {e}")
finally:
self.forward_task = None
# 关闭连接
# Close connection
if self.asr_ws:
try:
logger.bind(tag=TAG).debug("正在关闭WebSocket连接")
logger.bind(tag=TAG).debug("Closing WebSocket connection")
await asyncio.wait_for(self.asr_ws.close(), timeout=2.0)
logger.bind(tag=TAG).debug("WebSocket连接已关闭")
logger.bind(tag=TAG).debug("WebSocket connection closed")
except Exception as e:
logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}")
logger.bind(tag=TAG).error(
f"Failed to close WebSocket connection: {e}")
finally:
self.asr_ws = None
logger.bind(tag=TAG).info("ASR会话清理完成")
logger.bind(tag=TAG).info("ASR session cleanup completed")
async def speech_to_text(self, opus_data, session_id, audio_format):
"""获取识别结果"""
"""Get recognition result"""
result = self.text
self.text = ""
return result, None
async def close(self):
"""关闭资源"""
await self._cleanup()
"""Close resources"""
await self._cleanup()

View file

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

View file

@ -26,14 +26,14 @@ class ASRProviderBase(ABC):
def __init__(self):
pass
# 打开音频通道
# Open audio channels
async def open_audio_channels(self, conn):
conn.asr_priority_thread = threading.Thread(
target=self.asr_text_priority_thread, args=(conn,), daemon=True
)
conn.asr_priority_thread.start()
# 有序处理ASR音频
# Process ASR audio in order
def asr_text_priority_thread(self, conn):
while not conn.stop_event.is_set():
try:
@ -47,17 +47,17 @@ class ASRProviderBase(ABC):
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"处理ASR文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
f"Failed to process ASR text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}"
)
continue
# 接收音频
# Receive audio
async def receive_audio(self, conn, audio, audio_have_voice):
if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime":
have_voice = audio_have_voice
else:
have_voice = conn.client_have_voice
conn.asr_audio.append(audio)
if not have_voice and not conn.client_have_voice:
conn.asr_audio = conn.asr_audio[-10:]
@ -71,28 +71,28 @@ class ASRProviderBase(ABC):
if len(asr_audio_task) > 15:
await self.handle_voice_stop(conn, asr_audio_task)
# 处理语音停止
# Handle voice stop
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
"""并行处理ASR和声纹识别"""
"""Parallel processing of ASR and voiceprint recognition"""
try:
total_start_time = time.monotonic()
# 准备音频数据
# Prepare audio data
if conn.audio_format == "pcm":
pcm_data = asr_audio_task
else:
pcm_data = self.decode_opus(asr_audio_task)
combined_pcm_data = b"".join(pcm_data)
# 预先准备WAV数据
# Pre-prepare WAV data
wav_data = None
# 使用连接的声纹识别提供者
# Use connection's voiceprint provider
if conn.voiceprint_provider and combined_pcm_data:
wav_data = self._pcm_to_wav(combined_pcm_data)
# 定义ASR任务
# Define ASR task
def run_asr():
start_time = time.monotonic()
try:
@ -100,19 +100,21 @@ class ASRProviderBase(ABC):
asyncio.set_event_loop(loop)
try:
result = loop.run_until_complete(
self.speech_to_text(asr_audio_task, conn.session_id, conn.audio_format)
self.speech_to_text(
asr_audio_task, conn.session_id, conn.audio_format)
)
end_time = time.monotonic()
logger.bind(tag=TAG).info(f"ASR耗时: {end_time - start_time:.3f}s")
logger.bind(tag=TAG).info(
f"ASR time: {end_time - start_time:.3f}s")
return result
finally:
loop.close()
except Exception as e:
end_time = time.monotonic()
logger.bind(tag=TAG).error(f"ASR失败: {e}")
logger.bind(tag=TAG).error(f"ASR failed: {e}")
return ("", None)
# 定义声纹识别任务
# Define voiceprint recognition task
def run_voiceprint():
if not wav_data:
return None
@ -120,69 +122,75 @@ class ASRProviderBase(ABC):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
# 使用连接的声纹识别提供者
# Use connection's voiceprint provider
result = loop.run_until_complete(
conn.voiceprint_provider.identify_speaker(wav_data, conn.session_id)
conn.voiceprint_provider.identify_speaker(
wav_data, conn.session_id)
)
return result
finally:
loop.close()
except Exception as e:
logger.bind(tag=TAG).error(f"声纹识别失败: {e}")
logger.bind(tag=TAG).error(
f"Voiceprint recognition failed: {e}")
return None
# 使用线程池执行器并行运行
# Run in parallel using thread pool executor
parallel_start_time = time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as thread_executor:
asr_future = thread_executor.submit(run_asr)
if conn.voiceprint_provider and wav_data:
voiceprint_future = thread_executor.submit(run_voiceprint)
# 等待两个线程都完成
# Wait for both threads to complete
asr_result = asr_future.result(timeout=15)
voiceprint_result = voiceprint_future.result(timeout=15)
results = {"asr": asr_result, "voiceprint": voiceprint_result}
results = {"asr": asr_result,
"voiceprint": voiceprint_result}
else:
asr_result = asr_future.result(timeout=15)
results = {"asr": asr_result, "voiceprint": None}
# 处理结果
# Process results
raw_text, file_path = results.get("asr", ("", None))
speaker_name = results.get("voiceprint", None)
# 记录识别结果
# Log recognition results
if raw_text:
logger.bind(tag=TAG).info(f"识别文本: {raw_text}")
logger.bind(tag=TAG).info(f"Recognized text: {raw_text}")
if speaker_name:
logger.bind(tag=TAG).info(f"识别说话人: {speaker_name}")
# 性能监控
logger.bind(tag=TAG).info(
f"Identified speaker: {speaker_name}")
# Performance monitoring
total_time = time.monotonic() - total_start_time
logger.bind(tag=TAG).info(f"总处理耗时: {total_time:.3f}s")
# 检查文本长度
logger.bind(tag=TAG).info(
f"Total processing time: {total_time:.3f}s")
# Check text length
text_len, _ = remove_punctuation_and_length(raw_text)
self.stop_ws_connection()
if text_len > 0:
# 构建包含说话人信息的JSON字符串
enhanced_text = self._build_enhanced_text(raw_text, speaker_name)
# 使用自定义模块进行上报
# Build JSON string with speaker information
enhanced_text = self._build_enhanced_text(
raw_text, speaker_name)
# Use custom module for reporting
await startToChat(conn, enhanced_text)
enqueue_asr_report(conn, enhanced_text, asr_audio_task)
except Exception as e:
logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
logger.bind(tag=TAG).error(f"Failed to handle voice stop: {e}")
import traceback
logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}")
logger.bind(tag=TAG).debug(
f"Exception details: {traceback.format_exc()}")
def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str:
"""构建包含说话人信息的文本"""
"""Build text with speaker information"""
if speaker_name and speaker_name.strip():
return json.dumps({
"speaker": speaker_name,
@ -192,37 +200,38 @@ class ASRProviderBase(ABC):
return text
def _pcm_to_wav(self, pcm_data: bytes) -> bytes:
"""将PCM数据转换为WAV格式"""
"""Convert PCM data to WAV format"""
if len(pcm_data) == 0:
logger.bind(tag=TAG).warning("PCM数据为空,无法转换WAV")
logger.bind(tag=TAG).warning(
"PCM data is empty, cannot convert to WAV")
return b""
# 确保数据长度是偶数(16位音频)
# Ensure data length is even (16-bit audio)
if len(pcm_data) % 2 != 0:
pcm_data = pcm_data[:-1]
# 创建WAV文件头
# Create WAV file header
wav_buffer = io.BytesIO()
try:
with wave.open(wav_buffer, 'wb') as wav_file:
wav_file.setnchannels(1) # 单声道
wav_file.setsampwidth(2) # 16位
wav_file.setframerate(16000) # 16kHz采样率
wav_file.setnchannels(1) # Mono
wav_file.setsampwidth(2) # 16-bit
wav_file.setframerate(16000) # 16kHz sample rate
wav_file.writeframes(pcm_data)
wav_buffer.seek(0)
wav_data = wav_buffer.read()
return wav_data
except Exception as e:
logger.bind(tag=TAG).error(f"WAV转换失败: {e}")
logger.bind(tag=TAG).error(f"WAV conversion failed: {e}")
return b""
def stop_ws_connection(self):
pass
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
"""PCM数据保存为WAV文件"""
"""Save PCM data as WAV file"""
module_name = __name__.split(".")[-1]
file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
file_path = os.path.join(self.output_dir, file_name)
@ -239,33 +248,36 @@ class ASRProviderBase(ABC):
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
"""Convert speech data to text"""
pass
@staticmethod
def decode_opus(opus_data: List[bytes]) -> List[bytes]:
"""将Opus音频数据解码为PCM数据"""
"""Decode Opus audio data to PCM data"""
try:
decoder = opuslib_next.Decoder(16000, 1)
pcm_data = []
buffer_size = 960 # 每次处理960个采样点 (60ms at 16kHz)
buffer_size = 960 # Process 960 samples each time (60ms at 16kHz)
for i, opus_packet in enumerate(opus_data):
try:
if not opus_packet or len(opus_packet) == 0:
continue
pcm_frame = decoder.decode(opus_packet, buffer_size)
if pcm_frame and len(pcm_frame) > 0:
pcm_data.append(pcm_frame)
except opuslib_next.OpusError as e:
logger.bind(tag=TAG).warning(f"Opus解码错误,跳过数据包 {i}: {e}")
logger.bind(tag=TAG).warning(
f"Opus decode error, skipping packet {i}: {e}")
except Exception as e:
logger.bind(tag=TAG).error(f"音频处理错误,数据包 {i}: {e}")
logger.bind(tag=TAG).error(
f"Audio processing error, packet {i}: {e}")
return pcm_data
except Exception as e:
logger.bind(tag=TAG).error(f"音频解码过程发生错误: {e}")
return []
logger.bind(tag=TAG).error(
f"Error occurred during audio decoding: {e}")
return []

View file

@ -9,20 +9,16 @@ from typing import Optional, Tuple, List
from core.providers.asr.base import ASRProviderBase
from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
CLIENT_FULL_REQUEST = 0b0001
CLIENT_AUDIO_ONLY_REQUEST = 0b0010
NO_SEQUENCE = 0b0000
NEG_SEQUENCE = 0b0010
SERVER_FULL_RESPONSE = 0b1001
SERVER_ACK = 0b1011
SERVER_ERROR_RESPONSE = 0b1111
NO_SERIALIZATION = 0b0000
JSON = 0b0001
THRIFT = 0b0011
@ -37,9 +33,9 @@ def parse_response(res):
protocol_version(4 bits), header_size(4 bits),
message_type(4 bits), message_type_specific_flags(4 bits)
serialization_method(4 bits) message_compression(4 bits)
reserved (8bits) 保留字段
header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) )
payload 类似与http 请求体
reserved (8bits) reserved field
header_extensions extension header (size equals 8 * 4 * (header_size - 1))
payload similar to http request body
"""
protocol_version = res[0] >> 4
header_size = res[0] & 0x0F
@ -48,11 +44,13 @@ def parse_response(res):
serialization_method = res[2] >> 4
message_compression = res[2] & 0x0F
reserved = res[3]
header_extensions = res[4 : header_size * 4]
payload = res[header_size * 4 :]
header_extensions = res[4: header_size * 4]
payload = res[header_size * 4:]
result = {}
payload_msg = None
payload_size = 0
if message_type == SERVER_FULL_RESPONSE:
payload_size = int.from_bytes(payload[:4], "big", signed=True)
payload_msg = payload[4:]
@ -67,16 +65,21 @@ def parse_response(res):
result["code"] = code
payload_size = int.from_bytes(payload[4:8], "big", signed=False)
payload_msg = payload[8:]
if payload_msg is None:
return result
if message_compression == GZIP:
payload_msg = gzip.decompress(payload_msg)
if serialization_method == JSON:
payload_msg = json.loads(str(payload_msg, "utf-8"))
elif serialization_method != NO_SERIALIZATION:
payload_msg = str(payload_msg, "utf-8")
result["payload_msg"] = payload_msg
result["payload_size"] = payload_size
return result
@ -91,13 +94,12 @@ class ASRProvider(ASRProviderBase):
self.correct_table_name = config.get("correct_table_name", "")
self.output_dir = config.get("output_dir")
self.delete_audio_file = delete_audio_file
self.host = "openspeech.bytedance.com"
self.ws_url = f"wss://{self.host}/api/v2/asr"
self.success_code = 1000
self.seg_duration = 15000
# 确保输出目录存在
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
@staticmethod
@ -107,10 +109,13 @@ class ASRProvider(ASRProviderBase):
"""Generate protocol header."""
header = bytearray()
header_size = 1
header.append((0b0001 << 4) | header_size) # Protocol version
header.append((message_type << 4) | message_type_specific_flags)
header.append((0b0001 << 4) | 0b0001) # JSON serialization & GZIP compression
# JSON serialization & GZIP compression
header.append((0b0001 << 4) | 0b0001)
header.append(0x00) # reserved
return header
def _construct_request(self, reqid) -> dict:
@ -146,7 +151,8 @@ class ASRProvider(ASRProviderBase):
) -> Optional[str]:
"""Send request to Volcano ASR service."""
try:
auth_header = {"Authorization": "Bearer; {}".format(self.access_token)}
auth_header = {
"Authorization": "Bearer; {}".format(self.access_token)}
async with websockets.connect(
self.ws_url, additional_headers=auth_header
) as websocket:
@ -154,6 +160,7 @@ class ASRProvider(ASRProviderBase):
request_params = self._construct_request(str(uuid.uuid4()))
payload_bytes = str.encode(json.dumps(request_params))
payload_bytes = gzip.compress(payload_bytes)
full_client_request = self._generate_header()
full_client_request.extend(
(len(payload_bytes)).to_bytes(4, "big")
@ -165,10 +172,12 @@ class ASRProvider(ASRProviderBase):
await websocket.send(full_client_request)
res = await websocket.recv()
result = parse_response(res)
if (
"payload_msg" in result
and result["payload_msg"]["code"] != self.success_code
and result["payload_msg"]["code"] != 1013 # 忽略无有效语音的错误
# Ignore no valid voice error
and result["payload_msg"]["code"] != 1013
):
logger.bind(tag=TAG).error(f"ASR error: {result}")
return None
@ -185,34 +194,37 @@ class ASRProvider(ASRProviderBase):
audio_only_request = self._generate_header(
message_type=CLIENT_AUDIO_ONLY_REQUEST
)
payload_bytes = gzip.compress(chunk)
audio_only_request.extend(
(len(payload_bytes)).to_bytes(4, "big")
) # payload size(4 bytes)
audio_only_request.extend(payload_bytes) # payload
# Send audio data
await websocket.send(audio_only_request)
# Receive response
response = await websocket.recv()
result = parse_response(response)
# Receive response
response = await websocket.recv()
result = parse_response(response)
if (
"payload_msg" in result
and result["payload_msg"]["code"] == self.success_code
):
if len(result["payload_msg"]["result"]) > 0:
return result["payload_msg"]["result"][0]["text"]
return None
elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
# 无有效语音,返回空字符串
return ""
else:
logger.bind(tag=TAG).error(f"ASR error: {result}")
return None
if (
"payload_msg" in result
and result["payload_msg"]["code"] == self.success_code
):
if len(result["payload_msg"]["result"]) > 0:
return result["payload_msg"]["result"][0]["text"]
return None
elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
# No valid voice, return empty string
return ""
else:
logger.bind(tag=TAG).error(f"ASR error: {result}")
return None
except Exception as e:
logger.bind(tag=TAG).error(f"ASR request failed: {e}", exc_info=True)
logger.bind(tag=TAG).error(
f"ASR request failed: {e}", exc_info=True)
return None
@staticmethod
@ -226,7 +238,7 @@ class ASRProvider(ASRProviderBase):
data_len = len(data)
offset = 0
while offset + chunk_size < data_len:
yield data[offset : offset + chunk_size], False
yield data[offset: offset + chunk_size], False
offset += chunk_size
else:
yield data[offset:data_len], True
@ -234,38 +246,40 @@ class ASRProvider(ASRProviderBase):
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
"""Convert speech data to text"""
file_path = None
try:
# 合并所有opus数据包
# Merge all opus data packets
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件
# Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
file_path = self.save_audio_to_file(pcm_data, session_id)
# 直接使用PCM数据
# 计算分段大小 (单声道, 16bit, 16kHz采样率)
# Use PCM data directly
# Calculate segment size (mono, 16bit, 16kHz sample rate)
size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate
segment_size = int(size_per_sec * self.seg_duration / 1000)
# 语音识别
# Speech recognition
start_time = time.time()
text = await self._send_request(combined_pcm_data, segment_size)
if text:
logger.bind(tag=TAG).debug(
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
)
return text, file_path
return "", file_path
except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
logger.bind(tag=TAG).error(
f"Speech recognition failed: {e}", exc_info=True)
return "", file_path

View file

@ -9,20 +9,16 @@ from typing import Optional, Tuple, List
from core.providers.asr.base import ASRProviderBase
from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
CLIENT_FULL_REQUEST = 0b0001
CLIENT_AUDIO_ONLY_REQUEST = 0b0010
NO_SEQUENCE = 0b0000
NEG_SEQUENCE = 0b0010
SERVER_FULL_RESPONSE = 0b1001
SERVER_ACK = 0b1011
SERVER_ERROR_RESPONSE = 0b1111
NO_SERIALIZATION = 0b0000
JSON = 0b0001
THRIFT = 0b0011
@ -37,9 +33,9 @@ def parse_response(res):
protocol_version(4 bits), header_size(4 bits),
message_type(4 bits), message_type_specific_flags(4 bits)
serialization_method(4 bits) message_compression(4 bits)
reserved (8bits) 保留字段
header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) )
payload 类似与http 请求体
reserved (8bits) reserved field
header_extensions extension header (size equals 8 * 4 * (header_size - 1))
payload similar to http request body
"""
protocol_version = res[0] >> 4
header_size = res[0] & 0x0F
@ -48,11 +44,13 @@ def parse_response(res):
serialization_method = res[2] >> 4
message_compression = res[2] & 0x0F
reserved = res[3]
header_extensions = res[4 : header_size * 4]
payload = res[header_size * 4 :]
header_extensions = res[4: header_size * 4]
payload = res[header_size * 4:]
result = {}
payload_msg = None
payload_size = 0
if message_type == SERVER_FULL_RESPONSE:
payload_size = int.from_bytes(payload[:4], "big", signed=True)
payload_msg = payload[4:]
@ -67,16 +65,21 @@ def parse_response(res):
result["code"] = code
payload_size = int.from_bytes(payload[4:8], "big", signed=False)
payload_msg = payload[8:]
if payload_msg is None:
return result
if message_compression == GZIP:
payload_msg = gzip.decompress(payload_msg)
if serialization_method == JSON:
payload_msg = json.loads(str(payload_msg, "utf-8"))
elif serialization_method != NO_SERIALIZATION:
payload_msg = str(payload_msg, "utf-8")
result["payload_msg"] = payload_msg
result["payload_size"] = payload_size
return result
@ -91,13 +94,12 @@ class ASRProvider(ASRProviderBase):
self.correct_table_name = config.get("correct_table_name", "")
self.output_dir = config.get("output_dir")
self.delete_audio_file = delete_audio_file
self.host = "openspeech.bytedance.com"
self.ws_url = f"wss://{self.host}/api/v2/asr"
self.success_code = 1000
self.seg_duration = 15000
# 确保输出目录存在
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
@staticmethod
@ -107,10 +109,13 @@ class ASRProvider(ASRProviderBase):
"""Generate protocol header."""
header = bytearray()
header_size = 1
header.append((0b0001 << 4) | header_size) # Protocol version
header.append((message_type << 4) | message_type_specific_flags)
header.append((0b0001 << 4) | 0b0001) # JSON serialization & GZIP compression
# JSON serialization & GZIP compression
header.append((0b0001 << 4) | 0b0001)
header.append(0x00) # reserved
return header
def _construct_request(self, reqid) -> dict:
@ -146,7 +151,8 @@ class ASRProvider(ASRProviderBase):
) -> Optional[str]:
"""Send request to Volcano ASR service."""
try:
auth_header = {"Authorization": "Bearer; {}".format(self.access_token)}
auth_header = {
"Authorization": "Bearer; {}".format(self.access_token)}
async with websockets.connect(
self.ws_url, additional_headers=auth_header
) as websocket:
@ -154,6 +160,7 @@ class ASRProvider(ASRProviderBase):
request_params = self._construct_request(str(uuid.uuid4()))
payload_bytes = str.encode(json.dumps(request_params))
payload_bytes = gzip.compress(payload_bytes)
full_client_request = self._generate_header()
full_client_request.extend(
(len(payload_bytes)).to_bytes(4, "big")
@ -165,10 +172,12 @@ class ASRProvider(ASRProviderBase):
await websocket.send(full_client_request)
res = await websocket.recv()
result = parse_response(res)
if (
"payload_msg" in result
and result["payload_msg"]["code"] != self.success_code
and result["payload_msg"]["code"] != 1013 # 忽略无有效语音的错误
# Ignore no valid voice error
and result["payload_msg"]["code"] != 1013
):
logger.bind(tag=TAG).error(f"ASR error: {result}")
return None
@ -185,34 +194,37 @@ class ASRProvider(ASRProviderBase):
audio_only_request = self._generate_header(
message_type=CLIENT_AUDIO_ONLY_REQUEST
)
payload_bytes = gzip.compress(chunk)
audio_only_request.extend(
(len(payload_bytes)).to_bytes(4, "big")
) # payload size(4 bytes)
audio_only_request.extend(payload_bytes) # payload
# Send audio data
await websocket.send(audio_only_request)
# Receive response
response = await websocket.recv()
result = parse_response(response)
# Receive response
response = await websocket.recv()
result = parse_response(response)
if (
"payload_msg" in result
and result["payload_msg"]["code"] == self.success_code
):
if len(result["payload_msg"]["result"]) > 0:
return result["payload_msg"]["result"][0]["text"]
return None
elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
# 无有效语音,返回空字符串
return ""
else:
logger.bind(tag=TAG).error(f"ASR error: {result}")
return None
if (
"payload_msg" in result
and result["payload_msg"]["code"] == self.success_code
):
if len(result["payload_msg"]["result"]) > 0:
return result["payload_msg"]["result"][0]["text"]
return None
elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
# No valid voice, return empty string
return ""
else:
logger.bind(tag=TAG).error(f"ASR error: {result}")
return None
except Exception as e:
logger.bind(tag=TAG).error(f"ASR request failed: {e}", exc_info=True)
logger.bind(tag=TAG).error(
f"ASR request failed: {e}", exc_info=True)
return None
@staticmethod
@ -226,7 +238,7 @@ class ASRProvider(ASRProviderBase):
data_len = len(data)
offset = 0
while offset + chunk_size < data_len:
yield data[offset : offset + chunk_size], False
yield data[offset: offset + chunk_size], False
offset += chunk_size
else:
yield data[offset:data_len], True
@ -234,38 +246,40 @@ class ASRProvider(ASRProviderBase):
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
"""Convert speech data to text"""
file_path = None
try:
# 合并所有opus数据包
# Merge all opus data packets
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件
# Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
file_path = self.save_audio_to_file(pcm_data, session_id)
# 直接使用PCM数据
# 计算分段大小 (单声道, 16bit, 16kHz采样率)
# Use PCM data directly
# Calculate segment size (mono, 16bit, 16kHz sample rate)
size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate
segment_size = int(size_per_sec * self.seg_duration / 1000)
# 语音识别
# Speech recognition
start_time = time.time()
text = await self._send_request(combined_pcm_data, segment_size)
if text:
logger.bind(tag=TAG).debug(
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
)
return text, file_path
return "", file_path
except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
return "", file_path
logger.bind(tag=TAG).error(
f"Speech recognition failed: {e}", exc_info=True)
return "", file_path

View file

@ -3,7 +3,7 @@ from typing import Union, Optional
class InterfaceType(Enum):
# 接口类型
STREAM = "STREAM" # 流式接口
NON_STREAM = "NON_STREAM" # 非流式接口
LOCAL = "LOCAL" # 本地服务
# Interface type
STREAM = "STREAM" # Streaming interface
NON_STREAM = "NON_STREAM" # Non-streaming interface
LOCAL = "LOCAL" # Local service

View file

@ -15,10 +15,11 @@ TAG = __name__
logger = setup_logging()
MAX_RETRIES = 2
RETRY_DELAY = 1 # 重试延迟(秒)
RETRY_DELAY = 1 # Retry delay (seconds)
# Capture standard output
# 捕获标准输出
class CaptureOutput:
def __enter__(self):
self._output = io.StringIO()
@ -30,7 +31,7 @@ class CaptureOutput:
self.output = self._output.getvalue()
self._output.close()
# 将捕获到的内容通过 logger 输出
# Output captured content through logger
if self.output:
logger.bind(tag=TAG).info(self.output.strip())
@ -38,59 +39,61 @@ class CaptureOutput:
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
# 内存检测,要求大于2G
# Memory detection, require more than 2G
min_mem_bytes = 2 * 1024 * 1024 * 1024
total_mem = psutil.virtual_memory().total
if total_mem < min_mem_bytes:
logger.bind(tag=TAG).error(f"可用内存不足2G,当前仅有 {total_mem / (1024*1024):.2f} MB,可能无法启动FunASR")
logger.bind(tag=TAG).error(
f"Insufficient memory (less than 2G), currently only {total_mem / (1024*1024):.2f} MB available, may not be able to start FunASR")
self.interface_type = InterfaceType.LOCAL
self.model_dir = config.get("model_dir")
self.output_dir = config.get("output_dir") # 修正配置键名
# Correct configuration key name
self.output_dir = config.get("output_dir")
self.delete_audio_file = delete_audio_file
# 确保输出目录存在
# Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
with CaptureOutput():
self.model = AutoModel(
model=self.model_dir,
vad_kwargs={"max_single_segment_time": 30000},
disable_update=True,
hub="hf",
# device="cuda:0", # 启用GPU加速
# device="cuda:0", # Enable GPU acceleration
)
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""语音转文本主处理逻辑"""
"""Speech to text main processing logic"""
file_path = None
retry_count = 0
while retry_count < MAX_RETRIES:
try:
# 合并所有opus数据包
# Merge all opus data packets
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
# 检查磁盘空间
# Check disk space
if not self.delete_audio_file:
free_space = shutil.disk_usage(self.output_dir).free
if free_space < len(combined_pcm_data) * 2: # 预留2倍空间
raise OSError("磁盘空间不足")
if free_space < len(combined_pcm_data) * 2: # Reserve 2x space
raise OSError("Insufficient disk space")
# 判断是否保存为WAV文件
# Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
file_path = self.save_audio_to_file(pcm_data, session_id)
# 语音识别
# Speech recognition
start_time = time.time()
result = self.model.generate(
input=combined_pcm_data,
@ -99,9 +102,11 @@ class ASRProvider(ASRProviderBase):
use_itn=True,
batch_size_s=60,
)
text = rich_transcription_postprocess(result[0]["text"])
logger.bind(tag=TAG).debug(
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
)
return text, file_path
@ -110,25 +115,28 @@ class ASRProvider(ASRProviderBase):
retry_count += 1
if retry_count >= MAX_RETRIES:
logger.bind(tag=TAG).error(
f"语音识别失败(已重试{retry_count}次): {e}", exc_info=True
f"Speech recognition failed (retried {retry_count} times): {e}", exc_info=True
)
return "", file_path
logger.bind(tag=TAG).warning(
f"语音识别失败,正在重试({retry_count}/{MAX_RETRIES}): {e}"
f"Speech recognition failed, retrying ({retry_count}/{MAX_RETRIES}): {e}"
)
time.sleep(RETRY_DELAY)
except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
logger.bind(tag=TAG).error(
f"Speech recognition failed: {e}", exc_info=True)
return "", file_path
finally:
# 文件清理逻辑
# File cleanup logic
if self.delete_audio_file and file_path and os.path.exists(file_path):
try:
os.remove(file_path)
logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
logger.bind(tag=TAG).debug(
f"Deleted temporary audio file: {file_path}")
except Exception as e:
logger.bind(tag=TAG).error(
f"文件删除失败: {file_path} | 错误: {e}"
f"File deletion failed: {file_path} | Error: {e}"
)

View file

@ -11,11 +11,11 @@ import re
TAG = __name__
logger = setup_logging()
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
"""
Initialize the ASRProvider with server configuration.
:param config: Dictionary containing 'host', 'port', and 'is_ssl'.
:param delete_audio_file: Boolean to indicate whether to delete audio files after processing.
"""
@ -36,11 +36,12 @@ class ASRProvider(ASRProviderBase):
if self.is_ssl
else f"ws://{self.host}:{self.port}"
)
self.ssl_context = ssl.SSLContext() if self.is_ssl else None
if self.ssl_context:
self.ssl_context.check_hostname = False
self.ssl_context.verify_mode = ssl.CERT_NONE
async def _receive_responses(self, ws) -> None:
"""
Asynchronous generator to receive messages from the WebSocket.
@ -52,11 +53,13 @@ class ASRProvider(ASRProviderBase):
response = await asyncio.wait_for(ws.recv(), timeout=5)
response_data = json.loads(response)
logger.bind(tag=TAG).debug(f"Received response: {response_data}")
if response_data.get("is_final", True):
text += response_data.get("text", "")
break
else:
text += response_data.get("text", "")
except asyncio.TimeoutError:
logger.bind(tag=TAG).error(
"Timeout while waiting for response from WebSocket."
@ -65,45 +68,45 @@ class ASRProvider(ASRProviderBase):
except websockets.exceptions.ConnectionClosed as e:
logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}")
break
return text
async def _send_data(self, ws, pcm_data: bytes, session_id: str) -> tuple:
"""
Internal method to handle WebSocket communication.
Reuses the persistent WebSocket connection if available.
:param pcm_data: PCM audio data to send.
:param session_id: Unique session identifier.
:return: Tuple containing recognized text and optional timestamp.
"""
# Send initial configuration message
config_message = json.dumps(
{
"mode": "offline",
"chunk_size": [5, 10, 5],
"chunk_interval": 10,
"wav_name": session_id,
"is_speaking": True,
"itn": False,
}
)
config_message = json.dumps({
"mode": "offline",
"chunk_size": [5, 10, 5],
"chunk_interval": 10,
"wav_name": session_id,
"is_speaking": True,
"itn": False,
})
await ws.send(config_message)
logger.bind(tag=TAG).debug(f"Sent configuration message: {config_message}")
# Send PCM data
await ws.send(pcm_data)
logger.bind(tag=TAG).debug(f"Sent PCM data of length: {len(pcm_data)} bytes")
# Indicate end of speech
end_message = json.dumps({"is_speaking": False})
await ws.send(end_message)
logger.bind(tag=TAG).debug(f"Sent end message: {end_message}")
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""
Convert speech data to text using FunASR.
:param opus_data: List of Opus-encoded audio data chunks.
:param session_id: Unique session identifier.
:return: Tuple containing recognized text and optional timestamp.
@ -114,12 +117,13 @@ class ASRProvider(ASRProviderBase):
else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件
# Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
file_path = self.save_audio_to_file(pcm_data, session_id)
auth_header = {"Authorization": "Bearer; {}".format(self.api_key)}
async with websockets.connect(
self.uri,
@ -134,31 +138,33 @@ class ASRProvider(ASRProviderBase):
self._send_data(ws, combined_pcm_data, session_id)
)
receive_task = asyncio.create_task(self._receive_responses(ws))
# Gather tasks with error handling
done, pending = await asyncio.wait(
[send_task, receive_task], return_when=asyncio.FIRST_EXCEPTION
)
# Cancel any pending tasks
for task in pending:
task.cancel()
# Check for exceptions in completed tasks
for task in done:
if task.exception():
raise task.exception()
# Get the result from the receive task
result = receive_task.result()
match = re.match(r"<\|(.*?)\|><\|(.*?)\|><\|(.*?)\|>(.*)", result)
if match:
result = match.group(4).strip()
return (
result,
file_path,
) # Return the recognized text and timestamp (if any)
except websockets.exceptions.ConnectionClosed as e:
logger.bind(tag=TAG).error(f"WebSocket connection closed: {e}")
return "", file_path

View file

@ -17,7 +17,7 @@ class ASRProvider(ASRProviderBase):
Groq Whisper ASR Provider
Uses Groq's API for Whisper-based speech-to-text transcription
"""
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
self.interface_type = InterfaceType.NON_STREAM
@ -28,14 +28,14 @@ class ASRProvider(ASRProviderBase):
self.response_format = config.get("response_format", "text")
self.output_dir = config.get("output_dir", "./audio_files")
self.delete_audio_file = delete_audio_file
# Groq base URL (can be overridden in config)
self.base_url = config.get("base_url", "https://api.groq.com")
# Timeout configuration
timeout = config.get("timeout", 60)
self.timeout = int(timeout) if timeout else 60
# Initialize Groq client
self.client = Groq(
api_key=self.api_key,
@ -43,11 +43,11 @@ class ASRProvider(ASRProviderBase):
timeout=self.timeout,
max_retries=2
)
# Ensure output directory exists
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
logger.bind(tag=TAG).info(
f"Groq Whisper ASR initialized with model: {self.model}, "
f"language: {self.language}, temperature: {self.temperature}"
@ -57,9 +57,8 @@ class ASRProvider(ASRProviderBase):
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""Convert speech data to text using Groq Whisper API"""
start_time = time.time()
try:
# Decode Opus to PCM if needed
if audio_format == "opus":
@ -69,10 +68,10 @@ class ASRProvider(ASRProviderBase):
return None, None
else:
pcm_data = opus_data
# Save audio to temporary file (Groq API requires file upload)
audio_file_path = self.save_audio_to_file(pcm_data, session_id)
# Perform transcription
try:
with open(audio_file_path, "rb") as audio_file:
@ -88,7 +87,7 @@ class ASRProvider(ASRProviderBase):
response_format=self.response_format
)
)
# Extract text based on response format
if self.response_format == "text":
result_text = transcription
@ -96,33 +95,34 @@ class ASRProvider(ASRProviderBase):
result_text = transcription.text
else:
result_text = str(transcription)
elapsed_time = time.time() - start_time
logger.bind(tag=TAG).info(
f"Groq Whisper transcription completed in {elapsed_time:.2f}s: {result_text}"
)
return result_text, audio_file_path
except Exception as e:
logger.bind(tag=TAG).error(
f"Groq API error: {str(e)}, type: {type(e).__name__}"
)
return None, audio_file_path
finally:
# Clean up audio file if configured
if self.delete_audio_file and os.path.exists(audio_file_path):
try:
os.remove(audio_file_path)
logger.bind(tag=TAG).debug(f"Deleted audio file: {audio_file_path}")
logger.bind(tag=TAG).debug(
f"Deleted audio file: {audio_file_path}")
except Exception as e:
logger.bind(tag=TAG).warning(
f"Failed to delete audio file {audio_file_path}: {e}"
)
except Exception as e:
logger.bind(tag=TAG).error(
f"Speech-to-text error: {str(e)}, type: {type(e).__name__}"
)
return None, None
return None, None

View file

@ -10,12 +10,13 @@ import requests
TAG = __name__
logger = setup_logging()
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
self.interface_type = InterfaceType.NON_STREAM
self.api_key = config.get("api_key")
self.api_url = config.get("base_url")
self.model = config.get("model_name")
self.model = config.get("model_name")
self.output_dir = config.get("output_dir")
self.delete_audio_file = delete_audio_file
@ -32,21 +33,21 @@ class ASRProvider(ASRProviderBase):
file_path = self.save_audio_to_file(pcm_data, session_id)
logger.bind(tag=TAG).debug(
f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}"
f"Audio file save time: {time.time() - start_time:.3f}s | Path: {file_path}"
)
logger.bind(tag=TAG).info(f"file path: {file_path}")
headers = {
"Authorization": f"Bearer {self.api_key}",
}
# 使用data参数传递模型名称
# Use data parameter to pass model name
data = {
"model": self.model
}
with open(file_path, "rb") as audio_file: # 使用with语句确保文件关闭
# Use with statement to ensure file is closed
with open(file_path, "rb") as audio_file:
files = {
"file": audio_file
}
@ -59,24 +60,26 @@ class ASRProvider(ASRProviderBase):
headers=headers
)
logger.bind(tag=TAG).debug(
f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {response.text}"
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {response.text}"
)
if response.status_code == 200:
text = response.json().get("text", "")
return text, file_path
else:
raise Exception(f"API请求失败: {response.status_code} - {response.text}")
raise Exception(
f"API request failed: {response.status_code} - {response.text}")
except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}")
logger.bind(tag=TAG).error(f"Speech recognition failed: {e}")
return "", None
finally:
# 文件清理逻辑
# File cleanup logic
if self.delete_audio_file and file_path and os.path.exists(file_path):
try:
os.remove(file_path)
logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
logger.bind(tag=TAG).debug(
f"Deleted temporary audio file: {file_path}")
except Exception as e:
logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
logger.bind(tag=TAG).error(
f"File deletion failed: {file_path} | Error: {e}")

View file

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

View file

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

View file

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

View file

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

View file

@ -16,35 +16,34 @@ class IntentProvider(IntentProviderBase):
super().__init__(config)
self.llm = None
self.promot = ""
# 导入全局缓存管理器
from core.utils.cache.manager import cache_manager, CacheType
self.cache_manager = cache_manager
self.CacheType = CacheType
self.history_count = 4 # 默认使用最近4条对话记录
# Add cache management
self.intent_cache = {} # Cache for intent recognition results
self.cache_expiry = 600 # Cache validity period of 10 minutes
self.cache_max_size = 100 # Maximum of 100 intents to cache
self.history_count = 4 # Default to using the last 4 conversation records
def get_intent_system_prompt(self, functions_list: str) -> str:
"""
根据配置的意图选项和可用函数动态生成系统提示词
Dynamically generate a system prompt based on configured intent options and available functions.
Args:
functions: 可用的函数列表,JSON格式字符串
functions: A list of available functions in JSON format string.
Returns:
格式化后的系统提示词
A formatted system prompt.
"""
# 构建函数说明部分
functions_desc = "可用的函数列表:\n"
# Build the function description part
functions_desc = "Available functions list:\n"
for func in functions_list:
func_info = func.get("function", {})
name = func_info.get("name", "")
desc = func_info.get("description", "")
params = func_info.get("parameters", {})
functions_desc += f"\n函数名: {name}\n"
functions_desc += f"描述: {desc}\n"
functions_desc += f"\nFunction Name: {name}\n"
functions_desc += f"Description: {desc}\n"
if params:
functions_desc += "参数:\n"
functions_desc += "Parameters:\n"
for param_name, param_info in params.get("properties", {}).items():
param_desc = param_info.get("description", "")
param_type = param_info.get("type", "")
@ -53,60 +52,81 @@ class IntentProvider(IntentProviderBase):
functions_desc += "---\n"
prompt = (
"你是一个意图识别助手。请分析用户的最后一句话,判断用户意图并调用相应的函数。\n\n"
"- 如果用户使用疑问词(如'怎么'、'为什么'、'如何')询问退出相关的问题(例如'怎么退出了?'),注意这不是让你退出,请返回 {'function_call': {'name': 'continue_chat'}\n"
"- 仅当用户明确使用'退出系统'、'结束对话'、'我不想和你说话了'等指令时,才触发 handle_exit_intent\n\n"
"You are an intent recognition assistant. Please analyze the user's last sentence to determine the user's intent and call the corresponding function.\n\n"
"- If the user uses question words (like 'how', 'why', 'what') to ask about exiting (e.g., 'How did it exit?'), note that this is not a request to exit. Please return {'function_call': {'name': 'continue_chat'}}\n"
"- Only trigger handle_exit_intent when the user explicitly uses commands like 'exit system', 'end conversation', 'I don't want to talk to you anymore'.\n\n"
f"{functions_desc}\n"
"处理步骤:\n"
"1. 分析用户输入,确定用户意图\n"
"2. 从可用函数列表中选择最匹配的函数\n"
"3. 如果找到匹配的函数,生成对应的function_call 格式\n"
'4. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n\n'
"返回格式要求:\n"
"1. 必须返回纯JSON格式\n"
"2. 必须包含function_call字段\n"
"3. function_call必须包含name字段\n"
"4. 如果函数需要参数,必须包含arguments字段\n\n"
"示例:\n"
"Processing Steps:\n"
"1. Analyze user input to determine user intent.\n"
"2. Select the best matching function from the list of available functions.\n"
"3. If a matching function is found, generate the corresponding function_call format.\n"
'4. If no matching function is found, return {"function_call": {"name": "continue_chat"}}\n\n'
"Return Format Requirements:\n"
"1. Must return in pure JSON format.\n"
"2. Must include the function_call field.\n"
"3. function_call must include the name field.\n"
"4. If the function requires parameters, it must include the arguments field.\n\n"
"Examples:\n"
"```\n"
"用户: 现在几点了?\n"
'返回: {"function_call": {"name": "get_time"}}\n'
"User: What time is it?\n"
'Return: {"function_call": {"name": "get_time"}}\n'
"```\n"
"```\n"
"用户: 当前电池电量是多少?\n"
'返回: {"function_call": {"name": "get_battery_level", "arguments": {"response_success": "当前电池电量为{value}%", "response_failure": "无法获取Battery的当前电量百分比"}}}\n'
"User: What is the current battery level?\n"
'Return: {"function_call": {"name": "get_battery_level", "arguments": {"response_success": "Current battery level is {value}%", "response_failure": "Unable to get the current battery percentage."}}}\n'
"```\n"
"```\n"
"用户: 当前屏幕亮度是多少?\n"
'返回: {"function_call": {"name": "self_screen_get_brightness"}}\n'
"User: What is the current screen brightness?\n"
'Return: {"function_call": {"name": "self_screen_get_brightness"}}\n'
"```\n"
"```\n"
"用户: 设置屏幕亮度为50%\n"
'返回: {"function_call": {"name": "self_screen_set_brightness", "arguments": {"brightness": 50}}}\n'
"User: Set screen brightness to 50%.\n"
'Return: {"function_call": {"name": "self_screen_set_brightness", "arguments": {"brightness": 50}}}\n'
"```\n"
"```\n"
"用户: 我想结束对话\n"
'返回: {"function_call": {"name": "handle_exit_intent", "arguments": {"say_goodbye": "goodbye"}}}\n'
"User: I want to end the conversation.\n"
'Return: {"function_call": {"name": "handle_exit_intent", "arguments": {"say_goodbye": "goodbye"}}}\n'
"```\n"
"```\n"
"用户: 你好啊\n"
'返回: {"function_call": {"name": "continue_chat"}}\n'
"User: Hello.\n"
'Return: {"function_call": {"name": "continue_chat"}}\n'
"```\n\n"
"注意:\n"
"1. 只返回JSON格式,不要包含任何其他文字\n"
'2. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n'
"3. 确保返回的JSON格式正确,包含所有必要的字段\n"
"特殊说明:\n"
"- 当用户单次输入包含多个指令时(如'打开灯并且调高音量')\n"
"- 请返回多个function_call组成的JSON数组\n"
"- 示例:{'function_calls': [{name:'light_on'}, {name:'volume_up'}]}"
"Note:\n"
"1. Only return in JSON format, do not include any other text.\n"
'2. If no matching function is found, return {"function_call": {"name": "continue_chat"}}.\n'
"3. Ensure the returned JSON format is correct and includes all necessary fields.\n"
"Special Instructions:\n"
"- When a single user input contains multiple commands (e.g., 'turn on the light and increase the volume').\n"
"- Please return a JSON array of multiple function_calls.\n"
"- Example: {'function_calls': [{'name':'light_on'}, {'name':'volume_up'}]}"
)
return prompt
def clean_cache(self):
"""Clean up expired cache."""
now = time.time()
# Find expired keys
expired_keys = [
k
for k, v in self.intent_cache.items()
if now - v["timestamp"] > self.cache_expiry
]
for key in expired_keys:
del self.intent_cache[key]
# If the cache is too large, remove the oldest entries
if len(self.intent_cache) > self.cache_max_size:
# Sort by timestamp and keep the newest entries
sorted_items = sorted(
self.intent_cache.items(), key=lambda x: x[1]["timestamp"]
)
for key, _ in sorted_items[: len(sorted_items) - self.cache_max_size]:
del self.intent_cache[key]
def replyResult(self, text: str, original_text: str):
llm_result = self.llm.response_no_stream(
system_prompt=text,
user_prompt="请根据以上内容,像人类一样说话的口吻回复用户,要求简洁,请直接返回结果。用户现在说:"
user_prompt="Based on the content above, please reply to the user in a human-like tone, keep it concise, and return the result directly. The user now says: "
+ original_text,
)
return llm_result
@ -117,24 +137,31 @@ class IntentProvider(IntentProviderBase):
if conn.func_handler is None:
return '{"function_call": {"name": "continue_chat"}}'
# 记录整体开始时间
# Record the overall start time
total_start_time = time.time()
# 打印使用的模型信息
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
logger.bind(tag=TAG).debug(f"使用意图识别模型: {model_info}")
# Print the model information being used
model_info = getattr(self.llm, "model_name",
str(self.llm.__class__.__name__))
logger.bind(tag=TAG).debug(
f"Using intent recognition model: {model_info}")
# 计算缓存键
cache_key = hashlib.md5((conn.device_id + text).encode()).hexdigest()
# Calculate the cache key
cache_key = hashlib.md5(text.encode()).hexdigest()
# 检查缓存
cached_intent = self.cache_manager.get(self.CacheType.INTENT, cache_key)
if cached_intent is not None:
cache_time = time.time() - total_start_time
logger.bind(tag=TAG).debug(
f"使用缓存的意图: {cache_key} -> {cached_intent}, 耗时: {cache_time:.4f}秒"
)
return cached_intent
# Check the cache
if cache_key in self.intent_cache:
cache_entry = self.intent_cache[cache_key]
# Check if the cache has expired
if time.time() - cache_entry["timestamp"] <= self.cache_expiry:
cache_time = time.time() - total_start_time
logger.bind(tag=TAG).debug(
f"Using cached intent: {cache_key} -> {cache_entry['intent']}, time taken: {cache_time:.4f} seconds"
)
return cache_entry["intent"]
# Clean the cache
self.clean_cache()
if self.promot == "":
functions = conn.func_handler.get_functions()
@ -157,17 +184,17 @@ class IntentProvider(IntentProviderBase):
else:
devices = []
if len(devices) > 0:
hass_prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n"
hass_prompt = "\nHere is a list of my smart home devices (location, device name, entity_id), which can be controlled via Home Assistant:\n"
for device in devices:
hass_prompt += device + "\n"
prompt_music += hass_prompt
logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
# 构建用户对话历史的提示
# Build the user dialogue history prompt
msgStr = ""
# 获取最近的对话历史
# Get the recent dialogue history
start_idx = max(0, len(dialogue_history) - self.history_count)
for i in range(start_idx, len(dialogue_history)):
msgStr += f"{dialogue_history[i].role}: {dialogue_history[i].content}\n"
@ -175,57 +202,59 @@ class IntentProvider(IntentProviderBase):
msgStr += f"User: {text}\n"
user_prompt = f"current dialogue:\n{msgStr}"
# 记录预处理完成时间
# Record the preprocessing completion time
preprocess_time = time.time() - total_start_time
logger.bind(tag=TAG).debug(f"意图识别预处理耗时: {preprocess_time:.4f}秒")
logger.bind(tag=TAG).debug(
f"Intent recognition preprocessing time: {preprocess_time:.4f} seconds")
# 使用LLM进行意图识别
# Use LLM for intent recognition
llm_start_time = time.time()
logger.bind(tag=TAG).debug(f"开始LLM意图识别调用, 模型: {model_info}")
logger.bind(tag=TAG).debug(
f"Starting LLM intent recognition call, model: {model_info}")
intent = self.llm.response_no_stream(
system_prompt=prompt_music, user_prompt=user_prompt
)
# 记录LLM调用完成时间
# Record the LLM call completion time
llm_time = time.time() - llm_start_time
logger.bind(tag=TAG).debug(
f"LLM意图识别完成, 模型: {model_info}, 调用耗时: {llm_time:.4f}秒"
f"LLM intent recognition complete, model: {model_info}, call time: {llm_time:.4f} seconds"
)
# 记录后处理开始时间
# Record the post-processing start time
postprocess_start_time = time.time()
# 清理和解析响应
# Clean and parse the response
intent = intent.strip()
# 尝试提取JSON部分
# Try to extract the JSON part
match = re.search(r"\{.*\}", intent, re.DOTALL)
if match:
intent = match.group(0)
# 记录总处理时间
# Record the total processing time
total_time = time.time() - total_start_time
logger.bind(tag=TAG).debug(
f"【意图识别性能】模型: {model_info}, 总耗时: {total_time:.4f}秒, LLM调用: {llm_time:.4f}秒, 查询: '{text[:20]}...'"
f"【Intent Recognition Performance】Model: {model_info}, Total time: {total_time:.4f}s, LLM call: {llm_time:.4f}s, Query: '{text[:20]}...'"
)
# 尝试解析为JSON
# Try to parse as JSON
try:
intent_data = json.loads(intent)
# 如果包含function_call,则格式化为适合处理的格式
# If it contains function_call, format it for processing
if "function_call" in intent_data:
function_data = intent_data["function_call"]
function_name = function_data.get("name")
function_args = function_data.get("arguments", {})
# 记录识别到的function call
# Record the recognized function call
logger.bind(tag=TAG).info(
f"llm 识别到意图: {function_name}, 参数: {function_args}"
f"LLM recognized intent: {function_name}, arguments: {function_args}"
)
# 如果是继续聊天,清理工具调用相关的历史消息
# If continuing the chat, clean up tool call related history messages
if function_name == "continue_chat":
# 保留非工具相关的消息
# Keep non-tool related messages
clean_history = [
msg
for msg in conn.dialogue.dialogue
@ -233,30 +262,38 @@ class IntentProvider(IntentProviderBase):
]
conn.dialogue.dialogue = clean_history
# 添加到缓存
self.cache_manager.set(self.CacheType.INTENT, cache_key, intent)
# Add to cache
self.intent_cache[cache_key] = {
"intent": intent,
"timestamp": time.time(),
}
# 后处理时间
# Post-processing time
postprocess_time = time.time() - postprocess_start_time
logger.bind(tag=TAG).debug(f"意图后处理耗时: {postprocess_time:.4f}秒")
logger.bind(tag=TAG).debug(
f"Intent post-processing time: {postprocess_time:.4f} seconds")
# 确保返回完全序列化的JSON字符串
# Ensure a fully serialized JSON string is returned
return intent
else:
# 添加到缓存
self.cache_manager.set(self.CacheType.INTENT, cache_key, intent)
# Add to cache
self.intent_cache[cache_key] = {
"intent": intent,
"timestamp": time.time(),
}
# 后处理时间
# Post-processing time
postprocess_time = time.time() - postprocess_start_time
logger.bind(tag=TAG).debug(f"意图后处理耗时: {postprocess_time:.4f}秒")
logger.bind(tag=TAG).debug(
f"Intent post-processing time: {postprocess_time:.4f} seconds")
# 返回普通意图
# Return normal intent
return intent
except json.JSONDecodeError:
# 后处理时间
# Post-processing time
postprocess_time = time.time() - postprocess_start_time
logger.bind(tag=TAG).error(
f"无法解析意图JSON: {intent}, 后处理耗时: {postprocess_time:.4f}秒"
f"Failed to parse intent JSON: {intent}, post-processing time: {postprocess_time:.4f} seconds"
)
# 如果解析失败,默认返回继续聊天意图
return '{"intent": "继续聊天"}'
# If parsing fails, default to returning a continue chat intent
return '{"intent": "Continue Chat"}'

View file

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

View file

@ -4,6 +4,7 @@ from dashscope import Application
from core.providers.llm.base import LLMProviderBase
from core.utils.util import check_model_key
TAG = __name__
logger = setup_logging()
@ -19,14 +20,14 @@ class LLMProvider(LLMProviderBase):
def response(self, session_id, dialogue):
try:
# 处理dialogue
# Process dialogue
if self.is_No_prompt:
dialogue.pop(0)
logger.bind(tag=TAG).debug(
f"【阿里百练API服务】处理后的dialogue: {dialogue}"
f"[Alibaba Bailian API Service] Processed dialogue: {dialogue}"
)
# 构造调用参数
# Construct call parameters
call_params = {
"api_key": self.api_key,
"app_id": self.app_id,
@ -34,12 +35,12 @@ class LLMProvider(LLMProviderBase):
"messages": dialogue,
}
if self.memory_id != False:
# 百练memory需要prompt参数
# Bailian memory requires prompt parameter
prompt = dialogue[-1].get("content")
call_params["memory_id"] = self.memory_id
call_params["prompt"] = prompt
logger.bind(tag=TAG).debug(
f"【阿里百练API服务】处理后的prompt: {prompt}"
f"[Alibaba Bailian API Service] Processed prompt: {prompt}"
)
responses = Application.call(**call_params)
@ -47,20 +48,21 @@ class LLMProvider(LLMProviderBase):
logger.bind(tag=TAG).error(
f"code={responses.status_code}, "
f"message={responses.message}, "
f"请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code"
f"Please refer to documentation: https://help.aliyun.com/zh/model-studio/developer-reference/error-code"
)
yield "【阿里百练API服务响应异常】"
yield "[Alibaba Bailian API Service Response Exception]"
else:
logger.bind(tag=TAG).debug(
f"【阿里百练API服务】构造参数: {call_params}"
f"[Alibaba Bailian API Service] Constructed parameters: {call_params}"
)
yield responses.output.text
except Exception as e:
logger.bind(tag=TAG).error(f"【阿里百练API服务】响应异常: {e}")
yield "【LLM服务响应异常】"
logger.bind(tag=TAG).error(
f"[Alibaba Bailian API Service] Response exception: {e}")
yield "[LLM Service Response Exception]"
def response_with_functions(self, session_id, dialogue, functions=None):
logger.bind(tag=TAG).error(
f"阿里百练暂未实现完整的工具调用(function call),建议使用其他意图识别"
)
f"Alibaba Bailian has not yet implemented complete tool calling (function call), it is recommended to use other intent recognition methods"
)

View file

@ -1,9 +1,11 @@
from abc import ABC, abstractmethod
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
class LLMProviderBase(ABC):
@abstractmethod
def response(self, session_id, dialogue):
@ -12,7 +14,7 @@ class LLMProviderBase(ABC):
def response_no_stream(self, system_prompt, user_prompt, **kwargs):
try:
# 构造对话格式
# Construct dialogue format
dialogue = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
@ -23,17 +25,18 @@ class LLMProviderBase(ABC):
return result
except Exception as e:
logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}")
return "【LLM服务响应异常】"
logger.bind(tag=TAG).error(
f"Error in Ollama response generation: {e}")
return "[LLM Service Response Exception]"
def response_with_functions(self, session_id, dialogue, functions=None):
"""
Default implementation for function calling (streaming)
This should be overridden by providers that support function calls
Returns: generator that yields either text tokens or a special function call token
"""
# For providers that don't support functions, just return regular response
for token in self.response(session_id, dialogue):
yield token, None

View file

@ -2,6 +2,7 @@ from config.logger import setup_logging
import json
from core.providers.llm.base import LLMProviderBase
# official coze sdk for Python [cozepy](https://github.com/coze-dev/coze-py)
from cozepy import COZE_CN_BASE_URL
from cozepy import (
@ -13,34 +14,41 @@ from cozepy import (
from core.providers.llm.system_prompt import get_system_prompt_for_function
from core.utils.util import check_model_key
TAG = __name__
logger = setup_logging()
class LLMProvider(LLMProviderBase):
def __init__(self, config):
self.personal_access_token = config.get("personal_access_token")
self.bot_id = str(config.get("bot_id"))
self.user_id = str(config.get("user_id"))
self.session_conversation_map = {} # 存储session_id和conversation_id的映射
self.session_conversation_map = {} # Store mapping between session_id and conversation_id
model_key_msg = check_model_key("CozeLLM", self.personal_access_token)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
def response(self, session_id, dialogue, **kwargs):
coze_api_token = self.personal_access_token
coze_api_base = COZE_CN_BASE_URL
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)
conversation_id = self.session_conversation_map.get(session_id)
# 如果没有找到conversation_id,则创建新的对话
# If no conversation_id is found, create a new conversation
if not conversation_id:
conversation = coze.conversations.create(messages=[])
conversation_id = conversation.id
self.session_conversation_map[session_id] = conversation_id # 更新映射
self.session_conversation_map[session_id] = conversation_id # Update mapping
for event in coze.chat.stream(
bot_id=self.bot_id,
@ -54,15 +62,17 @@ class LLMProvider(LLMProviderBase):
print(event.message.content, end="", flush=True)
yield event.message.content
def response_with_functions(self, session_id, dialogue, functions=None):
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
# 第一次调用llm, 取最后一条用户消息,附加tool提示词
# First call to llm, get the last user message, append tool prompt
last_msg = dialogue[-1]["content"]
function_str = json.dumps(functions, ensure_ascii=False)
modify_msg = get_system_prompt_for_function(function_str) + last_msg
dialogue[-1]["content"] = modify_msg
# 如果最后一个是 role="tool",附加到user上
# If the last one is role="tool", append to user
if len(dialogue) > 1 and dialogue[-1]["role"] == "tool":
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
while len(dialogue) > 1:
@ -71,5 +81,6 @@ class LLMProvider(LLMProviderBase):
break
dialogue.pop()
for token in self.response(session_id, dialogue):
yield token, None
yield token, None

View file

@ -5,27 +5,31 @@ from core.providers.llm.base import LLMProviderBase
from core.providers.llm.system_prompt import get_system_prompt_for_function
from core.utils.util import check_model_key
TAG = __name__
logger = setup_logging()
class LLMProvider(LLMProviderBase):
def __init__(self, config):
self.api_key = config["api_key"]
self.mode = config.get("mode", "chat-messages")
self.base_url = config.get("base_url", "https://api.dify.ai/v1").rstrip("/")
self.session_conversation_map = {} # 存储session_id和conversation_id的映射
self.session_conversation_map = {} # Store mapping between session_id and conversation_id
model_key_msg = check_model_key("DifyLLM", self.api_key)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
def response(self, session_id, dialogue, **kwargs):
try:
# 取最后一条用户消息
# Get the last user message
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
conversation_id = self.session_conversation_map.get(session_id)
# 发起流式请求
# Initiate streaming request
if self.mode == "chat-messages":
request_json = {
"query": last_msg["content"],
@ -47,6 +51,7 @@ class LLMProvider(LLMProviderBase):
"user": session_id,
}
with requests.post(
f"{self.base_url}/{self.mode}",
headers={"Authorization": f"Bearer {self.api_key}"},
@ -57,13 +62,13 @@ class LLMProvider(LLMProviderBase):
for line in r.iter_lines():
if line.startswith(b"data: "):
event = json.loads(line[6:])
# 如果没有找到conversation_id,则获取此次conversation_id
# If no conversation_id is found, get the conversation_id from this response
if not conversation_id:
conversation_id = event.get("conversation_id")
self.session_conversation_map[session_id] = (
conversation_id # 更新映射
conversation_id # Update mapping
)
# 过滤 message_replace 事件,此事件会全量推一次
# Filter message_replace events, as they push the full content once
if event.get("event") != "message_replace" and event.get(
"answer"
):
@ -76,30 +81,33 @@ class LLMProvider(LLMProviderBase):
if event["data"]["status"] == "succeeded":
yield event["data"]["outputs"]["answer"]
else:
yield "【服务响应异常】"
yield "[Service Response Exception]"
elif self.mode == "completion-messages":
for line in r.iter_lines():
if line.startswith(b"data: "):
event = json.loads(line[6:])
# 过滤 message_replace 事件,此事件会全量推一次
# Filter message_replace events, as they push the full content once
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 "【服务响应异常】"
yield "[Service Response Exception]"
def response_with_functions(self, session_id, dialogue, functions=None):
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
# 第一次调用llm, 取最后一条用户消息,附加tool提示词
# First call to llm, get the last user message, append tool prompt
last_msg = dialogue[-1]["content"]
function_str = json.dumps(functions, ensure_ascii=False)
modify_msg = get_system_prompt_for_function(function_str) + last_msg
dialogue[-1]["content"] = modify_msg
# 如果最后一个是 role="tool",附加到user上
# If the last one is role="tool", append to user
if len(dialogue) > 1 and dialogue[-1]["role"] == "tool":
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
while len(dialogue) > 1:
@ -108,5 +116,6 @@ class LLMProvider(LLMProviderBase):
break
dialogue.pop()
for token in self.response(session_id, dialogue):
yield token, None
yield token, None

View file

@ -4,10 +4,12 @@ import requests
from core.providers.llm.base import LLMProviderBase
from core.utils.util import check_model_key
TAG = __name__
logger = setup_logging()
class LLMProvider(LLMProviderBase):
def __init__(self, config):
self.api_key = config["api_key"]
@ -18,12 +20,14 @@ class LLMProvider(LLMProviderBase):
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
def response(self, session_id, dialogue, **kwargs):
try:
# 取最后一条用户消息
# Get the last user message
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
# 发起流式请求
# Initiate streaming request
with requests.post(
f"{self.base_url}/chat/completions",
headers={"Authorization": f"Bearer {self.api_key}"},
@ -43,6 +47,7 @@ class LLMProvider(LLMProviderBase):
if line[6:].decode("utf-8") == "[DONE]":
break
data = json.loads(line[6:])
if "choices" in data and len(data["choices"]) > 0:
delta = data["choices"][0].get("delta", {})
@ -58,16 +63,19 @@ class LLMProvider(LLMProviderBase):
continue
yield content
except json.JSONDecodeError as e:
continue
except Exception as e:
continue
except Exception as e:
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
yield "【服务响应异常】"
yield "[Service Response Exception]"
def response_with_functions(self, session_id, dialogue, functions=None):
logger.bind(tag=TAG).error(
f"fastgpt暂未实现完整的工具调用(function call),建议使用其他意图识别"
)
f"FastGPT has not yet implemented complete tool calling (function call), it is recommended to use other intent recognition methods"
)

View file

@ -1,24 +1,26 @@
import os, json, uuid
import os
import json
import uuid
from types import SimpleNamespace
from typing import Any, Dict, List
import requests
from google import generativeai as genai
from google.generativeai import types, GenerationConfig
from core.providers.llm.base import LLMProviderBase
from core.utils.util import check_model_key
from config.logger import setup_logging
from google.generativeai.types import GenerateContentResponse
from requests import RequestException
log = setup_logging()
TAG = __name__
def test_proxy(proxy_url: str, test_url: str) -> bool:
try:
resp = requests.get(test_url, proxies={"http": proxy_url, "https": proxy_url})
resp = requests.get(test_url, proxies={
"http": proxy_url, "https": proxy_url})
return 200 <= resp.status_code < 400
except RequestException:
return False
@ -26,8 +28,8 @@ def test_proxy(proxy_url: str, test_url: str) -> bool:
def setup_proxy_env(http_proxy: str | None, https_proxy: str | None):
"""
分别测试 HTTP 和 HTTPS 代理是否可用,并设置环境变量。
如果 HTTPS 代理不可用但 HTTP 可用,会将 HTTPS_PROXY 也指向 HTTP。
Test whether HTTP and HTTPS proxies are available separately, and set environment variables.
If HTTPS proxy is not available but HTTP is available, will also point HTTPS_PROXY to HTTP.
"""
test_http_url = "http://www.google.com"
test_https_url = "https://www.google.com"
@ -38,32 +40,37 @@ def setup_proxy_env(http_proxy: str | None, https_proxy: str | None):
ok_http = test_proxy(http_proxy, test_http_url)
if ok_http:
os.environ["HTTP_PROXY"] = http_proxy
log.bind(tag=TAG).info(f"配置提供的Gemini HTTPS代理连通成功: {http_proxy}")
log.bind(tag=TAG).info(
f"Configured Gemini HTTP proxy connection successful: {http_proxy}")
else:
log.bind(tag=TAG).warning(f"配置提供的Gemini HTTP代理不可用: {http_proxy}")
log.bind(tag=TAG).warning(
f"Configured Gemini HTTP proxy not available: {http_proxy}")
if https_proxy:
ok_https = test_proxy(https_proxy, test_https_url)
if ok_https:
os.environ["HTTPS_PROXY"] = https_proxy
log.bind(tag=TAG).info(f"配置提供的Gemini HTTPS代理连通成功: {https_proxy}")
log.bind(tag=TAG).info(
f"Configured Gemini HTTPS proxy connection successful: {https_proxy}")
else:
log.bind(tag=TAG).warning(
f"配置提供的Gemini HTTPS代理不可用: {https_proxy}"
f"Configured Gemini HTTPS proxy not available: {https_proxy}"
)
# 如果https_proxy不可用,但http_proxy可用且能走通https,则复用http_proxy作为https_proxy
# If https_proxy is not available, but http_proxy is available and can handle https, reuse http_proxy as https_proxy
if ok_http and not ok_https:
if test_proxy(http_proxy, test_https_url):
os.environ["HTTPS_PROXY"] = http_proxy
ok_https = True
log.bind(tag=TAG).info(f"复用HTTP代理作为HTTPS代理: {http_proxy}")
log.bind(tag=TAG).info(
f"Reusing HTTP proxy as HTTPS proxy: {http_proxy}")
if not ok_http and not ok_https:
log.bind(tag=TAG).error(
f"Gemini 代理设置失败: HTTP 和 HTTPS 代理都不可用,请检查配置"
f"Gemini proxy setup failed: Both HTTP and HTTPS proxies are not available, please check configuration"
)
raise RuntimeError("HTTP 和 HTTPS 代理都不可用,请检查配置")
raise RuntimeError(
"Both HTTP and HTTPS proxies are not available, please check configuration")
class LLMProvider(LLMProviderBase):
@ -79,11 +86,11 @@ class LLMProvider(LLMProviderBase):
if http_proxy or https_proxy:
log.bind(tag=TAG).info(
f"检测到Gemini代理配置,开始测试代理连通性和设置代理环境..."
f"Gemini proxy configuration detected, starting proxy connectivity test and proxy environment setup..."
)
setup_proxy_env(http_proxy, https_proxy)
log.bind(tag=TAG).info(
f"Gemini 代理设置成功 - HTTP: {http_proxy}, HTTPS: {https_proxy}"
f"Gemini proxy setup successful - HTTP: {http_proxy}, HTTPS: {https_proxy}"
)
genai.configure(api_key=self.api_key)
self.model = genai.GenerativeModel(self.model_name)
@ -112,7 +119,8 @@ class LLMProvider(LLMProviderBase):
)
]
# Gemini文档提到,无需维护session-id,直接用dialogue拼接而成
# Gemini documentation mentions that there's no need to maintain session-id, just concatenate dialogue directly
def response(self, session_id, dialogue, **kwargs):
yield from self._generate(dialogue, None)
@ -122,7 +130,7 @@ class LLMProvider(LLMProviderBase):
def _generate(self, dialogue, tools):
role_map = {"assistant": "model", "user": "user"}
contents: list = []
# 拼接对话
# Concatenate dialogue
for m in dialogue:
r = m["role"]
@ -170,7 +178,7 @@ class LLMProvider(LLMProviderBase):
for chunk in stream:
cand = chunk.candidates[0]
for part in cand.content.parts:
# a) 函数调用-通常是最后一段话才是函数调用
# a) Function call - usually only the last part is a function call
if getattr(part, "function_call", None):
fc = part.function_call
yield None, [
@ -186,15 +194,16 @@ class LLMProvider(LLMProviderBase):
)
]
return
# b) 普通文本
# b) Plain text
if getattr(part, "text", None):
yield part.text if tools is None else (part.text, None)
finally:
if tools is not None:
yield None, None # function‑mode 结束,返回哑包
yield None, None # function‑mode end, return dummy packet
# Close stream, reserved for future conversation interruption functionality, official documentation recommends closing previous stream when interrupting conversation, which can effectively reduce quota billing and resource usage
# 关闭stream,预留后续打断对话功能的功能方法,官方文档推荐打断对话要关闭上一个流,可以有效减少配额计费和资源占用
@staticmethod
def _safe_finish_stream(stream: GenerateContentResponse):
if hasattr(stream, "resolve"):
@ -202,5 +211,5 @@ class LLMProvider(LLMProviderBase):
elif hasattr(stream, "close"):
stream.close() # Gemini SDK version < 0.5.0
else:
for _ in stream: # 兜底耗尽
pass
for _ in stream: # Fallback to exhaust
pass

View file

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

View file

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

View file

@ -5,10 +5,12 @@ from config.logger import setup_logging
from core.utils.util import check_model_key
from core.providers.llm.base import LLMProviderBase
TAG = __name__
logger = setup_logging()
class LLMProvider(LLMProviderBase):
def __init__(self, config):
self.model_name = config.get("model_name")
@ -17,10 +19,11 @@ class LLMProvider(LLMProviderBase):
self.base_url = config.get("base_url")
else:
self.base_url = config.get("url")
# 增加timeout的配置项,单位为秒
# Add timeout configuration item, unit is seconds
timeout = config.get("timeout", 300)
self.timeout = int(timeout) if timeout else 300
param_defaults = {
"max_tokens": (500, int),
"temperature": (0.7, lambda x: round(float(x), 1)),
@ -28,6 +31,7 @@ class LLMProvider(LLMProviderBase):
"frequency_penalty": (0, lambda x: round(float(x), 1)),
}
for param, (default, converter) in param_defaults.items():
value = config.get(param)
try:
@ -39,15 +43,18 @@ class LLMProvider(LLMProviderBase):
except (ValueError, TypeError):
setattr(self, param, default)
logger.debug(
f"意图识别参数初始化: {self.temperature}, {self.max_tokens}, {self.top_p}, {self.frequency_penalty}"
f"Intent recognition parameter initialization: {self.temperature}, {self.max_tokens}, {self.top_p}, {self.frequency_penalty}"
)
model_key_msg = check_model_key("LLM", self.api_key)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url, timeout=httpx.Timeout(self.timeout))
def response(self, session_id, dialogue, **kwargs):
try:
responses = self.client.chat.completions.create(
@ -62,10 +69,11 @@ class LLMProvider(LLMProviderBase):
),
)
is_active = True
for chunk in responses:
try:
# 检查是否存在有效的choice且content不为空
# Check if valid choice exists and content is not empty
delta = (
chunk.choices[0].delta
if getattr(chunk, "choices", None)
@ -75,7 +83,7 @@ class LLMProvider(LLMProviderBase):
except IndexError:
content = ""
if content:
# 处理标签跨多个chunk的情况
# Handle case where tags span multiple chunks
if "<think>" in content:
is_active = False
content = content.split("<think>")[0]
@ -85,30 +93,34 @@ class LLMProvider(LLMProviderBase):
if is_active:
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):
try:
stream = self.client.chat.completions.create(
model=self.model_name, messages=dialogue, stream=True, tools=functions
)
for chunk in stream:
# 检查是否存在有效的choice且content不为空
# Check if valid choice exists and content is not empty
if getattr(chunk, "choices", None):
yield chunk.choices[0].delta.content, chunk.choices[
0
].delta.tool_calls
# 存在 CompletionUsage 消息时,生成 Token 消耗 log
# When CompletionUsage message exists, generate Token consumption log
elif isinstance(getattr(chunk, "usage", None), CompletionUsage):
usage_info = getattr(chunk, "usage", None)
logger.bind(tag=TAG).info(
f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')},"
f"输出 {getattr(usage_info, 'completion_tokens', '未知')},"
f"共计 {getattr(usage_info, 'total_tokens', '未知')}"
f"Token consumption: input {getattr(usage_info, 'prompt_tokens', 'unknown')}, "
f"output {getattr(usage_info, 'completion_tokens', 'unknown')}, "
f"total {getattr(usage_info, 'total_tokens', 'unknown')}"
)
except Exception as e:
logger.bind(tag=TAG).error(f"Error in function call streaming: {e}")
yield f"【OpenAI服务响应异常: {e}】", None
yield f"[OpenAI Service Response Exception: {e}]", None

View file

@ -1,23 +1,28 @@
def get_system_prompt_for_function(functions: str) -> str:
"""
生成系统提示信息
:param functions: 可用的函数列表
:return: 系统提示信息
Generate system prompt message
:param functions: List of available functions
:return: System prompt message
"""
SYSTEM_PROMPT = f"""
====
TOOL USE
You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response.
You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
# Tool Use Formatting
Tool use is formatted using JSON-style tags. The tool name is enclosed in opening and closing tags, and each parameter is similarly enclosed within its own set of tags.
Here's the structure:
<tool_call>
{{
"name": "function name",
@ -29,20 +34,22 @@ Here's the structure:
}}
<tool_call>
For example:
if you got tool as follow
{{
"type": "function",
"function": {{
"name": "handle_exit_intent",
"description": "当用户想结束对话或需要退出系统时调用",
"description": "Called when user wants to end conversation or needs to exit system",
"parameters": {{
"type": "object",
"properties": {{
"say_goodbye": {{
"type": "string",
"description": "和用户友好结束对话的告别语",
"description": "Friendly goodbye message to end conversation with user",
}}
}},
"required": ["say_goodbye"],
@ -50,26 +57,33 @@ if you got tool as follow
}},
}}
you should respond with the following format:
<tool_call>
{{
"name": "handle_exit_intent",
"arguments": {{
"say_goodbye": "再见,祝您生活愉快!"
"say_goodbye": "Goodbye, have a pleasant life!"
}}
}}
</tool_call>
Always adhere to this format for the tool use to ensure proper parsing and execution.
# Tools
{functions}
# Tool Use Guidelines
1. Tools must be called in a separate message, Do not add thoughts when calling tools. The message must start with <tool_call> and end with </tool_call>, with the tool invocation JSON data in between. No additional response content is needed.
2. Choose the most appropriate tool based on the task and the tool descriptions provided. Assess if you need additional information to proceed, and which of the available tools would be most effective for gathering this information.
For example using the list_files tool is more effective than running a command like \`ls\` in the terminal. It's critical that you think about each available tool and use the one that best fits the current step in the task.
@ -84,20 +98,25 @@ Always adhere to this format for the tool use to ensure proper parsing and execu
6. ALWAYS wait for user confirmation after each tool use before proceeding. Never assume the success of a tool use without explicit confirmation of the result from the user.
7. Tool calls should contain no extra information. Only after receiving the tool's response should you integrate it into a complete reply.
It is crucial to proceed step-by-step, waiting for the user's message after each tool use before moving forward with the task. This approach allows you to:
1. Confirm the success of each step before proceeding.
2. Address any issues or errors that arise immediately.
3. Adapt your approach based on new information or unexpected results.
4. Ensure that each action builds correctly on the previous ones.
By waiting for and carefully considering the user's response after each tool use, you can react accordingly and make informed decisions about how to proceed with the task. This iterative process helps ensure the overall success and accuracy of your work.
====
USER CHAT CONTENT
The following additional message is the user's chat message, and should be followed to the best of your ability without interfering with the TOOL USE guidelines.
"""
return SYSTEM_PROMPT
"""
return SYSTEM_PROMPT

View file

@ -3,6 +3,7 @@ from openai import OpenAI
import json
from core.providers.llm.base import LLMProviderBase
TAG = __name__
logger = setup_logging()
@ -12,7 +13,7 @@ class LLMProvider(LLMProviderBase):
self.model_name = config.get("model_name")
self.base_url = config.get("base_url", "http://localhost:9997")
# Initialize OpenAI client with Xinference base URL
# 如果没有v1,增加v1
# If there's no v1, add v1
if not self.base_url.endswith("/v1"):
self.base_url = f"{self.base_url}/v1"
@ -23,11 +24,14 @@ class LLMProvider(LLMProviderBase):
try:
self.client = OpenAI(
base_url=self.base_url,
api_key="xinference", # Xinference has a similar setup to Ollama where it doesn't need an actual key
# Xinference has a similar setup to Ollama where it doesn't need an actual key
api_key="xinference",
)
logger.bind(tag=TAG).info("Xinference client initialized successfully")
logger.bind(tag=TAG).info(
"Xinference client initialized successfully")
except Exception as e:
logger.bind(tag=TAG).error(f"Error initializing Xinference client: {e}")
logger.bind(tag=TAG).error(
f"Error initializing Xinference client: {e}")
raise
def response(self, session_id, dialogue, **kwargs):
@ -46,7 +50,8 @@ class LLMProvider(LLMProviderBase):
if getattr(chunk, "choices", None)
else None
)
content = delta.content if hasattr(delta, "content") else ""
content = delta.content if hasattr(
delta, "content") else ""
if content:
if "<think>" in content:
is_active = False
@ -60,8 +65,9 @@ class LLMProvider(LLMProviderBase):
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服务响应异常】"
logger.bind(tag=TAG).error(
f"Error in Xinference response generation: {e}")
yield "[Xinference Service Response Exception]"
def response_with_functions(self, session_id, dialogue, functions=None):
try:
@ -91,8 +97,9 @@ class LLMProvider(LLMProviderBase):
yield None, tool_calls
except Exception as e:
logger.bind(tag=TAG).error(f"Error in Xinference function call: {e}")
logger.bind(tag=TAG).error(
f"Error in Xinference function call: {e}")
yield {
"type": "content",
"content": f"【Xinference服务响应异常: {str(e)}】",
}
"content": f"[Xinference Service Response Exception: {str(e)}]",
}

View file

@ -1,5 +1,4 @@
import traceback
from ..base import MemoryProviderBase, logger
from mem0 import MemoryClient
from core.utils.util import check_model_key
@ -22,10 +21,13 @@ class MemoryProvider(MemoryProviderBase):
try:
self.client = MemoryClient(api_key=self.api_key)
logger.bind(tag=TAG).info("成功连接到 Mem0ai 服务")
logger.bind(tag=TAG).info(
"Successfully connected to Mem0ai service")
except Exception as e:
logger.bind(tag=TAG).error(f"连接到 Mem0ai 服务时发生错误: {str(e)}")
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
logger.bind(tag=TAG).error(
f"Error occurred while connecting to Mem0ai service: {str(e)}")
logger.bind(tag=TAG).error(
f"Detailed error: {traceback.format_exc()}")
self.use_mem0 = False
async def save_memory(self, msgs):
@ -46,7 +48,7 @@ class MemoryProvider(MemoryProviderBase):
)
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
except Exception as e:
logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to save memory: {str(e)}")
return None
async def query_memory(self, query: str) -> str:
@ -73,7 +75,8 @@ class MemoryProvider(MemoryProviderBase):
memory = entry.get("memory", "")
if timestamp and memory:
# Store tuple of (timestamp, formatted_string) for sorting
memories.append((timestamp, f"[{formatted_time}] {memory}"))
memories.append(
(timestamp, f"[{formatted_time}] {memory}"))
# Sort by timestamp in descending order (newest first)
memories.sort(key=lambda x: x[0], reverse=True)
@ -83,5 +86,5 @@ class MemoryProvider(MemoryProviderBase):
logger.bind(tag=TAG).debug(f"Query results: {memories_str}")
return memories_str
except Exception as e:
logger.bind(tag=TAG).error(f"查询记忆失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to query memory: {str(e)}")
return ""

View file

@ -9,81 +9,80 @@ from core.utils.util import check_model_key
short_term_memory_prompt = """
# 时空记忆编织者
# Temporal Memory Weaver
## 核心使命
构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹
根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务
## Core Mission
Build a growable dynamic memory network that retains key information within limited space while intelligently maintaining information evolution trajectories
Summarize important user information based on conversation records to provide more personalized services in future conversations
## 记忆法则
### 1. 三维度记忆评估(每次更新必执行)
| 维度 | 评估标准 | 权重分 |
|------------|---------------------------|--------|
| 时效性 | 信息新鲜度(按对话轮次) | 40% |
| 情感强度 | 含💖标记/重复提及次数 | 35% |
| 关联密度 | 与其他信息的连接数量 | 25% |
## Memory Rules
### 1. Three-Dimensional Memory Assessment (Must execute on every update)
| Dimension | Assessment Criteria | Weight |
|----------------|----------------------------------|--------|
| Timeliness | Information freshness (by turns) | 40% |
| Emotional Intensity | Contains 💖 marks/repeat mentions | 35% |
| Association Density | Number of connections to other info | 25% |
### 2. 动态更新机制
**名字变更处理示例:**
原始记忆:"曾用名": ["张三"], "现用名": "张三丰"
触发条件:当检测到「我叫X」「称呼我Y」等命名信号时
操作流程:
1. 将旧名移入"曾用名"列表
2. 记录命名时间轴:"2024-02-15 14:32:启用张三丰"
3. 在记忆立方追加:「从张三到张三丰的身份蜕变」
### 2. Dynamic Update Mechanism
**Name Change Handling Example:**
Original memory: "former_names": ["Zhang San"], "current_name": "Zhang Sanfeng"
Trigger condition: When detecting naming signals like "My name is X" "Call me Y"
Operation process:
1. Move old name to "former_names" list
2. Record naming timeline: "2024-02-15 14:32: Activated Zhang Sanfeng"
3. Append to memory cube: "Identity transformation from Zhang San to Zhang Sanfeng"
### 3. 空间优化策略
- **信息压缩术**:用符号体系提升密度
- ✅"张三丰[北/软工/🐱]"
- ❌"北京软件工程师,养猫"
- **淘汰预警**:当总字数≥900时触发
1. 删除权重分<60且3轮未提及的信息
2. 合并相似条目(保留时间戳最近的)
### 3. Space Optimization Strategy
- **Information Compression**: Use symbol system to enhance density
- ✅"Zhang Sanfeng[Beijing/SoftEng/🐱]"
- ❌"Beijing software engineer, owns cat"
- **Elimination Warning**: Triggered when total word count ≥900
1. Delete info with weight score <60 and not mentioned for 3 rounds
2. Merge similar entries (keep most recent timestamp)
## 记忆结构
输出格式必须为可解析的json字符串,不需要解释、注释和说明,保存记忆时仅从对话提取信息,不要混入示例内容
## Memory Structure
Output format must be parseable JSON string, no explanations, comments or descriptions needed, only extract information from conversations when saving memory, do not mix in example content
```json
{
"时空档案": {
"身份图谱": {
"现用名": "",
"特征标记": []
"temporal_profile": {
"identity_map": {
"current_name": "",
"feature_tags": []
},
"记忆立方": [
"memory_cube": [
{
"事件": "入职新公司",
"时间戳": "2024-03-20",
"情感值": 0.9,
"关联项": ["下午茶"],
"保鲜期": 30
"event": "Started new job",
"timestamp": "2024-03-20",
"emotional_value": 0.9,
"related_items": ["afternoon tea"],
"freshness_period": 30
}
]
},
"关系网络": {
"高频话题": {"职场": 12},
"暗线联系": [""]
"relationship_network": {
"frequent_topics": {"workplace": 12},
"hidden_connections": [""]
},
"待响应": {
"紧急事项": ["需立即处理的任务"],
"潜在关怀": ["可主动提供的帮助"]
"pending_response": {
"urgent_matters": ["Tasks requiring immediate attention"],
"potential_care": ["Help that can be proactively offered"]
},
"高光语录": [
"最打动人心的瞬间,强烈的情感表达,user的原话"
"highlight_quotes": [
"Most touching moments, strong emotional expressions, user's original words"
]
}
```
"""
short_term_memory_prompt_only_content = """
你是一个经验丰富的记忆总结者,擅长将对话内容进行总结摘要,遵循以下规则:
1、总结user的重要信息,以便在未来的对话中提供更个性化的服务
2、不要重复总结,不要遗忘之前记忆,除非原来的记忆超过了1800字内,否则不要遗忘、不要压缩用户的历史记忆
3、用户操控的设备音量、播放音乐、天气、退出、不想对话等和用户本身无关的内容,这些信息不需要加入到总结中
4、聊天内容中的今天的日期时间、今天的天气情况与用户事件无关的数据,这些信息如果当成记忆存储会影响后序对话,这些信息不需要加入到总结中
5、不要把设备操控的成果结果和失败结果加入到总结中,也不要把用户的一些废话加入到总结中
6、不要为了总结而总结,如果用户的聊天没有意义,请返回原来的历史记录也是可以的
7、只需要返回总结摘要,严格控制在1800字内
8、不要包含代码、xml,不需要解释、注释和说明,保存记忆时仅从对话提取信息,不要混入示例内容
You are an experienced memory summarizer, skilled at summarizing conversation content, following these rules:
1. Summarize important user information to provide more personalized services in future conversations
2. Don't repeat summaries, don't forget previous memories, unless original memory exceeds 1800 words, otherwise don't forget or compress user's historical memory
3. User device control content like volume, music playback, weather, exit, not wanting to chat etc. that are unrelated to the user themselves, this information doesn't need to be included in the summary
4. Don't include device control success/failure results in the summary, and don't include user's meaningless chatter
5. Don't summarize for the sake of summarizing, if user's chat is meaningless, returning the original historical record is acceptable
6. Only return summary digest, strictly control within 1800 words
7. Don't include code, xml, no explanations, comments or descriptions needed, only extract information from conversations when saving memory, don't mix in example content
"""
@ -99,7 +98,7 @@ def extract_json_data(json_code):
except Exception as e:
print("Error:", e)
return ""
jsonData = json_code[start + 7 : end]
jsonData = json_code[start + 7: end]
return jsonData
@ -122,7 +121,7 @@ class MemoryProvider(MemoryProviderBase):
self.load_memory(summary_memory)
def load_memory(self, summary_memory):
# api获取到总结记忆后直接返回
# Return directly after API retrieves summary memory
if summary_memory or not self.save_to_file:
self.short_memory = summary_memory
return
@ -144,11 +143,18 @@ class MemoryProvider(MemoryProviderBase):
yaml.dump(all_memory, f, allow_unicode=True)
async def save_memory(self, msgs):
# 打印使用的模型信息
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
logger.bind(tag=TAG).debug(f"使用记忆保存模型: {model_info}")
# Check if llm is set
if not hasattr(self, 'llm') or self.llm is None:
logger.bind(tag=TAG).error("LLM is not set for memory provider")
return None
# Print model information being used
model_info = getattr(self.llm, "model_name",
str(self.llm.__class__.__name__))
logger.bind(tag=TAG).debug(f"Using memory saving model: {model_info}")
api_key = getattr(self.llm, "api_key", None)
memory_key_msg = check_model_key("记忆总结专用LLM", api_key)
memory_key_msg = check_model_key(
"Memory Summary Dedicated LLM", api_key)
if memory_key_msg:
logger.bind(tag=TAG).error(memory_key_msg)
if self.llm is None:
@ -165,12 +171,12 @@ class MemoryProvider(MemoryProviderBase):
elif msg.role == "assistant":
msgStr += f"Assistant: {msg.content}\n"
if self.short_memory and len(self.short_memory) > 0:
msgStr += "历史记忆:\n"
msgStr += "Historical Memory:\n"
msgStr += self.short_memory
# 当前时间
# Current time
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
msgStr += f"当前时间:{time_str}"
msgStr += f"Current time: {time_str}"
if self.save_to_file:
result = self.llm.response_no_stream(
@ -181,7 +187,7 @@ class MemoryProvider(MemoryProviderBase):
)
json_str = extract_json_data(result)
try:
json.loads(json_str) # 检查json格式是否正确
json.loads(json_str) # Check if JSON format is correct
self.short_memory = json_str
self.save_memory_to_file()
except Exception as e:
@ -194,9 +200,10 @@ class MemoryProvider(MemoryProviderBase):
temperature=0.2,
)
save_mem_local_short(self.role_id, result)
logger.bind(tag=TAG).info(f"Save memory successful - Role: {self.role_id}")
logger.bind(tag=TAG).info(
f"Save memory successful - Role: {self.role_id}")
return self.short_memory
async def query_memory(self, query: str) -> str:
return self.short_memory
return self.short_memory

View file

@ -1,20 +1,21 @@
"""
不使用记忆,可以选择此模块
If not using memory, you can choose this module
"""
from ..base import MemoryProviderBase, logger
TAG = __name__
class MemoryProvider(MemoryProviderBase):
def __init__(self, config, summary_memory=None):
super().__init__(config)
async def save_memory(self, msgs):
logger.bind(tag=TAG).debug("nomem mode: No memory saving is performed.")
return None
async def query_memory(self, query: str) -> str:
logger.bind(tag=TAG).debug("nomem mode: No memory query is performed.")
return ""
return ""

View file

@ -1,4 +1,4 @@
"""基础工具定义模块"""
"""Base tool definition module"""
from .tool_types import ToolType, ToolDefinition
from .tool_executor import ToolExecutor

View file

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

View file

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

View file

@ -1,4 +1,4 @@
"""设备端IoT工具模块"""
"""Device-side IoT tool module"""
from .iot_descriptor import IotDescriptor
from .iot_handler import handleIotDescriptors, handleIotStatus

View file

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

View file

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

View file

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

View file

@ -1,6 +1,7 @@
"""设备端MCP工具模块"""
"""Device-side MCP tool module"""
from .mcp_client import MCPClient
from .mcp_handler import (
send_mcp_message,
handle_mcp_message,
@ -8,6 +9,7 @@ from .mcp_handler import (
send_mcp_tools_list_request,
call_mcp_tool,
)
from .mcp_executor import DeviceMCPExecutor
__all__ = [

View file

@ -1,4 +1,4 @@
"""设备端MCP客户端定义"""
"""Device-side MCP client definition"""
import asyncio
from concurrent.futures import Future
@ -8,10 +8,9 @@ from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
class MCPClient:
"""设备端MCP客户端,用于管理MCP状态和工具"""
"""Device-side MCP client for managing MCP state and tools"""
def __init__(self):
self.tools = {} # sanitized_name -> tool_data
self.name_mapping = {}
@ -28,7 +27,7 @@ class MCPClient:
# Check if the cache is valid
if self._cached_available_tools is not None:
return self._cached_available_tools
# If cache is not valid, regenerate the list
result = []
for tool_name, tool_data in self.tools.items():
@ -42,7 +41,7 @@ class MCPClient:
},
}
result.append({"type": "function", "function": function_def})
self._cached_available_tools = result # Store the generated list in cache
return result
@ -59,9 +58,7 @@ class MCPClient:
sanitized_name = sanitize_tool_name(tool_data["name"])
self.tools[sanitized_name] = tool_data
self.name_mapping[sanitized_name] = tool_data["name"]
self._cached_available_tools = (
None # Invalidate the cache when a tool is added
)
self._cached_available_tools = None # Invalidate the cache when a tool is added
async def get_next_id(self) -> int:
async with self.lock:
@ -90,4 +87,4 @@ class MCPClient:
async def cleanup_call_result(self, id: int):
async with self.lock:
if id in self.call_results:
self.call_results.pop(id)
self.call_results.pop(id)

View file

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

View file

@ -1,4 +1,4 @@
"""设备端MCP客户端支持模块"""
"""Device-side MCP client support module"""
import json
import asyncio
@ -12,111 +12,28 @@ TAG = __name__
logger = setup_logging()
class MCPClient:
"""设备端MCP客户端,用于管理MCP状态和工具"""
def __init__(self):
self.tools = {} # sanitized_name -> tool_data
self.name_mapping = {}
self.ready = False
self.call_results = {} # To store Futures for tool call responses
self.next_id = 1
self.lock = asyncio.Lock()
self._cached_available_tools = None # Cache for get_available_tools
def has_tool(self, name: str) -> bool:
return name in self.tools
def get_available_tools(self) -> list:
# Check if the cache is valid
if self._cached_available_tools is not None:
return self._cached_available_tools
# If cache is not valid, regenerate the list
result = []
for tool_name, tool_data in self.tools.items():
function_def = {
"name": tool_name,
"description": tool_data["description"],
"parameters": {
"type": tool_data["inputSchema"].get("type", "object"),
"properties": tool_data["inputSchema"].get("properties", {}),
"required": tool_data["inputSchema"].get("required", []),
},
}
result.append({"type": "function", "function": function_def})
self._cached_available_tools = result # Store the generated list in cache
return result
async def is_ready(self) -> bool:
async with self.lock:
return self.ready
async def set_ready(self, status: bool):
async with self.lock:
self.ready = status
async def add_tool(self, tool_data: dict):
async with self.lock:
sanitized_name = sanitize_tool_name(tool_data["name"])
self.tools[sanitized_name] = tool_data
self.name_mapping[sanitized_name] = tool_data["name"]
self._cached_available_tools = (
None # Invalidate the cache when a tool is added
)
async def get_next_id(self) -> int:
async with self.lock:
current_id = self.next_id
self.next_id += 1
return current_id
async def register_call_result_future(self, id: int, future: Future):
async with self.lock:
self.call_results[id] = future
async def resolve_call_result(self, id: int, result: any):
async with self.lock:
if id in self.call_results:
future = self.call_results.pop(id)
if not future.done():
future.set_result(result)
async def reject_call_result(self, id: int, exception: Exception):
async with self.lock:
if id in self.call_results:
future = self.call_results.pop(id)
if not future.done():
future.set_exception(exception)
async def cleanup_call_result(self, id: int):
async with self.lock:
if id in self.call_results:
self.call_results.pop(id)
async def send_mcp_message(conn, payload: dict):
"""Helper to send MCP messages, encapsulating common logic."""
if not conn.features.get("mcp"):
logger.bind(tag=TAG).warning("客户端不支持MCP,无法发送MCP消息")
logger.bind(tag=TAG).warning(
"Client does not support MCP, cannot send MCP message")
return
message = json.dumps({"type": "mcp", "payload": payload})
try:
await conn.websocket.send(message)
logger.bind(tag=TAG).info(f"成功发送MCP消息: {message}")
logger.bind(tag=TAG).info(f"Successfully sent MCP message: {message}")
except Exception as e:
logger.bind(tag=TAG).error(f"发送MCP消息失败: {e}")
logger.bind(tag=TAG).error(f"Failed to send MCP message: {e}")
async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
"""处理MCP消息,包括初始化、工具列表和工具调用响应等"""
logger.bind(tag=TAG).info(f"处理MCP消息: {str(payload)[:100]}")
async def handle_mcp_message(conn, mcp_client, payload: dict):
"""Handle MCP messages, including initialization, tool list and tool call responses"""
logger.bind(tag=TAG).info(f"Handling MCP message: {str(payload)[:100]}")
if not isinstance(payload, dict):
logger.bind(tag=TAG).error("MCP消息缺少payload字段或格式错误")
logger.bind(tag=TAG).error(
"MCP message missing payload field or format error")
return
# Handle result
@ -127,32 +44,32 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
# Check for tool call response first
if msg_id in mcp_client.call_results:
logger.bind(tag=TAG).debug(
f"收到工具调用响应,ID: {msg_id}, 结果: {result}"
f"Received tool call response, ID: {msg_id}, Result: {result}"
)
await mcp_client.resolve_call_result(msg_id, result)
return
if msg_id == 1: # mcpInitializeID
logger.bind(tag=TAG).debug("收到MCP初始化响应")
logger.bind(tag=TAG).debug("Received MCP initialization response")
server_info = result.get("serverInfo")
if isinstance(server_info, dict):
name = server_info.get("name")
version = server_info.get("version")
logger.bind(tag=TAG).info(
f"客户端MCP服务器信息: name={name}, version={version}"
f"Client MCP server info: name={name}, version={version}"
)
return
elif msg_id == 2: # mcpToolsListID
logger.bind(tag=TAG).debug("收到MCP工具列表响应")
logger.bind(tag=TAG).debug("Received MCP tools list response")
if isinstance(result, dict) and "tools" in result:
tools_data = result["tools"]
if not isinstance(tools_data, list):
logger.bind(tag=TAG).error("工具列表格式错误")
logger.bind(tag=TAG).error("Tools list format error")
return
logger.bind(tag=TAG).info(
f"客户端设备支持的工具数量: {len(tools_data)}"
f"Client device supported tools count: {len(tools_data)}"
)
for i, tool in enumerate(tools_data):
@ -161,12 +78,14 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
name = tool.get("name", "")
description = tool.get("description", "")
input_schema = {"type": "object", "properties": {}, "required": []}
input_schema = {"type": "object",
"properties": {}, "required": []}
if "inputSchema" in tool and isinstance(tool["inputSchema"], dict):
schema = tool["inputSchema"]
input_schema["type"] = schema.get("type", "object")
input_schema["properties"] = schema.get("properties", {})
input_schema["properties"] = schema.get(
"properties", {})
input_schema["required"] = [
s for s in schema.get("required", []) if isinstance(s, str)
]
@ -176,14 +95,15 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
"description": description,
"inputSchema": input_schema,
}
await mcp_client.add_tool(new_tool)
logger.bind(tag=TAG).debug(f"客户端工具 #{i+1}: {name}")
# 替换所有工具描述中的工具名称
await mcp_client.add_tool(new_tool)
logger.bind(tag=TAG).debug(f"Client tool #{i+1}: {name}")
# Replace all tool names in tool descriptions
for tool_data in mcp_client.tools.values():
if "description" in tool_data:
description = tool_data["description"]
# 遍历所有工具名称进行替换
# Iterate through all tool names for replacement
for (
sanitized_name,
original_name,
@ -195,13 +115,15 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
next_cursor = result.get("nextCursor", "")
if next_cursor:
logger.bind(tag=TAG).info(f"有更多工具,nextCursor: {next_cursor}")
logger.bind(tag=TAG).info(
f"More tools available, nextCursor: {next_cursor}")
await send_mcp_tools_list_continue_request(conn, next_cursor)
else:
await mcp_client.set_ready(True)
logger.bind(tag=TAG).info("所有工具已获取,MCP客户端准备就绪")
logger.bind(tag=TAG).info(
"All tools retrieved, MCP client ready")
# 刷新工具缓存,确保MCP工具被包含在函数列表中
# Refresh tool cache to ensure MCP tools are included in function list
if hasattr(conn, "func_handler") and conn.func_handler:
conn.func_handler.tool_manager.refresh_tools()
conn.func_handler.current_support_functions()
@ -210,26 +132,24 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
# Handle method calls (requests from the client)
elif "method" in payload:
method = payload["method"]
logger.bind(tag=TAG).info(f"收到MCP客户端请求: {method}")
logger.bind(tag=TAG).info(f"Received MCP client request: {method}")
elif "error" in payload:
error_data = payload["error"]
error_msg = error_data.get("message", "未知错误")
logger.bind(tag=TAG).error(f"收到MCP错误响应: {error_msg}")
error_msg = error_data.get("message", "Unknown error")
logger.bind(tag=TAG).error(f"Received MCP error response: {error_msg}")
msg_id = int(payload.get("id", 0))
if msg_id in mcp_client.call_results:
await mcp_client.reject_call_result(
msg_id, Exception(f"MCP错误: {error_msg}")
msg_id, Exception(f"MCP error: {error_msg}")
)
async def send_mcp_initialize_message(conn):
"""发送MCP初始化消息"""
"""Send MCP initialization message"""
vision_url = get_vision_url(conn.config)
# 密钥生成token
# Generate token using key
auth = AuthToken(conn.config["server"]["auth_key"])
token = auth.generate_token(conn.headers.get("device-id"))
@ -255,66 +175,68 @@ async def send_mcp_initialize_message(conn):
},
},
}
logger.bind(tag=TAG).info("发送MCP初始化消息")
logger.bind(tag=TAG).info("Sending MCP initialization message")
await send_mcp_message(conn, payload)
async def send_mcp_tools_list_request(conn):
"""发送MCP工具列表请求"""
"""Send MCP tools list request"""
payload = {
"jsonrpc": "2.0",
"id": 2, # mcpToolsListID
"method": "tools/list",
}
logger.bind(tag=TAG).debug("发送MCP工具列表请求")
logger.bind(tag=TAG).debug("Sending MCP tools list request")
await send_mcp_message(conn, payload)
async def send_mcp_tools_list_continue_request(conn, cursor: str):
"""发送带有cursor的MCP工具列表请求"""
"""Send MCP tools list request with cursor"""
payload = {
"jsonrpc": "2.0",
"id": 2, # mcpToolsListID (same ID for continuation)
"method": "tools/list",
"params": {"cursor": cursor},
}
logger.bind(tag=TAG).info(f"发送带cursor的MCP工具列表请求: {cursor}")
logger.bind(tag=TAG).info(
f"Sending MCP tools list request with cursor: {cursor}")
await send_mcp_message(conn, payload)
async def call_mcp_tool(
conn, mcp_client: MCPClient, tool_name: str, args: str = "{}", timeout: int = 30
conn, mcp_client, tool_name: str, args: str = "{}", timeout: int = 30
):
"""
调用指定的工具,并等待响应
"""
"""Call the specified tool and wait for response"""
if not await mcp_client.is_ready():
raise RuntimeError("MCP客户端尚未准备就绪")
raise RuntimeError("MCP client is not ready yet")
if not mcp_client.has_tool(tool_name):
raise ValueError(f"工具 {tool_name} 不存在")
raise ValueError(f"Tool {tool_name} does not exist")
tool_call_id = await mcp_client.get_next_id()
result_future = asyncio.Future()
await mcp_client.register_call_result_future(tool_call_id, result_future)
# 处理参数
# Handle parameters
try:
if isinstance(args, str):
# 确保字符串是有效的JSON
# Ensure string is valid JSON
if not args.strip():
arguments = {}
else:
try:
# 尝试直接解析
# Try to parse directly
arguments = json.loads(args)
except json.JSONDecodeError:
# 如果解析失败,尝试合并多个JSON对象
# If parsing fails, try to merge multiple JSON objects
try:
# 使用正则表达式匹配所有JSON对象
# Use regex to match all JSON objects
json_objects = re.findall(r"\{[^{}]*\}", args)
if len(json_objects) > 1:
# 合并所有JSON对象
# Merge all JSON objects
merged_dict = {}
for json_str in json_objects:
try:
@ -326,29 +248,35 @@ async def call_mcp_tool(
if merged_dict:
arguments = merged_dict
else:
raise ValueError(f"无法解析任何有效的JSON对象: {args}")
raise ValueError(
f"Cannot parse any valid JSON objects: {args}")
else:
raise ValueError(f"参数JSON解析失败: {args}")
raise ValueError(
f"Parameter JSON parsing failed: {args}")
except Exception as e:
logger.bind(tag=TAG).error(
f"参数JSON解析失败: {str(e)}, 原始参数: {args}"
f"Parameter JSON parsing failed: {str(e)}, Original parameters: {args}"
)
raise ValueError(f"参数JSON解析失败: {str(e)}")
raise ValueError(
f"Parameter JSON parsing failed: {str(e)}")
elif isinstance(args, dict):
arguments = args
else:
raise ValueError(f"参数类型错误,期望字符串或字典,实际类型: {type(args)}")
raise ValueError(
f"Parameter type error, expected string or dictionary, actual type: {type(args)}")
# 确保参数是字典类型
# Ensure parameters are dictionary type
if not isinstance(arguments, dict):
raise ValueError(f"参数必须是字典类型,实际类型: {type(arguments)}")
raise ValueError(
f"Parameters must be dictionary type, actual type: {type(arguments)}")
except Exception as e:
if not isinstance(e, ValueError):
raise ValueError(f"参数处理失败: {str(e)}")
raise ValueError(f"Parameter processing failed: {str(e)}")
raise e
actual_name = mcp_client.name_mapping.get(tool_name, tool_name)
payload = {
"jsonrpc": "2.0",
"id": tool_call_id,
@ -356,33 +284,36 @@ async def call_mcp_tool(
"params": {"name": actual_name, "arguments": arguments},
}
logger.bind(tag=TAG).info(f"发送客户端mcp工具调用请求: {actual_name},参数: {args}")
logger.bind(tag=TAG).info(
f"Sending client MCP tool call request: {actual_name}, Parameters: {args}")
await send_mcp_message(conn, payload)
try:
# Wait for response or timeout
raw_result = await asyncio.wait_for(result_future, timeout=timeout)
logger.bind(tag=TAG).info(
f"客户端mcp工具调用 {actual_name} 成功,原始结果: {raw_result}"
f"Client MCP tool call {actual_name} successful, Raw result: {raw_result}"
)
if isinstance(raw_result, dict):
if raw_result.get("isError") is True:
error_msg = raw_result.get(
"error", "工具调用返回错误,但未提供具体错误信息"
"error", "Tool call returned error but did not provide specific error information"
)
raise RuntimeError(f"工具调用错误: {error_msg}")
raise RuntimeError(f"Tool call error: {error_msg}")
content = raw_result.get("content")
if isinstance(content, list) and len(content) > 0:
if isinstance(content[0], dict) and "text" in content[0]:
# 直接返回文本内容,不进行JSON解析
# Return text content directly without JSON parsing
return content[0]["text"]
# 如果结果不是预期的格式,将其转换为字符串
# If result is not in expected format, convert to string
return str(raw_result)
except asyncio.TimeoutError:
await mcp_client.cleanup_call_result(tool_call_id)
raise TimeoutError("工具调用请求超时")
raise TimeoutError("Tool call request timeout")
except Exception as e:
await mcp_client.cleanup_call_result(tool_call_id)
raise e

View file

@ -1,7 +1,9 @@
"""MCP接入点工具模块"""
"""MCP endpoint tool module"""
from .mcp_endpoint_executor import MCPEndpointExecutor
from .mcp_endpoint_client import MCPEndpointClient
from .mcp_endpoint_handler import (
connect_mcp_endpoint,
send_mcp_endpoint_initialize,

View file

@ -1,4 +1,4 @@
"""MCP接入点客户端定义"""
"""MCP endpoint client definition"""
import asyncio
from concurrent.futures import Future
@ -8,10 +8,9 @@ from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
class MCPEndpointClient:
"""MCP接入点客户端,用于管理MCP接入点状态和工具"""
"""MCP endpoint client for managing MCP endpoint state and tools"""
def __init__(self, conn=None):
self.conn = conn
self.tools = {} # sanitized_name -> tool_data
@ -21,7 +20,7 @@ class MCPEndpointClient:
self.next_id = 1
self.lock = asyncio.Lock()
self._cached_available_tools = None # Cache for get_available_tools
self.websocket = None # WebSocket连接
self.websocket = None # WebSocket connection
def has_tool(self, name: str) -> bool:
return name in self.tools
@ -30,7 +29,7 @@ class MCPEndpointClient:
# Check if the cache is valid
if self._cached_available_tools is not None:
return self._cached_available_tools
# If cache is not valid, regenerate the list
result = []
for tool_name, tool_data in self.tools.items():
@ -44,7 +43,7 @@ class MCPEndpointClient:
},
}
result.append({"type": "function", "function": function_def})
self._cached_available_tools = result # Store the generated list in cache
return result
@ -61,9 +60,7 @@ class MCPEndpointClient:
sanitized_name = sanitize_tool_name(tool_data["name"])
self.tools[sanitized_name] = tool_data
self.name_mapping[sanitized_name] = tool_data["name"]
self._cached_available_tools = (
None # Invalidate the cache when a tool is added
)
self._cached_available_tools = None # Invalidate the cache when a tool is added
async def get_next_id(self) -> int:
async with self.lock:
@ -95,18 +92,18 @@ class MCPEndpointClient:
self.call_results.pop(id)
def set_websocket(self, websocket):
"""设置WebSocket连接"""
"""Set WebSocket connection"""
self.websocket = websocket
async def send_message(self, message: str):
"""发送消息到MCP接入点"""
"""Send message to MCP endpoint"""
if self.websocket:
await self.websocket.send(message)
else:
raise RuntimeError("WebSocket连接未建立")
raise RuntimeError("WebSocket connection not established")
async def close(self):
"""关闭WebSocket连接"""
"""Close WebSocket connection"""
if self.websocket:
await self.websocket.close()
self.websocket = None
self.websocket = None

View file

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

View file

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

View file

@ -1,4 +1,4 @@
"""服务端MCP工具模块"""
"""Server-side MCP tool module"""
from .mcp_manager import ServerMCPManager
from .mcp_executor import ServerMCPExecutor

View file

@ -1,7 +1,6 @@
"""服务端MCP客户端"""
"""Server-side MCP client"""
from __future__ import annotations
from datetime import timedelta
import asyncio
import os
@ -9,7 +8,6 @@ import shutil
import concurrent.futures
from contextlib import AsyncExitStack
from typing import Optional, List, Dict, Any
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp.client.sse import sse_client
@ -20,42 +18,40 @@ TAG = __name__
class ServerMCPClient:
"""服务端MCP客户端,用于连接和管理MCP服务"""
"""Server-side MCP client for connecting and managing MCP services"""
def __init__(self, config: Dict[str, Any]):
"""初始化服务端MCP客户端
"""Initialize server-side MCP client
Args:
config: MCP服务配置字典
config: MCP service configuration dictionary
"""
self.logger = setup_logging()
self.config = config
self._worker_task: Optional[asyncio.Task] = None
self._ready_evt = asyncio.Event()
self._shutdown_evt = asyncio.Event()
self.session: Optional[ClientSession] = None
self.tools: List = [] # 原始工具对象
self.tools: List = [] # Original tool objects
self.tools_dict: Dict[str, Any] = {}
self.name_mapping: Dict[str, str] = {}
async def initialize(self):
"""初始化MCP客户端连接"""
"""Initialize MCP client connection"""
if self._worker_task:
return
self._worker_task = asyncio.create_task(
self._worker(), name="ServerMCPClientWorker"
)
await self._ready_evt.wait()
await self._ready_evt.wait()
self.logger.bind(tag=TAG).info(
f"服务端MCP客户端已连接,可用工具: {[name for name in self.name_mapping.values()]}"
f"Server-side MCP client connected, available tools: {[name for name in self.name_mapping.values()]}"
)
async def cleanup(self):
"""清理MCP客户端资源"""
"""Clean up MCP client resources"""
if not self._worker_task:
return
@ -63,26 +59,27 @@ class ServerMCPClient:
try:
await asyncio.wait_for(self._worker_task, timeout=20)
except (asyncio.TimeoutError, Exception) as e:
self.logger.bind(tag=TAG).error(f"服务端MCP客户端关闭错误: {e}")
self.logger.bind(tag=TAG).error(
f"Server-side MCP client shutdown error: {e}")
finally:
self._worker_task = None
def has_tool(self, name: str) -> bool:
"""检查是否包含指定工具
"""Check if the specified tool is included
Args:
name: 工具名称
name: Tool name
Returns:
bool: 是否包含该工具
bool: Whether the tool is included
"""
return name in self.tools_dict
def get_available_tools(self) -> List[Dict[str, Any]]:
"""获取所有可用工具的定义
"""Get definitions of all available tools
Returns:
List[Dict[str, Any]]: 工具定义列表
List[Dict[str, Any]]: Tool definition list
"""
return [
{
@ -97,20 +94,20 @@ class ServerMCPClient:
]
async def call_tool(self, name: str, args: dict) -> Any:
"""调用指定工具
"""Call the specified tool
Args:
name: 工具名称
args: 工具参数
name: Tool name
args: Tool parameters
Returns:
Any: 工具执行结果
Any: Tool execution result
Raises:
RuntimeError: 客户端未初始化时抛出
RuntimeError: Thrown when client is not initialized
"""
if not self.session:
raise RuntimeError("服务端MCP客户端未初始化")
raise RuntimeError("Server-side MCP client not initialized")
real_name = self.name_mapping.get(name, name)
loop = self._worker_task.get_loop()
@ -119,35 +116,36 @@ class ServerMCPClient:
if loop is asyncio.get_running_loop():
return await coro
fut: concurrent.futures.Future = asyncio.run_coroutine_threadsafe(coro, loop)
fut: concurrent.futures.Future = asyncio.run_coroutine_threadsafe(
coro, loop)
return await asyncio.wrap_future(fut)
def is_connected(self) -> bool:
"""检查MCP客户端是否连接正常
"""Check if MCP client is connected normally
Returns:
bool: 如果客户端已连接并正常工作,返回True,否则返回False
bool: Returns True if client is connected and working normally, otherwise False
"""
# 检查工作任务是否存在
# Check if worker task exists
if self._worker_task is None:
return False
# 检查工作任务是否已经完成或取消
# Check if worker task is completed or cancelled
if self._worker_task.done():
return False
# 检查会话是否存在
# Check if session exists
if self.session is None:
return False
# 所有检查都通过,连接正常
# All checks passed, connection is normal
return True
async def _worker(self):
"""MCP客户端工作协程"""
"""MCP client worker coroutine"""
async with AsyncExitStack() as stack:
try:
# 建立 StdioClient
# Establish StdioClient
if "command" in self.config:
cmd = (
shutil.which("npx")
@ -165,7 +163,7 @@ class ServerMCPClient:
)
read_stream, write_stream = stdio_r, stdio_w
# 建立SSEClient
# Establish SSEClient
elif "url" in self.config:
if "API_ACCESS_TOKEN" in self.config:
headers = {
@ -173,13 +171,15 @@ class ServerMCPClient:
}
else:
headers = {}
sse_r, sse_w = await stack.enter_async_context(
sse_client(self.config["url"], headers=headers)
)
read_stream, write_stream = sse_r, sse_w
else:
raise ValueError("MCP客户端配置必须包含'command'或'url'")
raise ValueError(
"MCP client configuration must contain 'command' or 'url'")
self.session = await stack.enter_async_context(
ClientSession(
@ -188,10 +188,12 @@ class ServerMCPClient:
read_timeout_seconds=timedelta(seconds=15),
)
)
await self.session.initialize()
# 获取工具
# Get tools
self.tools = (await self.session.list_tools()).tools
for t in self.tools:
sanitized = sanitize_tool_name(t.name)
self.tools_dict[sanitized] = t
@ -199,10 +201,11 @@ class ServerMCPClient:
self._ready_evt.set()
# 挂起等待关闭
# Suspend and wait for shutdown
await self._shutdown_evt.wait()
except Exception as e:
self.logger.bind(tag=TAG).error(f"服务端MCP客户端工作协程错误: {e}")
self.logger.bind(tag=TAG).error(
f"Server-side MCP client worker coroutine error: {e}")
self._ready_evt.set()
raise

View file

@ -1,13 +1,15 @@
"""服务端MCP工具执行器"""
"""Server-side MCP tool executor"""
from typing import Dict, Any, Optional
from ..base import ToolType, ToolDefinition, ToolExecutor
from plugins_func.register import Action, ActionResponse
from .mcp_manager import ServerMCPManager
class ServerMCPExecutor(ToolExecutor):
"""服务端MCP工具执行器"""
"""Server-side MCP tool executor"""
def __init__(self, conn):
self.conn = conn
@ -15,7 +17,7 @@ class ServerMCPExecutor(ToolExecutor):
self._initialized = False
async def initialize(self):
"""初始化MCP管理器"""
"""Initialize MCP manager"""
if not self._initialized:
self.mcp_manager = ServerMCPManager(self.conn)
await self.mcp_manager.initialize_servers()
@ -24,21 +26,20 @@ class ServerMCPExecutor(ToolExecutor):
async def execute(
self, conn, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
"""执行服务端MCP工具"""
"""Execute server-side MCP tool"""
if not self._initialized or not self.mcp_manager:
return ActionResponse(
action=Action.ERROR,
response="MCP管理器未初始化",
response="MCP manager not initialized",
)
try:
# 移除mcp_前缀(如果有)
# Remove mcp_ prefix (if present)
actual_tool_name = tool_name
if tool_name.startswith("mcp_"):
actual_tool_name = tool_name[4:]
result = await self.mcp_manager.execute_tool(actual_tool_name, arguments)
return ActionResponse(action=Action.REQLLM, result=str(result))
except ValueError as e:
@ -53,7 +54,7 @@ class ServerMCPExecutor(ToolExecutor):
)
def get_tools(self) -> Dict[str, ToolDefinition]:
"""获取所有服务端MCP工具"""
"""Get all server-side MCP tools"""
if not self._initialized or not self.mcp_manager:
return {}
@ -65,6 +66,7 @@ class ServerMCPExecutor(ToolExecutor):
tool_name = func_def.get("name", "")
if tool_name == "":
continue
tools[tool_name] = ToolDefinition(
name=tool_name, description=tool, tool_type=ToolType.SERVER_MCP
)
@ -72,11 +74,11 @@ class ServerMCPExecutor(ToolExecutor):
return tools
def has_tool(self, tool_name: str) -> bool:
"""检查是否有指定的服务端MCP工具"""
"""Check if the specified server-side MCP tool exists"""
if not self._initialized or not self.mcp_manager:
return False
# 移除mcp_前缀(如果有)
# Remove mcp_ prefix (if present)
actual_tool_name = tool_name
if tool_name.startswith("mcp_"):
actual_tool_name = tool_name[4:]
@ -84,6 +86,6 @@ class ServerMCPExecutor(ToolExecutor):
return self.mcp_manager.is_mcp_tool(actual_tool_name)
async def cleanup(self):
"""清理MCP连接"""
"""Clean up MCP connections"""
if self.mcp_manager:
await self.mcp_manager.cleanup_all()
await self.mcp_manager.cleanup_all()

View file

@ -1,34 +1,43 @@
"""服务端MCP管理器"""
"""Server-side MCP manager"""
import asyncio
import os
import json
from typing import Dict, Any, List
from config.config_loader import get_project_dir
from config.logger import setup_logging
from .mcp_client import ServerMCPClient
TAG = __name__
logger = setup_logging()
class ServerMCPManager:
"""管理多个服务端MCP服务的集中管理器"""
"""Centralized manager for managing multiple server-side MCP services"""
def __init__(self, conn) -> None:
"""初始化MCP管理器"""
"""Initialize MCP manager"""
self.conn = conn
self.config_path = get_project_dir() + "data/.mcp_server_settings.json"
if not os.path.exists(self.config_path):
self.config_path = ""
logger.bind(tag=TAG).warning(
f"请检查mcp服务配置文件:data/.mcp_server_settings.json"
f"Please check the MCP service configuration file: data/.mcp_server_settings.json"
)
self.clients: Dict[str, ServerMCPClient] = {}
self.tools = []
def load_config(self) -> Dict[str, Any]:
"""加载MCP服务配置"""
"""Load MCP service configuration"""
if len(self.config_path) == 0:
return {}
@ -43,8 +52,9 @@ class ServerMCPManager:
return {}
async def initialize_servers(self) -> None:
"""初始化所有MCP服务"""
"""Initialize all MCP services"""
config = self.load_config()
for name, srv_config in config.items():
if not srv_config.get("command") and not srv_config.get("url"):
logger.bind(tag=TAG).warning(
@ -53,11 +63,13 @@ class ServerMCPManager:
continue
try:
# 初始化服务端MCP客户端
logger.bind(tag=TAG).info(f"初始化服务端MCP客户端: {name}")
# Initialize server-side MCP client
logger.bind(tag=TAG).info(
f"Initializing server-side MCP client: {name}")
client = ServerMCPClient(srv_config)
await client.initialize()
self.clients[name] = client
client_tools = client.get_available_tools()
self.tools.extend(client_tools)
@ -66,16 +78,16 @@ class ServerMCPManager:
f"Failed to initialize MCP server {name}: {e}"
)
# 输出当前支持的服务端MCP工具列表
# Output current supported server-side MCP tools list
if hasattr(self.conn, "func_handler") and self.conn.func_handler:
self.conn.func_handler.current_support_functions()
def get_all_tools(self) -> List[Dict[str, Any]]:
"""获取所有服务的工具function定义"""
"""Get function definitions for all service tools"""
return self.tools
def is_mcp_tool(self, tool_name: str) -> bool:
"""检查是否是MCP工具"""
"""Check if it's an MCP tool"""
for tool in self.tools:
if (
tool.get("function") is not None
@ -85,15 +97,17 @@ class ServerMCPManager:
return False
async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
"""执行工具调用,失败时会尝试重新连接"""
logger.bind(tag=TAG).info(f"执行服务端MCP工具 {tool_name},参数: {arguments}")
"""Execute tool call, will attempt to reconnect on failure"""
logger.bind(tag=TAG).info(
f"Executing server-side MCP tool {tool_name}, parameters: {arguments}")
max_retries = 3 # 最大重试次数
retry_interval = 2 # 重试间隔(秒)
max_retries = 3 # Maximum retry attempts
retry_interval = 2 # Retry interval (seconds)
# 找到对应的客户端
# Find the corresponding client
client_name = None
target_client = None
for name, client in self.clients.items():
if client.has_tool(tool_name):
client_name = name
@ -101,38 +115,40 @@ class ServerMCPManager:
break
if not target_client:
raise ValueError(f"工具 {tool_name} 在任意MCP服务中未找到")
raise ValueError(f"Tool {tool_name} not found in any MCP service")
# 带重试机制的工具调用
# Tool call with retry mechanism
for attempt in range(max_retries):
try:
return await target_client.call_tool(tool_name, arguments)
except Exception as e:
# 最后一次尝试失败时直接抛出异常
# Throw exception directly on last attempt failure
if attempt == max_retries - 1:
raise
logger.bind(tag=TAG).warning(
f"执行工具 {tool_name} 失败 (尝试 {attempt+1}/{max_retries}): {e}"
f"Failed to execute tool {tool_name} (attempt {attempt+1}/{max_retries}): {e}"
)
# 尝试重新连接
# Attempt to reconnect
logger.bind(tag=TAG).info(
f"重试前尝试重新连接 MCP 客户端 {client_name}"
f"Attempting to reconnect MCP client {client_name} before retry"
)
try:
# 关闭旧的连接
# Close old connection
await target_client.cleanup()
# 重新初始化客户端
# Reinitialize client
config = self.load_config()
if client_name in config:
client = ServerMCPClient(config[client_name])
await client.initialize()
self.clients[client_name] = client
target_client = client
logger.bind(tag=TAG).info(
f"成功重新连接 MCP 客户端: {client_name}"
f"Successfully reconnected MCP client: {client_name}"
)
else:
logger.bind(tag=TAG).error(
@ -143,16 +159,19 @@ class ServerMCPManager:
f"Failed to reconnect MCP client {client_name}: {reconnect_error}"
)
# 等待一段时间再重试
# Wait for a while before retrying
await asyncio.sleep(retry_interval)
async def cleanup_all(self) -> None:
"""关闭所有 MCP客户端"""
"""Close all MCP clients"""
for name, client in list(self.clients.items()):
try:
if hasattr(client, "cleanup"):
await asyncio.wait_for(client.cleanup(), timeout=20)
logger.bind(tag=TAG).info(f"服务端MCP客户端已关闭: {name}")
logger.bind(tag=TAG).info(
f"Server-side MCP client closed: {name}")
except (asyncio.TimeoutError, Exception) as e:
logger.bind(tag=TAG).error(f"关闭服务端MCP客户端 {name} 时出错: {e}")
logger.bind(tag=TAG).error(
f"Error closing server-side MCP client {name}: {e}")
self.clients.clear()

View file

@ -1,5 +1,5 @@
"""服务端插件工具模块"""
"""Server-side plugin tool module"""
from .plugin_executor import ServerPluginExecutor
__all__ = ["ServerPluginExecutor"]
__all__ = ["ServerPluginExecutor"]

View file

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

View file

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

View file

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

View file

@ -1,205 +1,354 @@
import uuid
import json
import hmac
import hashlib
import base64
import requests
from datetime import datetime
from core.providers.tts.base import TTSProviderBase
from config.logger import setup_logging
import time
import uuid
from urllib import parse
TAG = __name__
logger = setup_logging()
import json
import hmac
import hashlib
import base64
import requests
from datetime import datetime
from core.providers.tts.base import TTSProviderBase
import time
import uuid
from urllib import parse
class AccessToken:
@staticmethod
def _encode_text(text):
encoded_text = parse.quote_plus(text)
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
@staticmethod
def _encode_dict(dic):
keys = dic.keys()
dic_sorted = [(key, dic[key]) for key in sorted(keys)]
encoded_text = parse.urlencode(dic_sorted)
return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
@staticmethod
def create_token(access_key_id, access_key_secret):
parameters = {
"AccessKeyId": access_key_id,
"Action": "CreateToken",
"Format": "JSON",
"RegionId": "cn-shanghai",
"SignatureMethod": "HMAC-SHA1",
"SignatureNonce": str(uuid.uuid1()),
"SignatureVersion": "1.0",
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"Version": "2019-02-28",
}
# 构造规范化的请求字符串
# Construct normalized request string
query_string = AccessToken._encode_dict(parameters)
# print('规范化的请求字符串: %s' % query_string)
# 构造待签名字符串
# print('Normalized request string: %s' % query_string)
# Construct string to be signed
string_to_sign = (
"GET"
+ "&"
+ AccessToken._encode_text("/")
+ "&"
+ AccessToken._encode_text(query_string)
)
# print('待签名的字符串: %s' % string_to_sign)
# 计算签名
# print('String to be signed: %s' % string_to_sign)
# Calculate signature
secreted_string = hmac.new(
bytes(access_key_secret + "&", encoding="utf-8"),
bytes(string_to_sign, encoding="utf-8"),
hashlib.sha1,
).digest()
signature = base64.b64encode(secreted_string)
# print('签名: %s' % signature)
# 进行URL编码
# print('Signature: %s' % signature)
# URL encode
signature = AccessToken._encode_text(signature)
# print('URL编码后的签名: %s' % signature)
# 调用服务
# print('URL encoded signature: %s' % signature)
# Call service
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
signature,
query_string,
)
# print('url: %s' % full_url)
# 提交HTTP GET请求
# Submit HTTP GET request
response = requests.get(full_url)
if response.ok:
root_obj = response.json()
key = "Token"
if key in root_obj:
token = root_obj[key]["Id"]
expire_time = root_obj[key]["ExpireTime"]
return token, expire_time
# print(response.text)
return None, None
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
# 新增空值判断逻辑
# Add null value check logic
self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret")
self.appkey = config.get("appkey")
self.format = config.get("format", "wav")
self.audio_file_type = config.get("format", "wav")
sample_rate = config.get("sample_rate", "16000")
self.sample_rate = int(sample_rate) if sample_rate else 16000
if config.get("private_voice"):
self.voice = config.get("private_voice")
else:
self.voice = config.get("voice", "xiaoyun")
volume = config.get("volume", "50")
self.volume = int(volume) if volume else 50
speech_rate = config.get("speech_rate", "0")
self.speech_rate = int(speech_rate) if speech_rate else 0
pitch_rate = config.get("pitch_rate", "0")
self.pitch_rate = int(pitch_rate) if pitch_rate else 0
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
self.api_url = f"https://{self.host}/stream/v1/tts"
self.header = {"Content-Type": "application/json"}
if self.access_key_id and self.access_key_secret:
# 使用密钥对生成临时token
# Use key pair to generate temporary token
self._refresh_token()
else:
# 直接使用预生成的长期token
# Directly use pre-generated long-term token
self.token = config.get("token")
self.expire_time = None
def _refresh_token(self):
"""刷新Token并记录过期时间"""
"""Refresh Token and record expiration time"""
if self.access_key_id and self.access_key_secret:
self.token, expire_time_str = AccessToken.create_token(
self.access_key_id, self.access_key_secret
)
if not expire_time_str:
raise ValueError("无法获取有效的Token过期时间")
raise ValueError("Unable to get valid Token expiration time")
try:
# 统一转换为字符串处理
# Uniformly convert to string processing
expire_str = str(expire_time_str).strip()
if expire_str.isdigit():
expire_time = datetime.fromtimestamp(int(expire_str))
else:
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
expire_time = datetime.strptime(
expire_str, "%Y-%m-%dT%H:%M:%SZ")
self.expire_time = expire_time.timestamp() - 60
except Exception as e:
raise ValueError(f"无效的过期时间格式: {expire_str}") from e
raise ValueError(
f"Invalid expiration time format: {expire_str}") from e
else:
self.expire_time = None
if not self.token:
raise ValueError("无法获取有效的访问Token")
raise ValueError("Unable to get valid access Token")
def _is_token_expired(self):
"""检查Token是否过期"""
"""Check if Token has expired"""
if not self.expire_time:
return False # 长期Token不过期
# 新增调试日志
return False # Long-term Token does not expire
# Add debug log
# current_time = time.time()
# remaining = self.expire_time - current_time
# print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | "
# f"过期时间 {datetime.fromtimestamp(self.expire_time)} | "
# f"剩余 {remaining:.2f}秒")
# print(f"Token expiration check: current time {datetime.fromtimestamp(current_time)} | "
# f"expiration time {datetime.fromtimestamp(self.expire_time)} | "
# f"remaining {remaining:.2f}seconds")
return time.time() > self.expire_time
async def text_to_speak(self, text, output_file):
if self._is_token_expired():
logger.warning("Token已过期,正在自动刷新...")
logger.warning("Token has expired, automatically refreshing...")
self._refresh_token()
request_json = {
"appkey": self.appkey,
"token": self.token,
"text": text,
"format": self.format,
"sample_rate": self.sample_rate,
"voice": self.voice,
"volume": self.volume,
"speech_rate": self.speech_rate,
"pitch_rate": self.pitch_rate,
}
# print(self.api_url, json.dumps(request_json, ensure_ascii=False))
try:
resp = requests.post(
self.api_url, json.dumps(request_json), headers=self.header
)
if resp.status_code == 401: # Token过期特殊处理
if resp.status_code == 401: # Special handling for Token expiration
self._refresh_token()
resp = requests.post(
self.api_url, json.dumps(request_json), headers=self.header
)
# 检查返回请求数据的mime类型是否是audio/***,是则保存到指定路径下;返回的是binary格式的
# Check if the mime type of returned request data is audio/***, if so save to specified path; returned is binary format
if resp.headers["Content-Type"].startswith("audio/"):
if output_file:
with open(output_file, "wb") as f:
f.write(resp.content)
return output_file
else:
return resp.content
else:
raise Exception(
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
)
except Exception as e:
raise Exception(f"{__name__} error: {e}")
raise Exception(f"{__name__} error: {e}")

View file

@ -41,7 +41,7 @@ class AccessToken:
"AccessKeyId": access_key_id,
"Action": "CreateToken",
"Format": "JSON",
"RegionId": "cn-shanghai", # 使用上海地域进行Token获取
"RegionId": "cn-shanghai", # Use Shanghai region for Token acquisition
"SignatureMethod": "HMAC-SHA1",
"SignatureNonce": str(uuid.uuid1()),
"SignatureVersion": "1.0",
@ -88,27 +88,28 @@ class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
# 设置为流式接口类型
# Set to streaming interface type
self.interface_type = InterfaceType.DUAL_STREAM
# 基础配置
# Basic configuration
self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret")
self.appkey = config.get("appkey")
self.format = config.get("format", "pcm")
self.audio_file_type = config.get("format", "pcm")
# 采样率配置
# Sample rate configuration
sample_rate = config.get("sample_rate", "16000")
self.sample_rate = int(sample_rate) if sample_rate else 16000
# 音色配置 - CosyVoice大模型音色
# Voice configuration - CosyVoice large model voice
if config.get("private_voice"):
self.voice = config.get("private_voice")
else:
self.voice = config.get("voice", "longxiaochun") # CosyVoice默认音色
# CosyVoice default voice
self.voice = config.get("voice", "longxiaochun")
# 音频参数配置
# Audio parameter configuration
volume = config.get("volume", "50")
self.volume = int(volume) if volume else 50
@ -118,27 +119,27 @@ class TTSProvider(TTSProviderBase):
pitch_rate = config.get("pitch_rate", "0")
self.pitch_rate = int(pitch_rate) if pitch_rate else 0
# WebSocket配置
# WebSocket configuration
self.host = config.get("host", "nls-gateway-cn-beijing.aliyuncs.com")
# 如果配置的是内网地址(包含-internal.aliyuncs.com),则使用ws协议,默认是wss协议
# If configured with internal network address (contains -internal.aliyuncs.com), use ws protocol, default is wss protocol
if "-internal." in self.host:
self.ws_url = f"ws://{self.host}/ws/v1"
else:
# 默认使用wss协议
# Default to wss protocol
self.ws_url = f"wss://{self.host}/ws/v1"
self.ws = None
self._monitor_task = None
self.last_active_time = None
# 专属tts设置
# Dedicated TTS settings
self.message_id = ""
# 创建Opus编码器
# Create Opus encoder
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
sample_rate=16000, channels=1, frame_size_ms=60
)
# Token管理
# Token management
if self.access_key_id and self.access_key_secret:
self._refresh_token()
else:
@ -146,13 +147,13 @@ class TTSProvider(TTSProviderBase):
self.expire_time = None
def _refresh_token(self):
"""刷新Token并记录过期时间"""
"""Refresh Token and record expiration time"""
if self.access_key_id and self.access_key_secret:
self.token, expire_time_str = AccessToken.create_token(
self.access_key_id, self.access_key_secret
)
if not expire_time_str:
raise ValueError("无法获取有效的Token过期时间")
raise ValueError("Unable to get valid Token expiration time")
expire_str = str(expire_time_str).strip()
@ -160,34 +161,38 @@ class TTSProvider(TTSProviderBase):
if expire_str.isdigit():
expire_time = datetime.fromtimestamp(int(expire_str))
else:
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
expire_time = datetime.strptime(
expire_str, "%Y-%m-%dT%H:%M:%SZ")
self.expire_time = expire_time.timestamp() - 60
except Exception as e:
raise ValueError(f"无效的过期时间格式: {expire_str}") from e
raise ValueError(
f"Invalid expiration time format: {expire_str}") from e
else:
self.expire_time = None
if not self.token:
raise ValueError("无法获取有效的访问Token")
raise ValueError("Unable to get valid access Token")
def _is_token_expired(self):
"""检查Token是否过期"""
"""Check if Token is expired"""
if not self.expire_time:
return False
return time.time() > self.expire_time
async def _ensure_connection(self):
"""确保WebSocket连接可用"""
"""Ensure WebSocket connection is available"""
try:
if self._is_token_expired():
logger.bind(tag=TAG).warning("Token已过期,正在自动刷新...")
logger.bind(tag=TAG).warning(
"Token has expired, automatically refreshing...")
self._refresh_token()
current_time = time.time()
if self.ws and current_time - self.last_active_time < 10:
# 10秒内才可以复用链接进行连续对话
logger.bind(tag=TAG).info(f"使用已有链接...")
# Can only reuse connection for continuous conversation within 10 seconds
logger.bind(tag=TAG).info(f"Using existing connection...")
return self.ws
logger.bind(tag=TAG).info("开始建立新连接...")
logger.bind(tag=TAG).info(
"Starting to establish new connection...")
self.ws = await websockets.connect(
self.ws_url,
@ -196,106 +201,118 @@ class TTSProvider(TTSProviderBase):
ping_timeout=10,
close_timeout=10,
)
logger.bind(tag=TAG).info("WebSocket连接建立成功")
logger.bind(tag=TAG).info(
"WebSocket connection established successfully")
self.last_active_time = time.time()
return self.ws
except Exception as e:
logger.bind(tag=TAG).error(f"建立连接失败: {str(e)}")
logger.bind(tag=TAG).error(
f"Failed to establish connection: {str(e)}")
self.ws = None
self.last_active_time = None
raise
def tts_text_priority_thread(self):
"""流式文本处理线程"""
"""Streaming text processing thread"""
while not self.conn.stop_event.is_set():
try:
message = self.tts_text_queue.get(timeout=1)
logger.bind(tag=TAG).debug(
f"收到TTS任务|{message.sentence_type.name} | {message.content_type.name} | 会话ID: {self.conn.sentence_id}"
f"Received TTS task|{message.sentence_type.name} | {message.content_type.name} | Session ID: {self.conn.sentence_id}"
)
if message.sentence_type == SentenceType.FIRST:
self.conn.client_abort = False
if self.conn.client_abort:
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
logger.bind(tag=TAG).info(
"Received interruption signal, terminating TTS text processing thread")
continue
if message.sentence_type == SentenceType.FIRST:
# 初始化参数
# Initialize parameters
try:
if not getattr(self.conn, "sentence_id", None):
self.conn.sentence_id = uuid.uuid4().hex
logger.bind(tag=TAG).info(
f"自动生成新的 会话ID: {self.conn.sentence_id}"
f"Auto-generated new session ID: {self.conn.sentence_id}"
)
# aliyunStream独有的参数生成
# AliyunStream-specific parameter generation
self.message_id = str(uuid.uuid4().hex)
logger.bind(tag=TAG).info("开始启动TTS会话...")
logger.bind(tag=TAG).info("Starting TTS session...")
future = asyncio.run_coroutine_threadsafe(
self.start_session(self.conn.sentence_id),
loop=self.conn.loop,
)
future.result()
self.before_stop_play_files.clear()
logger.bind(tag=TAG).info("TTS会话启动成功")
logger.bind(tag=TAG).info(
"TTS session started successfully")
except Exception as e:
logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
logger.bind(tag=TAG).error(
f"Failed to start TTS session: {str(e)}")
continue
elif ContentType.TEXT == message.content_type:
if message.content_detail:
try:
logger.bind(tag=TAG).debug(
f"开始发送TTS文本: {message.content_detail}"
f"Starting to send TTS text: {message.content_detail}"
)
future = asyncio.run_coroutine_threadsafe(
self.text_to_speak(message.content_detail, None),
self.text_to_speak(
message.content_detail, None),
loop=self.conn.loop,
)
future.result()
logger.bind(tag=TAG).debug("TTS文本发送成功")
logger.bind(tag=TAG).debug(
"TTS text sent successfully")
except Exception as e:
logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
logger.bind(tag=TAG).error(
f"Failed to send TTS text: {str(e)}")
continue
elif ContentType.FILE == message.content_type:
logger.bind(tag=TAG).info(
f"添加音频文件到待播放列表: {message.content_file}"
f"Adding audio file to playback queue: {message.content_file}"
)
if message.content_file and os.path.exists(message.content_file):
# 先处理文件音频数据
file_audio = self._process_audio_file(message.content_file)
# Process file audio data first
file_audio = self._process_audio_file(
message.content_file)
self.before_stop_play_files.append(
(file_audio, message.content_detail)
)
if message.sentence_type == SentenceType.LAST:
try:
logger.bind(tag=TAG).info("开始结束TTS会话...")
logger.bind(tag=TAG).info(
"Starting to end TTS session...")
future = asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
future.result()
except Exception as e:
logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
logger.bind(tag=TAG).error(
f"Failed to end TTS session: {str(e)}")
continue
except queue.Empty:
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
f"Failed to process TTS text: {str(e)}, Type: {type(e).__name__}, Stack: {traceback.format_exc()}"
)
async def text_to_speak(self, text, _):
try:
if self.ws is None:
logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
logger.bind(tag=TAG).warning(
f"WebSocket connection does not exist, terminating text sending")
return
filtered_text = MarkdownCleaner.clean_markdown(text)
run_request = {
@ -313,7 +330,7 @@ class TTSProvider(TTSProviderBase):
return
except Exception as e:
logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to send TTS text: {str(e)}")
if self.ws:
try:
await self.ws.close()
@ -323,24 +340,25 @@ class TTSProvider(TTSProviderBase):
raise
async def start_session(self, session_id):
logger.bind(tag=TAG).info(f"开始会话~~{session_id}")
logger.bind(tag=TAG).info(f"Starting session~~{session_id}")
try:
# 会话开始时检测上个会话的监听状态
# Check previous session monitoring status when session starts
if (
self._monitor_task is not None
and isinstance(self._monitor_task, Task)
and not self._monitor_task.done()
):
logger.bind(tag=TAG).info(
"检测到未完成的上个会话,关闭监听任务和连接..."
"Detected incomplete previous session, closing monitoring task and connection..."
)
await self.close()
# 建立新连接
# Establish new connection
await self._ensure_connection()
# 启动监听任务
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
# Start monitoring task
self._monitor_task = asyncio.create_task(
self._start_monitor_tts_response())
start_request = {
"header": {
@ -362,15 +380,15 @@ class TTSProvider(TTSProviderBase):
}
await self.ws.send(json.dumps(start_request))
self.last_active_time = time.time()
logger.bind(tag=TAG).info("会话启动请求已发送")
logger.bind(tag=TAG).info("Session start request sent")
except Exception as e:
logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to start session: {str(e)}")
# 确保清理资源
await self.close()
raise
async def finish_session(self, session_id):
logger.bind(tag=TAG).info(f"关闭会话~~{session_id}")
logger.bind(tag=TAG).info(f"Closing session~~{session_id}")
try:
if self.ws:
stop_request = {
@ -383,25 +401,25 @@ class TTSProvider(TTSProviderBase):
}
}
await self.ws.send(json.dumps(stop_request))
logger.bind(tag=TAG).info("会话结束请求已发送")
logger.bind(tag=TAG).info("Session end request sent")
self.last_active_time = time.time()
if self._monitor_task:
try:
await self._monitor_task
except Exception as e:
logger.bind(tag=TAG).error(
f"等待监听任务完成时发生错误: {str(e)}"
f"Error occurred while waiting for monitoring task to complete: {str(e)}"
)
finally:
self._monitor_task = None
except Exception as e:
logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}")
logger.bind(tag=TAG).error(f"Failed to close session: {str(e)}")
# 确保清理资源
await self.close()
raise
async def close(self):
"""资源清理"""
"""Resource cleanup"""
if self._monitor_task:
try:
self._monitor_task.cancel()
@ -409,7 +427,8 @@ class TTSProvider(TTSProviderBase):
except asyncio.CancelledError:
pass
except Exception as e:
logger.bind(tag=TAG).warning(f"关闭时取消监听任务错误: {e}")
logger.bind(tag=TAG).warning(
f"Error canceling monitoring task during close: {e}")
self._monitor_task = None
if self.ws:
@ -421,27 +440,29 @@ class TTSProvider(TTSProviderBase):
self.last_active_time = None
async def _start_monitor_tts_response(self):
"""监听TTS响应"""
"""Monitor TTS responses"""
opus_datas_cache = []
is_first_sentence = True
first_sentence_segment_count = 0 # 添加计数器
first_sentence_segment_count = 0 # Add counter
try:
session_finished = False # 标记会话是否正常结束
session_finished = False # Mark whether session ended normally
while not self.conn.stop_event.is_set():
try:
msg = await self.ws.recv()
self.last_active_time = time.time()
# 检查客户端是否中止
# Check if client aborted
if self.conn.client_abort:
logger.bind(tag=TAG).info("收到打断信息,终止监听TTS响应")
logger.bind(tag=TAG).info(
"Received interruption signal, terminating TTS response monitoring")
break
if isinstance(msg, str): # 文本控制消息
if isinstance(msg, str): # Text control message
try:
data = json.loads(msg)
header = data.get("header", {})
event_name = header.get("name")
if event_name == "SynthesisStarted":
logger.bind(tag=TAG).debug("TTS合成已启动")
logger.bind(tag=TAG).debug(
"TTS synthesis started")
self.tts_audio_queue.put(
(SentenceType.FIRST, [], None)
)
@ -452,34 +473,38 @@ class TTSProvider(TTSProviderBase):
not is_first_sentence
or first_sentence_segment_count > 10
):
# 发送缓存的数据
# Send cached data
if self.conn.tts_MessageText:
logger.bind(tag=TAG).info(
f"句子语音生成成功: {self.conn.tts_MessageText}"
f"Sentence voice generation successful: {self.conn.tts_MessageText}"
)
self.tts_audio_queue.put(
(SentenceType.MIDDLE, opus_datas_cache, self.conn.tts_MessageText)
(SentenceType.MIDDLE, opus_datas_cache,
self.conn.tts_MessageText)
)
self.conn.tts_MessageText = None
else:
self.tts_audio_queue.put(
(SentenceType.MIDDLE, opus_datas_cache, None)
(SentenceType.MIDDLE,
opus_datas_cache, None)
)
# 第一句话结束后,将标志设置为False
# After first sentence ends, set flag to False
is_first_sentence = False
elif event_name == "SynthesisCompleted":
logger.bind(tag=TAG).debug(f"会话结束~~")
logger.bind(tag=TAG).debug(f"Session ended~~")
self._process_before_stop_play_files()
session_finished = True
break
except json.JSONDecodeError:
logger.bind(tag=TAG).warning("收到无效的JSON消息")
# 二进制消息(音频数据)
logger.bind(tag=TAG).warning(
"Received invalid JSON message")
# Binary message (audio data)
elif isinstance(msg, (bytes, bytearray)):
logger.bind(tag=TAG).debug(f"推送数据到队列里面~~")
opus_datas = self.opus_encoder.encode_pcm_to_opus(msg, False)
logger.bind(tag=TAG).debug(f"Pushing data to queue~~")
opus_datas = self.opus_encoder.encode_pcm_to_opus(
msg, False)
logger.bind(tag=TAG).debug(
f"推送数据到队列里面帧数~~{len(opus_datas)}"
f"Pushing data to queue frame count~~{len(opus_datas)}"
)
if is_first_sentence:
first_sentence_segment_count += 1
@ -490,46 +515,46 @@ class TTSProvider(TTSProviderBase):
else:
opus_datas_cache.extend(opus_datas)
else:
# 后续句子缓存
# Cache subsequent sentences
opus_datas_cache.extend(opus_datas)
except websockets.ConnectionClosed:
logger.bind(tag=TAG).warning("WebSocket连接已关闭")
logger.bind(tag=TAG).warning("WebSocket connection closed")
break
except Exception as e:
logger.bind(tag=TAG).error(
f"处理TTS响应时出错: {e}\n{traceback.format_exc()}"
f"Error processing TTS response: {e}\n{traceback.format_exc()}"
)
break
# 仅在连接异常时才关闭
# Only close on connection exception
if not session_finished and self.ws:
try:
await self.ws.close()
except:
pass
self.ws = None
# 监听任务退出时清理引用
# Clean up references when monitoring task exits
finally:
self._monitor_task = None
def to_tts(self, text: str) -> list:
"""非流式TTS处理,用于测试及保存音频文件的场景"""
"""Non-streaming TTS processing, used for testing and saving audio files scenarios"""
try:
# 创建新的事件循环
# Create new event loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# 生成会话ID
# Generate session ID
session_id = uuid.uuid4().hex
# 存储音频数据
# Store audio data
audio_data = []
async def _generate_audio():
# 刷新Token(如果需要)
# Refresh Token (if needed)
if self._is_token_expired():
self._refresh_token()
# 建立WebSocket连接
# Establish WebSocket connection
ws = await websockets.connect(
self.ws_url,
additional_headers={"X-NLS-Token": self.token},
@ -538,7 +563,7 @@ class TTSProvider(TTSProviderBase):
close_timeout=10,
)
try:
# 发送StartSynthesis请求
# Send StartSynthesis request
start_message_id = str(uuid.uuid4().hex)
start_request = {
"header": {
@ -560,7 +585,7 @@ class TTSProvider(TTSProviderBase):
}
await ws.send(json.dumps(start_request))
# 等待SynthesisStarted响应
# Wait for SynthesisStarted response
synthesis_started = False
while not synthesis_started:
msg = await ws.recv()
@ -569,7 +594,8 @@ class TTSProvider(TTSProviderBase):
header = data.get("header", {})
if header.get("name") == "SynthesisStarted":
synthesis_started = True
logger.bind(tag=TAG).debug("TTS合成已启动")
logger.bind(tag=TAG).debug(
"TTS synthesis started")
elif header.get("name") == "TaskFailed":
error_info = data.get("payload", {}).get(
"error_info", {}
@ -579,10 +605,10 @@ class TTSProvider(TTSProviderBase):
"error_message", "未知错误"
)
raise Exception(
f"启动合成失败: {error_code} - {error_message}"
f"Failed to start synthesis: {error_code} - {error_message}"
)
# 发送文本合成请求
# Send text synthesis request
filtered_text = MarkdownCleaner.clean_markdown(text)
run_message_id = str(uuid.uuid4().hex)
run_request = {
@ -597,7 +623,7 @@ class TTSProvider(TTSProviderBase):
}
await ws.send(json.dumps(run_request))
# 发送停止合成请求
# Send stop synthesis request
stop_message_id = str(uuid.uuid4().hex)
stop_request = {
"header": {
@ -610,12 +636,12 @@ class TTSProvider(TTSProviderBase):
}
await ws.send(json.dumps(stop_request))
# 接收音频数据
# Receive audio data
synthesis_completed = False
while not synthesis_completed:
msg = await ws.recv()
if isinstance(msg, (bytes, bytearray)):
# 编码为Opus并收集
# Encode to Opus and collect
opus_frames = self.opus_encoder.encode_pcm_to_opus(
msg, False
)
@ -626,7 +652,8 @@ class TTSProvider(TTSProviderBase):
event_name = header.get("name")
if event_name == "SynthesisCompleted":
synthesis_completed = True
logger.bind(tag=TAG).debug("TTS合成完成")
logger.bind(tag=TAG).debug(
"TTS synthesis completed")
elif event_name == "TaskFailed":
error_info = data.get("payload", {}).get(
"error_info", {}
@ -636,7 +663,7 @@ class TTSProvider(TTSProviderBase):
"error_message", "未知错误"
)
raise Exception(
f"合成失败: {error_code} - {error_message}"
f"Synthesis failed: {error_code} - {error_message}"
)
finally:
try:
@ -649,5 +676,6 @@ class TTSProvider(TTSProviderBase):
return audio_data
except Exception as e:
logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}")
return []
logger.bind(tag=TAG).error(
f"Failed to generate audio data: {str(e)}")
return []

View file

@ -20,13 +20,11 @@ from core.providers.tts.dto.dto import (
ContentType,
InterfaceType,
)
import traceback
TAG = __name__
logger = setup_logging()
class TTSProviderBase(ABC):
def __init__(self, config, delete_audio_file):
self.interface_type = InterfaceType.NON_STREAM
@ -39,7 +37,6 @@ class TTSProviderBase(ABC):
self.tts_audio_queue = queue.Queue()
self.tts_audio_first_sentence = True
self.before_stop_play_files = []
self.tts_text_buff = []
self.punctuations = (
"。",
@ -81,7 +78,7 @@ class TTSProviderBase(ABC):
text = MarkdownCleaner.clean_markdown(text)
max_repeat_time = 5
if self.delete_audio_file:
# 需要删除文件的直接转为音频数据
# Files that need to be deleted are directly converted to audio data
while max_repeat_time > 0:
try:
audio_bytes = asyncio.run(self.text_to_speak(text, None))
@ -94,16 +91,17 @@ class TTSProviderBase(ABC):
max_repeat_time -= 1
except Exception as e:
logger.bind(tag=TAG).warning(
f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
f"Speech generation failed {5 - max_repeat_time + 1} times: {text}, error: {e}"
)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
f"语音生成成功: {text},重试{5 - max_repeat_time}次"
f"Speech generation successful: {text}, retried {5 - max_repeat_time} times"
)
else:
logger.bind(tag=TAG).error(
f"语音生成失败: {text},请检查网络或服务是否正常"
f"Speech generation failed: {text}, please check network or service status"
)
return None
else:
@ -114,22 +112,21 @@ class TTSProviderBase(ABC):
asyncio.run(self.text_to_speak(text, tmp_file))
except Exception as e:
logger.bind(tag=TAG).warning(
f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
f"Speech generation failed {5 - max_repeat_time + 1} times: {text}, error: {e}"
)
# 未执行成功,删除文件
# If execution unsuccessful, delete file
if os.path.exists(tmp_file):
os.remove(tmp_file)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
f"语音生成成功: {text}:{tmp_file},重试{5 - max_repeat_time}次"
f"Speech generation successful: {text}:{tmp_file}, retried {5 - max_repeat_time} times"
)
else:
logger.bind(tag=TAG).error(
f"语音生成失败: {text},请检查网络或服务是否正常"
f"Speech generation failed: {text}, please check network or service status"
)
return tmp_file
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
@ -140,11 +137,11 @@ class TTSProviderBase(ABC):
pass
def audio_to_pcm_data(self, audio_file_path):
"""音频文件转换为PCM编码"""
"""Convert audio file to PCM encoding"""
return audio_to_data(audio_file_path, is_opus=False)
def audio_to_opus_data(self, audio_file_path):
"""音频文件转换为Opus编码"""
"""Convert audio file to Opus encoding"""
return audio_to_data(audio_file_path, is_opus=True)
def tts_one_sentence(
@ -155,14 +152,15 @@ class TTSProviderBase(ABC):
content_file=None,
sentence_id=None,
):
"""发送一句话"""
"""Send one sentence"""
if not sentence_id:
if conn.sentence_id:
sentence_id = conn.sentence_id
else:
sentence_id = str(uuid.uuid4().hex)
conn.sentence_id = sentence_id
# 对于单句的文本,进行分段处理
# For single sentence text, perform segmentation processing
segments = re.split(r"([。!?!?;;\n])", content_detail)
for seg in segments:
self.tts_text_queue.put(
@ -178,36 +176,38 @@ class TTSProviderBase(ABC):
async def open_audio_channels(self, conn):
self.conn = conn
self.tts_timeout = conn.config.get("tts_timeout", 10)
# tts 消化线程
# TTS processing thread
self.tts_priority_thread = threading.Thread(
target=self.tts_text_priority_thread, daemon=True
)
self.tts_priority_thread.start()
# 音频播放 消化线程
# Audio playback processing thread
self.audio_play_priority_thread = threading.Thread(
target=self._audio_play_priority_thread, daemon=True
)
self.audio_play_priority_thread.start()
# Default is non-streaming processing mode
# Override in subclass for streaming processing mode
# 这里默认是非流式的处理方式
# 流式处理方式请在子类中重写
def tts_text_priority_thread(self):
while not self.conn.stop_event.is_set():
try:
message = self.tts_text_queue.get(timeout=1)
if message.sentence_type == SentenceType.FIRST:
self.conn.client_abort = False
if self.conn.client_abort:
logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
logger.bind(tag=TAG).info("Received interrupt signal, terminating TTS text processing thread")
continue
if message.sentence_type == SentenceType.FIRST:
# 初始化参数
# Initialize parameters
self.tts_stop_request = False
self.processed_chars = 0
self.tts_text_buff = []
self.is_first_sentence = True
self.tts_audio_first_sentence = True
elif ContentType.TEXT == message.content_type:
self.tts_text_buff.append(message.content_detail)
segment_text = self._get_segment_text()
@ -225,6 +225,7 @@ class TTSProviderBase(ABC):
self.tts_audio_queue.put(
(message.sentence_type, audio_datas, segment_text)
)
elif ContentType.FILE == message.content_type:
self._process_remaining_text()
tts_file = message.content_file
@ -244,7 +245,7 @@ class TTSProviderBase(ABC):
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
f"Failed to process TTS text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}"
)
continue
@ -260,14 +261,18 @@ class TTSProviderBase(ABC):
if self.conn.stop_event.is_set():
break
continue
future = asyncio.run_coroutine_threadsafe(
sendAudioMessage(self.conn, sentence_type, audio_datas, text),
self.conn.loop,
)
future.result()
if self.conn.max_output_size > 0 and text:
add_device_output(self.conn.headers.get("device-id"), len(text))
enqueue_tts_report(self.conn, text, audio_datas)
except Exception as e:
logger.bind(tag=TAG).error(
f"audio_play_priority priority_thread: {text} {e}"
@ -280,17 +285,17 @@ class TTSProviderBase(ABC):
pass
async def close(self):
"""资源清理方法"""
"""Resource cleanup method"""
if hasattr(self, "ws") and self.ws:
await self.ws.close()
def _get_segment_text(self):
# 合并当前全部文本并处理未分割部分
# Merge all current text and process unsegmented parts
full_text = "".join(self.tts_text_buff)
current_text = full_text[self.processed_chars :] # 从未处理的位置开始
current_text = full_text[self.processed_chars:] # Start from unprocessed position
last_punct_pos = -1
# 根据是否是第一句话选择不同的标点符号集合
# Choose different punctuation sets based on whether it's the first sentence
punctuations_to_use = (
self.first_sentence_punctuations
if self.is_first_sentence
@ -309,27 +314,25 @@ class TTSProviderBase(ABC):
segment_text = textUtils.get_string_no_punctuation_or_emoji(
segment_text_raw
)
self.processed_chars += len(segment_text_raw) # 更新已处理字符位置
# 如果是第一句话,在找到第一个逗号后,将标志设置为False
self.processed_chars += len(segment_text_raw) # Update processed character position
# If it's the first sentence, set flag to False after finding first comma
if self.is_first_sentence:
self.is_first_sentence = False
return segment_text
elif self.tts_stop_request and current_text:
segment_text = current_text
self.is_first_sentence = True # 重置标志
self.is_first_sentence = True # Reset flag
return segment_text
else:
return None
def _process_audio_file(self, tts_file):
"""处理音频文件并转换为指定格式
"""Process audio file and convert to specified format
Args:
tts_file: 音频文件路径
content_detail: 内容详情
tts_file: Audio file path
content_detail: Content details
Returns:
tuple: (sentence_type, audio_datas, content_detail)
"""
@ -347,6 +350,7 @@ class TTSProviderBase(ABC):
and tts_file.startswith(self.output_file)
):
os.remove(tts_file)
return audio_datas
def _process_before_stop_play_files(self):
@ -356,15 +360,17 @@ class TTSProviderBase(ABC):
self.tts_audio_queue.put((SentenceType.LAST, [], None))
def _process_remaining_text(self):
"""处理剩余的文本并生成语音
"""Process remaining text and generate speech
Returns:
bool: 是否成功处理了文本
bool: Whether text was successfully processed
"""
full_text = "".join(self.tts_text_buff)
remaining_text = full_text[self.processed_chars :]
remaining_text = full_text[self.processed_chars:]
if remaining_text:
segment_text = textUtils.get_string_no_punctuation_or_emoji(remaining_text)
segment_text = textUtils.get_string_no_punctuation_or_emoji(
remaining_text
)
if segment_text:
if self.delete_audio_file:
audio_datas = self.to_tts(segment_text)
@ -380,4 +386,4 @@ class TTSProviderBase(ABC):
)
self.processed_chars += len(full_text)
return True
return False
return False

View file

@ -1,42 +1,76 @@
import requests
from core.providers.tts.base import TTSProviderBase
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.model = config.get("model")
self.access_token = config.get("access_token")
if config.get("private_voice"):
self.voice = config.get("private_voice")
else:
self.voice = config.get("voice")
self.response_format = config.get("response_format", "wav")
self.audio_file_type = config.get("response_format", "wav")
self.host = "api.coze.cn"
self.api_url = f"https://{self.host}/v1/audio/speech"
async def text_to_speak(self, text, output_file):
request_json = {
"model": self.model,
"input": text,
"voice_id": self.voice,
"response_format": self.response_format,
}
headers = {
"Authorization": f"Bearer {self.access_token}",
"Content-Type": "application/json",
}
try:
response = requests.request(
"POST", self.api_url, json=request_json, headers=headers
)
data = response.content
if output_file:
with open(output_file, "wb") as file_to_save:
file_to_save.write(data)
else:
return data
except Exception as e:
raise Exception(f"{__name__} error: {e}")

View file

@ -1,54 +1,95 @@
import os
import json
import uuid
import requests
from config.logger import setup_logging
from datetime import datetime
from core.providers.tts.base import TTSProviderBase
TAG = __name__
logger = setup_logging()
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.url = config.get("url")
self.method = config.get("method", "GET")
self.headers = config.get("headers", {})
self.format = config.get("format", "wav")
self.audio_file_type = config.get("format", "wav")
self.output_file = config.get("output_dir", "tmp/")
self.params = config.get("params")
if isinstance(self.params, str):
try:
self.params = json.loads(self.params)
except json.JSONDecodeError:
raise ValueError("Custom TTS配置参数出错,无法将字符串解析为对象")
raise ValueError("Custom TTS configuration parameter error, unable to parse string as object")
elif not isinstance(self.params, dict):
raise TypeError("Custom TTS配置参数出错, 请参考配置说明")
raise TypeError("Custom TTS configuration parameter error, please refer to configuration instructions")
def generate_filename(self):
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}.{self.format}")
async def text_to_speak(self, text, output_file):
request_params = {}
for k, v in self.params.items():
if isinstance(v, str) and "{prompt_text}" in v:
v = v.replace("{prompt_text}", text)
request_params[k] = v
if self.method.upper() == "POST":
resp = requests.post(self.url, json=request_params, headers=self.headers)
else:
resp = requests.get(self.url, params=request_params, headers=self.headers)
if resp.status_code == 200:
if output_file:
with open(output_file, "wb") as file:
file.write(resp.content)
else:
return resp.content
else:
error_msg = f"Custom TTS请求失败: {resp.status_code} - {resp.text}"
error_msg = f"Custom TTS request failed: {resp.status_code} - {resp.text}"
logger.bind(tag=TAG).error(error_msg)
raise Exception(error_msg) # 抛出异常,让调用方捕获
raise Exception(error_msg) # Throw exception for caller to catch

View file

@ -1,23 +1,34 @@
import os
from config.logger import setup_logging
from core.providers.tts.base import TTSProviderBase
TAG = __name__
logger = setup_logging()
class DefaultTTS(TTSProviderBase):
def __init__(self, config, delete_audio_file=True):
super().__init__(config, delete_audio_file)
self.output_dir = config.get("output_dir", "output")
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
def generate_filename(self):
"""生成唯一的音频文件名"""
"""Generate unique audio filename"""
import uuid
return os.path.join(self.output_dir, f"{uuid.uuid4()}.wav")
async def text_to_speak(self, text, output_file):
logger.bind(tag=TAG).error(f"无法实例化 TTS 服务,请检查配置")
logger.bind(tag=TAG).error(
f"Unable to instantiate TTS service, please check configuration")

View file

@ -1,86 +1,155 @@
import uuid
import json
import base64
import requests
from core.utils.util import check_model_key
from core.providers.tts.base import TTSProviderBase
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
if config.get("appid"):
self.appid = int(config.get("appid"))
else:
self.appid = ""
self.access_token = config.get("access_token")
self.cluster = config.get("cluster")
if config.get("private_voice"):
self.voice = config.get("private_voice")
else:
self.voice = config.get("voice")
# 处理空字符串的情况
# Handle empty string cases
speed_ratio = config.get("speed_ratio", "1.0")
volume_ratio = config.get("volume_ratio", "1.0")
pitch_ratio = config.get("pitch_ratio", "1.0")
self.audio_file_type = config.get("format", "wav")
self.speed_ratio = float(speed_ratio) if speed_ratio else 1.0
self.volume_ratio = float(volume_ratio) if volume_ratio else 1.0
self.pitch_ratio = float(pitch_ratio) if pitch_ratio else 1.0
self.api_url = config.get("api_url")
self.authorization = config.get("authorization")
self.header = {"Authorization": f"{self.authorization}{self.access_token}"}
model_key_msg = check_model_key("TTS", self.access_token)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
async def text_to_speak(self, text, output_file):
request_json = {
"app": {
"appid": f"{self.appid}",
"token": self.access_token,
"cluster": self.cluster,
},
"user": {"uid": "1"},
"audio": {
"voice_type": self.voice,
"encoding": self.audio_file_type,
"speed_ratio": self.speed_ratio,
"volume_ratio": self.volume_ratio,
"pitch_ratio": self.pitch_ratio,
},
"request": {
"reqid": str(uuid.uuid4()),
"text": text,
"text_type": "plain",
"operation": "query",
"with_frontend": 1,
"frontend_type": "unitTson",
},
}
try:
resp = requests.post(
self.api_url, json.dumps(request_json), headers=self.header
)
if "data" in resp.json():
data = resp.json()["data"]
audio_bytes = base64.b64decode(data)
if output_file:
with open(output_file, "wb") as file_to_save:
file_to_save.write(audio_bytes)
else:
return audio_bytes
else:
raise Exception(
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
)
except Exception as e:
raise Exception(f"{__name__} error: {e}")
raise Exception(f"{__name__} error: {e}")

View file

@ -3,41 +3,41 @@ from typing import Union, Optional
class SentenceType(Enum):
# 说话阶段
FIRST = "FIRST" # 首句话
MIDDLE = "MIDDLE" # 说话中
LAST = "LAST" # 最后一句
# Speaking stage
FIRST = "FIRST" # First sentence
MIDDLE = "MIDDLE" # Speaking in progress
LAST = "LAST" # Last sentence
class ContentType(Enum):
# 内容类型
TEXT = "TEXT" # 文本内容
FILE = "FILE" # 文件内容
ACTION = "ACTION" # 动作内容
# Content type
TEXT = "TEXT" # Text content
FILE = "FILE" # File content
ACTION = "ACTION" # Action content
class InterfaceType(Enum):
# 接口类型
DUAL_STREAM = "DUAL_STREAM" # 双流式
SINGLE_STREAM = "SINGLE_STREAM" # 单流式
NON_STREAM = "NON_STREAM" # 非流式
# Interface type
DUAL_STREAM = "DUAL_STREAM" # Dual streaming
SINGLE_STREAM = "SINGLE_STREAM" # Single streaming
NON_STREAM = "NON_STREAM" # Non-streaming
class TTSMessageDTO:
def __init__(
self,
sentence_id: str,
# 说话阶段
# Speaking stage
sentence_type: SentenceType,
# 内容类型
# Content type
content_type: ContentType,
# 内容详情,一般是需要转换的文本或者音频的歌词
# Content details, usually text to be converted or lyrics of audio
content_detail: Optional[str] = None,
# 如果内容类型为文件,则需要传入文件路径
# If content type is file, need to pass file path
content_file: Optional[str] = None,
):
self.sentence_id = sentence_id
self.sentence_type = sentence_type
self.content_type = content_type
self.content_detail = content_detail
self.content_file = content_file
self.content_file = content_file

View file

@ -1,46 +1,81 @@
import os
import uuid
import edge_tts
from datetime import datetime
from core.providers.tts.base import TTSProviderBase
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
if config.get("private_voice"):
self.voice = config.get("private_voice")
else:
self.voice = config.get("voice")
self.audio_file_type = config.get("format", "mp3")
def generate_filename(self, extension=".mp3"):
return os.path.join(
self.output_file,
f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
)
async def text_to_speak(self, text, output_file):
try:
communicate = edge_tts.Communicate(text, voice=self.voice)
if output_file:
# 确保目录存在并创建空文件
# Ensure directory exists and create empty file
os.makedirs(os.path.dirname(output_file), exist_ok=True)
with open(output_file, "wb") as f:
pass
# 流式写入音频数据
with open(output_file, "ab") as f: # 改为追加模式避免覆盖
# Stream write audio data
with open(output_file, "ab") as f: # Change to append mode to avoid overwrite
async for chunk in communicate.stream():
if chunk["type"] == "audio": # 只处理音频数据块
if chunk["type"] == "audio": # Only process audio data chunks
f.write(chunk["data"])
else:
# 返回音频二进制数据
# Return audio binary data
audio_bytes = b""
async for chunk in communicate.stream():
if chunk["type"] == "audio":
audio_bytes += chunk["data"]
return audio_bytes
except Exception as e:
error_msg = f"Edge TTS请求失败: {e}"
raise Exception(error_msg) # 抛出异常,让调用方捕获
error_msg = f"Edge TTS request failed: {e}"
raise Exception(error_msg) # Throw exception for caller to catch

View file

@ -9,43 +9,54 @@ logger = setup_logging()
class TTSProvider(TTSProviderBase):
"""
ElevenLabs TTS Provider
Supports high-quality voice synthesis with multiple voices and languages
"""
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.api_key = config.get("api_key","sk_7bbbc42db83364614c2e07da3991c16a91256df9e7281f37")
if not self.api_key:
self.api_key = config.get(
"api_key", "sk_7bbbc42db83364614c2e07da3991c16a91256df9e7281f37")
if not self.api_key:
raise ValueError("ElevenLabs API key is required")
self.voice_id = config.get("voice_id", "21m00Tcm4TlvDq8ikWAM") # Default to Rachel voice
self.model_id = config.get("model_id", "eleven_multilingual_v2") # Default multilingual model
# Default to Rachel voice
self.voice_id = config.get("voice_id", "21m00Tcm4TlvDq8ikWAM")
# Default multilingual model
self.model_id = config.get("model_id", "eleven_multilingual_v2")
# ElevenLabs API endpoint
self.api_url = f"https://api.elevenlabs.io/v1/text-to-speech/{self.voice_id}"
# Voice settings
self.stability = float(config.get("stability", "0.75"))
self.similarity_boost = float(config.get("similarity_boost", "0.75"))
self.style = float(config.get("style", "0.0")) # For v2 models
self.use_speaker_boost = config.get("use_speaker_boost", True)
# Output format (ElevenLabs supports mp3, pcm, ulaw, mulaw)
self.output_format = config.get("output_format", "mp3_44100_128")
self.audio_file_type = "mp3" if "mp3" in self.output_format else "wav"
# Streaming settings
self.optimize_streaming_latency = int(config.get("optimize_streaming_latency", "0"))
self.optimize_streaming_latency = int(
config.get("optimize_streaming_latency", "0"))
self.output_file = config.get("output_dir", "tmp/")
model_key_msg = check_model_key("ElevenLabs TTS", self.api_key)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
# Validate API key format
if self.api_key and len(self.api_key) < 32:
logger.bind(tag=TAG).warning("ElevenLabs API key appears to be too short. Please check your API key.")
logger.bind(tag=TAG).warning(
"ElevenLabs API key appears to be too short. Please check your API key.")
async def text_to_speak(self, text, output_file):
"""
@ -56,80 +67,139 @@ class TTSProvider(TTSProviderBase):
"Content-Type": "application/json",
"xi-api-key": self.api_key
}
data = {
"text": text,
"model_id": self.model_id,
"voice_settings": {
"stability": self.stability,
"similarity_boost": self.similarity_boost,
"style": self.style,
"use_speaker_boost": self.use_speaker_boost
}
}
# Add streaming optimization if specified
if self.optimize_streaming_latency > 0:
params = {
"optimize_streaming_latency": self.optimize_streaming_latency,
"output_format": self.output_format
}
else:
params = {
"output_format": self.output_format
}
try:
response = requests.post(
self.api_url,
json=data,
headers=headers,
params=params,
timeout=30
)
if response.status_code == 200:
if output_file:
with open(output_file, "wb") as audio_file:
audio_file.write(response.content)
logger.bind(tag=TAG).debug(f"ElevenLabs TTS saved to: {output_file}")
logger.bind(tag=TAG).debug(
f"ElevenLabs TTS saved to: {output_file}")
else:
return response.content
else:
error_data = response.json() if response.headers.get('content-type') == 'application/json' else response.text
error_data = response.json() if response.headers.get(
'content-type') == 'application/json' else response.text
raise Exception(
f"ElevenLabs TTS request failed: {response.status_code} - {error_data}"
)
except requests.exceptions.Timeout:
raise Exception("ElevenLabs TTS request timed out")
except requests.exceptions.RequestException as e:
raise Exception(f"ElevenLabs TTS network error: {str(e)}")
except Exception as e:
logger.bind(tag=TAG).error(f"ElevenLabs TTS error: {str(e)}")
raise
def get_available_voices(self):
"""
Helper method to get available voices from ElevenLabs
"""
headers = {
"Accept": "application/json",
"xi-api-key": self.api_key
}
try:
response = requests.get(
"https://api.elevenlabs.io/v1/voices",
headers=headers
)
if response.status_code == 200:
voices = response.json()["voices"]
return [(v["voice_id"], v["name"]) for v in voices]
else:
logger.bind(tag=TAG).error(f"Failed to fetch voices: {response.status_code}")
logger.bind(tag=TAG).error(
f"Failed to fetch voices: {response.status_code}")
return []
except Exception as e:
logger.bind(tag=TAG).error(f"Error fetching voices: {str(e)}")
return []
return []

View file

@ -1,188 +1,319 @@
import base64
import requests
import ormsgpack
from pathlib import Path
from pydantic import BaseModel, Field, conint, model_validator
from typing_extensions import Annotated
from typing import Literal
from core.utils.util import check_model_key, parse_string_to_list
from core.providers.tts.base import TTSProviderBase
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
class ServeReferenceAudio(BaseModel):
audio: bytes
text: str
@model_validator(mode="before")
def decode_audio(cls, values):
audio = values.get("audio")
if (
isinstance(audio, str) and len(audio) > 255
): # Check if audio is a string (Base64)
): # Check if audio is a string (Base64)
try:
values["audio"] = base64.b64decode(audio)
except Exception as e:
# If the audio is not a valid base64 string, we will just ignore it and let the server handle it
pass
return values
def __repr__(self) -> str:
return f"ServeReferenceAudio(text={self.text!r}, audio_size={len(self.audio)})"
class ServeTTSRequest(BaseModel):
text: str
chunk_length: Annotated[int, conint(ge=100, le=300, strict=True)] = 200
# Audio format
format: Literal["wav", "pcm", "mp3"] = "wav"
# References audios for in-context learning
references: list[ServeReferenceAudio] = []
# Reference id
# For example, if you want use https://fish.audio/m/7f92f8afb8ec43bf81429cc1c9199cb1/
# Just pass 7f92f8afb8ec43bf81429cc1c9199cb1
reference_id: str | None = None
seed: int | None = None
use_memory_cache: Literal["on", "off"] = "off"
# Normalize text for en & zh, this increase stability for numbers
normalize: bool = True
# not usually used below
streaming: bool = False
max_new_tokens: int = 1024
top_p: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7
repetition_penalty: Annotated[float, Field(ge=0.9, le=2.0, strict=True)] = 1.2
temperature: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7
class Config:
# Allow arbitrary types for pytorch related types
arbitrary_types_allowed = True
def audio_to_bytes(file_path):
if not file_path or not Path(file_path).exists():
return None
with open(file_path, "rb") as wav_file:
wav = wav_file.read()
return wav
def read_ref_text(ref_text):
path = Path(ref_text)
if path.exists() and path.is_file():
with path.open("r", encoding="utf-8") as file:
return file.read()
return ref_text
path = Path(ref_text)
if path.exists() and path.is_file():
with path.open("r", encoding="utf-8") as file:
return file.read()
return ref_text
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.reference_id = (
None if not config.get("reference_id") else config.get("reference_id")
)
self.reference_audio = parse_string_to_list(
config.get('ref_audio')if config.get('ref_audio') else config.get("reference_audio")
)
self.reference_text = parse_string_to_list(
config.get('ref_text')if config.get('ref_text') else config.get("reference_text")
)
self.format = config.get("response_format", "wav")
self.audio_file_type = config.get("response_format", "wav")
self.api_key = config.get("api_key", "YOUR_API_KEY")
model_key_msg = check_model_key("FishSpeech TTS", self.api_key)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
return
self.normalize = str(config.get("normalize", True)).lower() in (
"true",
"1",
"yes",
)
# 处理空字符串的情况
self.reference_audio = parse_string_to_list(
config.get('ref_audio')if config.get('ref_audio') else config.get("reference_audio")
)
self.reference_text = parse_string_to_list(
config.get('ref_text')if config.get('ref_text') else config.get("reference_text")
)
self.format = config.get("response_format", "wav")
self.audio_file_type = config.get("response_format", "wav")
self.api_key = config.get("api_key", "YOUR_API_KEY")
model_key_msg = check_model_key("FishSpeech TTS", self.api_key)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
return
self.normalize = str(config.get("normalize", True)).lower() in (
"true",
"1",
"yes",
)
# Handle empty string cases
channels = config.get("channels", "1")
rate = config.get("rate", "44100")
max_new_tokens = config.get("max_new_tokens", "1024")
chunk_length = config.get("chunk_length", "200")
self.channels = int(channels) if channels else 1
self.rate = int(rate) if rate else 44100
self.max_new_tokens = int(max_new_tokens) if max_new_tokens else 1024
self.chunk_length = int(chunk_length) if chunk_length else 200
# 处理空字符串的情况
# Handle empty string cases
top_p = config.get("top_p", "0.7")
temperature = config.get("temperature", "0.7")
repetition_penalty = config.get("repetition_penalty", "1.2")
self.top_p = float(top_p) if top_p else 0.7
self.temperature = float(temperature) if temperature else 0.7
self.repetition_penalty = (
float(repetition_penalty) if repetition_penalty else 1.2
)
self.streaming = str(config.get("streaming", False)).lower() in (
"true",
"1",
"yes",
)
self.use_memory_cache = config.get("use_memory_cache", "on")
self.seed = int(config.get("seed")) if config.get("seed") else None
self.api_url = config.get("api_url", "http://127.0.0.1:8080/v1/tts")
async def text_to_speak(self, text, output_file):
# Prepare reference data
byte_audios = [audio_to_bytes(ref_audio) for ref_audio in self.reference_audio]
ref_texts = [read_ref_text(ref_text) for ref_text in self.reference_text]
data = {
"text": text,
"references": [
ServeReferenceAudio(audio=audio if audio else b"", text=text)
for text, audio in zip(ref_texts, byte_audios)
],
"reference_id": self.reference_id,
"normalize": self.normalize,
"format": self.format,
"max_new_tokens": self.max_new_tokens,
"chunk_length": self.chunk_length,
"top_p": self.top_p,
"repetition_penalty": self.repetition_penalty,
"temperature": self.temperature,
"streaming": self.streaming,
"use_memory_cache": self.use_memory_cache,
"seed": self.seed,
}
pydantic_data = ServeTTSRequest(**data)
response = requests.post(
self.api_url,
data=ormsgpack.packb(
pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC
),
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/msgpack",
},
)
if response.status_code == 200:
audio_content = response.content
if output_file:
with open(output_file, "wb") as audio_file:
audio_file.write(audio_content)
else:
return audio_content
else:
error_msg = f"Request failed with status code {response.status_code}"
print(error_msg)
print(response.json())
raise Exception(error_msg)
raise Exception(error_msg)

View file

@ -1,103 +1,185 @@
import requests
from config.logger import setup_logging
from core.providers.tts.base import TTSProviderBase
from core.utils.util import parse_string_to_list
TAG = __name__
logger = setup_logging()
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.url = config.get("url")
self.text_lang = config.get("text_lang", "zh")
self.ref_audio_path = config.get('ref_audio') if config.get('ref_audio') else config.get("ref_audio_path")
self.prompt_text = config.get('ref_text') if config.get('ref_text') else config.get("prompt_text")
self.ref_audio_path = config.get('ref_audio') if config.get(
'ref_audio') else config.get("ref_audio_path")
self.prompt_text = config.get('ref_text') if config.get(
'ref_text') else config.get("prompt_text")
self.prompt_lang = config.get("prompt_lang", "zh")
# 处理空字符串的情况
# Handle empty string cases
top_k = config.get("top_k", "5")
top_p = config.get("top_p", "1")
temperature = config.get("temperature", "1")
batch_threshold = config.get("batch_threshold", "0.75")
batch_size = config.get("batch_size", "1")
speed_factor = config.get("speed_factor", "1.0")
seed = config.get("seed", "-1")
repetition_penalty = config.get("repetition_penalty", "1.35")
self.top_k = int(top_k) if top_k else 5
self.top_p = float(top_p) if top_p else 1
self.temperature = float(temperature) if temperature else 1
self.batch_threshold = float(batch_threshold) if batch_threshold else 0.75
self.batch_threshold = float(
batch_threshold) if batch_threshold else 0.75
self.batch_size = int(batch_size) if batch_size else 1
self.speed_factor = float(speed_factor) if speed_factor else 1.0
self.seed = int(seed) if seed else -1
self.repetition_penalty = (
float(repetition_penalty) if repetition_penalty else 1.35
)
self.text_split_method = config.get("text_split_method", "cut0")
self.split_bucket = str(config.get("split_bucket", True)).lower() in (
"true",
"1",
"yes",
)
self.return_fragment = str(config.get("return_fragment", False)).lower() in (
"true",
"1",
"yes",
)
self.streaming_mode = str(config.get("streaming_mode", False)).lower() in (
"true",
"1",
"yes",
)
self.parallel_infer = str(config.get("parallel_infer", True)).lower() in (
"true",
"1",
"yes",
)
self.aux_ref_audio_paths = parse_string_to_list(
config.get("aux_ref_audio_paths")
)
self.audio_file_type = config.get("format", "wav")
async def text_to_speak(self, text, output_file):
request_json = {
"text": text,
"text_lang": self.text_lang,
"ref_audio_path": self.ref_audio_path,
"aux_ref_audio_paths": self.aux_ref_audio_paths,
"prompt_text": self.prompt_text,
"prompt_lang": self.prompt_lang,
"top_k": self.top_k,
"top_p": self.top_p,
"temperature": self.temperature,
"text_split_method": self.text_split_method,
"batch_size": self.batch_size,
"batch_threshold": self.batch_threshold,
"split_bucket": self.split_bucket,
"return_fragment": self.return_fragment,
"speed_factor": self.speed_factor,
"streaming_mode": self.streaming_mode,
"seed": self.seed,
"parallel_infer": self.parallel_infer,
"repetition_penalty": self.repetition_penalty,
}
resp = requests.post(self.url, json=request_json)
if resp.status_code == 200:
if output_file:
with open(output_file, "wb") as file:
file.write(resp.content)
else:
return resp.content
else:
error_msg = f"GPT_SoVITS_V2 TTS请求失败: {resp.status_code} - {resp.text}"
error_msg = f"GPT_SoVITS_V2 TTS request failed: {resp.status_code} - {resp.text}"
logger.bind(tag=TAG).error(error_msg)
raise Exception(error_msg)

View file

@ -1,64 +1,111 @@
import requests
from config.logger import setup_logging
from core.providers.tts.base import TTSProviderBase
from core.utils.util import parse_string_to_list
TAG = __name__
logger = setup_logging()
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.url = config.get("url")
self.refer_wav_path = config.get('ref_audio')if config.get('ref_audio') else config.get("refer_wav_path")
self.prompt_text = config.get('ref_text')if config.get('ref_text') else config.get("prompt_text")
self.prompt_language = config.get("prompt_language")
self.text_language = config.get("text_language", "audo")
# 处理空字符串的情况
# Handle empty string cases
top_k = config.get("top_k", "15")
top_p = config.get("top_p", "1.0")
temperature = config.get("temperature", "1.0")
sample_steps = config.get("sample_steps", "32")
speed = config.get("speed", "1.0")
self.top_k = int(top_k) if top_k else 15
self.top_p = float(top_p) if top_p else 1.0
self.temperature = float(temperature) if temperature else 1.0
self.sample_steps = int(sample_steps) if sample_steps else 32
self.speed = float(speed) if speed else 1.0
self.cut_punc = config.get("cut_punc", "")
self.inp_refs = parse_string_to_list(config.get("inp_refs"))
self.if_sr = str(config.get("if_sr", False)).lower() in ("true", "1", "yes")
self.audio_file_type = config.get("format", "wav")
async def text_to_speak(self, text, output_file):
request_params = {
"refer_wav_path": self.refer_wav_path,
"prompt_text": self.prompt_text,
"prompt_language": self.prompt_language,
"text": text,
"text_language": self.text_language,
"top_k": self.top_k,
"top_p": self.top_p,
"temperature": self.temperature,
"cut_punc": self.cut_punc,
"speed": self.speed,
"inp_refs": self.inp_refs,
"sample_steps": self.sample_steps,
"if_sr": self.if_sr,
}
resp = requests.get(self.url, params=request_params)
if resp.status_code == 200:
if output_file:
with open(output_file, "wb") as file:
file.write(resp.content)
else:
return resp.content
else:
error_msg = f"GPT_SoVITS_V3 TTS请求失败: {resp.status_code} - {resp.text}"
error_msg = f"GPT_SoVITS_V3 TTS request failed: {resp.status_code} - {resp.text}"
logger.bind(tag=TAG).error(error_msg)
raise Exception(error_msg)
raise Exception(error_msg)

File diff suppressed because it is too large Load diff

View file

@ -29,27 +29,28 @@ class TTSProvider(TTSProviderBase):
self.before_stop_play_files = []
self.segment_count = 0
# 创建Opus编码器 需注意接口返回的采样率为24000
# Create Opus encoder Note: interface returns sample rate of 24000
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
sample_rate=24000, channels=1, frame_size_ms=60
)
# 文本缓冲区和PCM缓冲区
# Text buffer and PCM buffer
self.text_buffer = ""
self.pcm_buffer = bytearray()
def tts_text_priority_thread(self):
"""流式文本处理线程"""
"""Streaming text processing thread"""
while not self.conn.stop_event.is_set():
try:
message = self.tts_text_queue.get(timeout=1)
if message.sentence_type == SentenceType.FIRST:
# 初始化参数
# Initialize parameters
self.tts_stop_request = False
self.processed_chars = 0
self.tts_text_buff = []
self.segment_count = 0
self.before_stop_play_files.clear()
elif ContentType.TEXT == message.content_type:
self.tts_text_buff.append(message.content_detail)
segment_text = self._get_segment_text()
@ -58,35 +59,39 @@ class TTSProvider(TTSProviderBase):
elif ContentType.FILE == message.content_type:
logger.bind(tag=TAG).info(
f"添加音频文件到待播放列表: {message.content_file}"
f"Adding audio file to playback queue: {message.content_file}"
)
if message.content_file and os.path.exists(message.content_file):
# 先处理文件音频数据
file_audio = self._process_audio_file(message.content_file)
# Process file audio data first
file_audio = self._process_audio_file(
message.content_file)
self.before_stop_play_files.append(
(file_audio, message.content_detail)
)
if message.sentence_type == SentenceType.LAST:
# 处理剩余的文本
# Process remaining text
self._process_remaining_text(True)
except queue.Empty:
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
f"Failed to process TTS text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}"
)
def _process_remaining_text(self, is_last=False):
"""处理剩余的文本并生成语音
"""Process remaining text and generate speech
Returns:
bool: 是否成功处理了文本
bool: Whether text was successfully processed
"""
full_text = "".join(self.tts_text_buff)
remaining_text = full_text[self.processed_chars :]
remaining_text = full_text[self.processed_chars:]
if remaining_text:
segment_text = textUtils.get_string_no_punctuation_or_emoji(remaining_text)
segment_text = textUtils.get_string_no_punctuation_or_emoji(
remaining_text)
if segment_text:
self.to_tts_single_stream(segment_text, is_last)
self.processed_chars += len(full_text)
@ -103,27 +108,27 @@ class TTSProvider(TTSProviderBase):
asyncio.run(self.text_to_speak(text, is_last))
except Exception as e:
logger.bind(tag=TAG).warning(
f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
f"Speech generation failed {5 - max_repeat_time + 1} times: {text}, error: {e}"
)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
f"语音生成成功: {text},重试{5 - max_repeat_time}次"
)
else:
logger.bind(tag=TAG).error(
f"语音生成失败: {text},请检查网络或服务是否正常"
)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
f"Speech generation successful: {text}, retried {5 - max_repeat_time} times"
)
else:
logger.bind(tag=TAG).error(
f"Speech generation failed: {text}, please check network or service status"
)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
finally:
return None
async def text_to_speak(self, text, is_last):
"""流式处理TTS音频,每句只推送一次音频列表"""
"""Stream process TTS audio, push audio list only once per sentence"""
payload = {"text": text, "character": self.voice}
frame_bytes = int(
self.opus_encoder.sample_rate
* self.opus_encoder.channels # 1
@ -131,25 +136,25 @@ class TTSProvider(TTSProviderBase):
/ 1000
* 2
) # 16-bit = 2 bytes
try:
async with aiohttp.ClientSession() as session:
async with session.post(self.api_url, json=payload, timeout=10) as resp:
if resp.status != 200:
logger.bind(tag=TAG).error(
f"TTS请求失败: {resp.status}, {await resp.text()}"
f"TTS request failed: {resp.status}, {await resp.text()}"
)
self.tts_audio_queue.put((SentenceType.LAST, [], None))
return
self.pcm_buffer.clear()
opus_datas_cache = []
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
# 处理音频流数据
# Process audio stream data
async for chunk in resp.content.iter_any():
data = chunk[0] if isinstance(chunk, (list, tuple)) else chunk
data = chunk[0] if isinstance(
chunk, (list, tuple)) else chunk
if not data:
continue
@ -161,8 +166,9 @@ class TTSProvider(TTSProviderBase):
opus = self.opus_encoder.encode_pcm_to_opus(
frame, end_of_stream=False
)
if opus:
if self.segment_count < 10: # 前10个片段直接发送
if self.segment_count < 10: # Send first 10 segments directly
self.tts_audio_queue.put(
(SentenceType.MIDDLE, opus, None)
)
@ -170,72 +176,74 @@ class TTSProvider(TTSProviderBase):
else:
opus_datas_cache.extend(opus)
# flush 剩余不足一帧的数据
# Flush remaining data that doesn't fill a complete frame
if self.pcm_buffer:
opus = self.opus_encoder.encode_pcm_to_opus(
bytes(self.pcm_buffer), end_of_stream=True
)
if opus:
if self.segment_count < 10: # 前10个片段直接发送
# 直接发送
if self.segment_count < 10: # Send first 10 segments directly
# Send directly
self.tts_audio_queue.put(
(SentenceType.MIDDLE, opus, None)
)
self.segment_count += 1
else:
# 后续片段缓存
# Cache subsequent segments
opus_datas_cache.extend(opus)
self.pcm_buffer.clear()
# 如果不是前10个片段,发送缓存的数据
# If not in first 10 segments, send cached data
if self.segment_count >= 10 and opus_datas_cache:
self.tts_audio_queue.put(
(SentenceType.MIDDLE, opus_datas_cache, None)
)
# 如果是最后一段,输出音频获取完毕
# If this is the last segment, audio acquisition complete
if is_last:
self._process_before_stop_play_files()
except Exception as e:
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
logger.bind(tag=TAG).error(f"TTS request exception: {e}")
self.tts_audio_queue.put((SentenceType.LAST, [], None))
async def close(self):
"""资源清理"""
"""Resource cleanup"""
await super().close()
if hasattr(self, "opus_encoder"):
self.opus_encoder.close()
def to_tts(self, text: str) -> list:
"""非流式TTS处理,用于测试及保存音频文件的场景
"""Non-streaming TTS processing for testing and saving audio files
Args:
text: 要转换的文本
text: Text to convert
Returns:
list: 返回opus编码后的音频数据列表
list: Returns opus-encoded audio data list
"""
start_time = time.time()
text = MarkdownCleaner.clean_markdown(text)
payload = {"text": text, "character": self.character}
try:
with requests.post(self.api_url, json=payload, timeout=5) as response:
if response.status_code != 200:
logger.bind(tag=TAG).error(
f"TTS请求失败: {response.status_code}, {response.text}"
f"TTS request failed: {response.status_code}, {response.text}"
)
return []
logger.info(f"TTS请求成功: {text}, 耗时: {time.time() - start_time}秒")
logger.info(
f"TTS request successful: {text}, time cost: {time.time() - start_time} seconds")
# 使用opus编码器处理PCM数据
# Use opus encoder to process PCM data
opus_datas = []
pcm_data = response.content
# 计算每帧的字节数
# Calculate bytes per frame
frame_bytes = int(
self.opus_encoder.sample_rate
* self.opus_encoder.channels
@ -244,21 +252,22 @@ class TTSProvider(TTSProviderBase):
* 2
)
# 分帧处理PCM数据
# Process PCM data frame by frame
for i in range(0, len(pcm_data), frame_bytes):
frame = pcm_data[i : i + frame_bytes]
frame = pcm_data[i: i + frame_bytes]
if len(frame) < frame_bytes:
# 最后一帧可能不足,用0填充
# Last frame might be insufficient, pad with zeros
frame = frame + b"\x00" * (frame_bytes - len(frame))
opus = self.opus_encoder.encode_pcm_to_opus(
frame, end_of_stream=(i + frame_bytes >= len(pcm_data))
)
if opus:
opus_datas.extend(opus)
return opus_datas
except Exception as e:
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
return []
logger.bind(tag=TAG).error(f"TTS request exception: {e}")
return []

View file

@ -14,7 +14,6 @@ from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
TAG = __name__
logger = setup_logging()
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
@ -24,68 +23,69 @@ class TTSProvider(TTSProviderBase):
self.api_url = config.get("api_url")
self.audio_format = "pcm"
self.before_stop_play_files = []
self.segment_count = 0 # 添加片段计数器
# 创建Opus编码器
self.segment_count = 0 # Add segment counter
# Create Opus encoder
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
sample_rate=16000, channels=1, frame_size_ms=60
)
# 添加文本缓冲区
# Add text buffer
self.text_buffer = ""
# PCM缓冲区
# PCM buffer
self.pcm_buffer = bytearray()
###################################################################################
# linkerai单流式TTS重写父类的方法--开始
# linkerai single-stream TTS override parent class methods - Start
###################################################################################
def tts_text_priority_thread(self):
"""流式文本处理线程"""
"""Streaming text processing thread"""
while not self.conn.stop_event.is_set():
try:
message = self.tts_text_queue.get(timeout=1)
if message.sentence_type == SentenceType.FIRST:
# 初始化参数
# Initialize parameters
self.tts_stop_request = False
self.processed_chars = 0
self.tts_text_buff = []
self.segment_count = 0
self.before_stop_play_files.clear()
elif ContentType.TEXT == message.content_type:
self.tts_text_buff.append(message.content_detail)
segment_text = self._get_segment_text()
if segment_text:
self.to_tts_single_stream(segment_text)
elif ContentType.FILE == message.content_type:
logger.bind(tag=TAG).info(
f"添加音频文件到待播放列表: {message.content_file}"
f"Adding audio file to playback queue: {message.content_file}"
)
if message.content_file and os.path.exists(message.content_file):
# 先处理文件音频数据
# Process file audio data first
file_audio = self._process_audio_file(message.content_file)
self.before_stop_play_files.append(
(file_audio, message.content_detail)
)
if message.sentence_type == SentenceType.LAST:
# 处理剩余的文本
# Process remaining text
self._process_remaining_text(True)
except queue.Empty:
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
f"Failed to process TTS text: {str(e)}, type: {type(e).__name__}, stack: {traceback.format_exc()}"
)
def _process_remaining_text(self, is_last=False):
"""处理剩余的文本并生成语音
"""Process remaining text and generate speech
Returns:
bool: 是否成功处理了文本
bool: Whether text was successfully processed
"""
full_text = "".join(self.tts_text_buff)
remaining_text = full_text[self.processed_chars :]
@ -98,7 +98,7 @@ class TTSProvider(TTSProviderBase):
self._process_before_stop_play_files()
else:
self._process_before_stop_play_files()
def to_tts_single_stream(self, text, is_last=False):
try:
max_repeat_time = 5
@ -107,37 +107,38 @@ class TTSProvider(TTSProviderBase):
asyncio.run(self.text_to_speak(text, is_last))
except Exception as e:
logger.bind(tag=TAG).warning(
f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
f"Speech generation failed {5 - max_repeat_time + 1} times: {text}, error: {e}"
)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
f"语音生成成功: {text},重试{5 - max_repeat_time}次"
)
else:
logger.bind(tag=TAG).error(
f"语音生成失败: {text},请检查网络或服务是否正常"
)
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
f"Speech generation successful: {text}, retried {5 - max_repeat_time} times"
)
else:
logger.bind(tag=TAG).error(
f"Speech generation failed: {text}, please check network or service status"
)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
finally:
return None
###################################################################################
# linkerai单流式TTS重写父类的方法--结束
# linkerai single-stream TTS override parent class methods - End
###################################################################################
async def text_to_speak(self, text, is_last):
"""流式处理TTS音频,每句只推送一次音频列表"""
"""Stream process TTS audio, push audio list only once per sentence"""
await self._tts_request(text, is_last)
async def close(self):
"""资源清理"""
"""Resource cleanup"""
await super().close()
if hasattr(self, "opus_encoder"):
self.opus_encoder.close()
async def _tts_request(self, text: str, is_last: bool) -> None:
params = {
"tts_text": text,
@ -146,14 +147,15 @@ class TTSProvider(TTSProviderBase):
"stream": "true",
"target_sr": 16000,
"audio_format": "pcm",
"instruct_text": "请生成一段自然流畅的语音",
"instruct_text": "Please generate natural and fluent speech",
}
headers = {
"Authorization": f"Bearer {self.access_token}",
"Content-Type": "application/json",
}
# 一帧 PCM 所需字节数:60 ms &times; 16 kHz &times; 1 ch &times; 2 B = 1 920
# PCM bytes per frame: 60 ms × 16 kHz × 1 ch × 2 B = 1920
frame_bytes = int(
self.opus_encoder.sample_rate
* self.opus_encoder.channels # 1
@ -161,94 +163,93 @@ class TTSProvider(TTSProviderBase):
/ 1000
* 2
) # 16-bit = 2 bytes
try:
async with aiohttp.ClientSession() as session:
async with session.get(
self.api_url, params=params, headers=headers, timeout=10
) as resp:
if resp.status != 200:
logger.bind(tag=TAG).error(
f"TTS请求失败: {resp.status}, {await resp.text()}"
f"TTS request failed: {resp.status}, {await resp.text()}"
)
self.tts_audio_queue.put((SentenceType.LAST, [], None))
return
self.pcm_buffer.clear()
opus_datas_cache = []
self.tts_audio_queue.put((SentenceType.FIRST, [], text))
# 兼容 iter_chunked / iter_chunks / iter_any
# Compatible with iter_chunked / iter_chunks / iter_any
async for chunk in resp.content.iter_any():
data = chunk[0] if isinstance(chunk, (list, tuple)) else chunk
if not data:
continue
# 拼到 buffer
# Append to buffer
self.pcm_buffer.extend(data)
# 够一帧就编码
# Encode when enough for one frame
while len(self.pcm_buffer) >= frame_bytes:
frame = bytes(self.pcm_buffer[:frame_bytes])
del self.pcm_buffer[:frame_bytes]
opus = self.opus_encoder.encode_pcm_to_opus(
frame, end_of_stream=False
)
if opus:
if self.segment_count < 10: # 前10个片段直接发送
if self.segment_count < 10: # Send first 10 segments directly
self.tts_audio_queue.put(
(SentenceType.MIDDLE, opus, None)
)
self.segment_count += 1
else:
opus_datas_cache.extend(opus)
# flush 剩余不足一帧的数据
# Flush remaining data that doesn't fill a complete frame
if self.pcm_buffer:
opus = self.opus_encoder.encode_pcm_to_opus(
bytes(self.pcm_buffer), end_of_stream=True
)
if opus:
if self.segment_count < 10: # 前10个片段直接发送
# 直接发送
if self.segment_count < 10: # Send first 10 segments directly
# Send directly
self.tts_audio_queue.put(
(SentenceType.MIDDLE, opus, None)
)
self.segment_count += 1
else:
# 后续片段缓存
# Cache subsequent segments
opus_datas_cache.extend(opus)
self.pcm_buffer.clear()
# 如果不是前10个片段,发送缓存的数据
# If not in first 10 segments, send cached data
if self.segment_count >= 10 and opus_datas_cache:
self.tts_audio_queue.put(
(SentenceType.MIDDLE, opus_datas_cache, None)
)
# 如果是最后一段,输出音频获取完毕
# If this is the last segment, audio acquisition complete
if is_last:
self._process_before_stop_play_files()
except Exception as e:
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
logger.bind(tag=TAG).error(f"TTS request exception: {e}")
self.tts_audio_queue.put((SentenceType.LAST, [], None))
def to_tts(self, text: str) -> list:
"""非流式TTS处理,用于测试及保存音频文件的场景
"""Non-streaming TTS processing for testing and saving audio files
Args:
text: 要转换的文本
text: Text to convert
Returns:
list: 返回opus编码后的音频数据列表
list: Returns opus-encoded audio data list
"""
start_time = time.time()
text = MarkdownCleaner.clean_markdown(text)
params = {
"tts_text": text,
"spk_id": self.voice,
@ -256,30 +257,31 @@ class TTSProvider(TTSProviderBase):
"stream": False,
"target_sr": 16000,
"audio_format": self.audio_format,
"instruct_text": "请生成一段自然流畅的语音",
"instruct_text": "Please generate natural and fluent speech",
}
headers = {
"Authorization": f"Bearer {self.access_token}",
"Content-Type": "application/json",
}
try:
with requests.get(
self.api_url, params=params, headers=headers, timeout=5
) as response:
if response.status_code != 200:
logger.bind(tag=TAG).error(
f"TTS请求失败: {response.status_code}, {response.text}"
f"TTS request failed: {response.status_code}, {response.text}"
)
return []
logger.info(f"TTS请求成功: {text}, 耗时: {time.time() - start_time}秒")
# 使用opus编码器处理PCM数据
logger.info(f"TTS request successful: {text}, time cost: {time.time() - start_time} seconds")
# Use opus encoder to process PCM data
opus_datas = []
pcm_data = response.content
# 计算每帧的字节数
# Calculate bytes per frame
frame_bytes = int(
self.opus_encoder.sample_rate
* self.opus_encoder.channels
@ -287,22 +289,23 @@ class TTSProvider(TTSProviderBase):
/ 1000
* 2
)
# 分帧处理PCM数据
# Process PCM data frame by frame
for i in range(0, len(pcm_data), frame_bytes):
frame = pcm_data[i : i + frame_bytes]
if len(frame) < frame_bytes:
# 最后一帧可能不足,用0填充
# Last frame might be insufficient, pad with zeros
frame = frame + b"\x00" * (frame_bytes - len(frame))
opus = self.opus_encoder.encode_pcm_to_opus(
frame, end_of_stream=(i + frame_bytes >= len(pcm_data))
)
if opus:
opus_datas.extend(opus)
return opus_datas
except Exception as e:
logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
return []
logger.bind(tag=TAG).error(f"TTS request exception: {e}")
return []

View file

@ -6,18 +6,18 @@ from datetime import datetime
from core.providers.tts.base import TTSProviderBase
from core.utils.util import parse_string_to_list
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.group_id = config.get("group_id")
self.api_key = config.get("api_key")
self.model = config.get("model")
if config.get("private_voice"):
self.voice = config.get("private_voice")
else:
self.voice = config.get("voice_id")
default_voice_setting = {
"voice_id": "female-shaonv",
"speed": 1,
@ -25,6 +25,7 @@ class TTSProvider(TTSProviderBase):
"pitch": 0,
"emotion": "happy",
}
default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]}
defult_audio_setting = {
"sample_rate": 32000,
@ -32,20 +33,23 @@ class TTSProvider(TTSProviderBase):
"format": "mp3",
"channel": 1,
}
self.voice_setting = {
**default_voice_setting,
**config.get("voice_setting", {}),
}
self.pronunciation_dict = {
**default_pronunciation_dict,
**config.get("pronunciation_dict", {}),
}
self.audio_setting = {**defult_audio_setting, **config.get("audio_setting", {})}
self.timber_weights = parse_string_to_list(config.get("timber_weights"))
if self.voice:
self.voice_setting["voice_id"] = self.voice
self.host = "api.minimax.chat"
self.api_url = f"https://{self.host}/v1/t2a_v2?GroupId={self.group_id}"
self.header = {
@ -53,13 +57,13 @@ class TTSProvider(TTSProviderBase):
"Authorization": f"Bearer {self.api_key}",
}
self.audio_file_type = defult_audio_setting.get("format", "mp3")
def generate_filename(self, extension=".mp3"):
return os.path.join(
self.output_file,
f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
)
async def text_to_speak(self, text, output_file):
request_json = {
"model": self.model,
@ -69,19 +73,21 @@ class TTSProvider(TTSProviderBase):
"pronunciation_dict": self.pronunciation_dict,
"audio_setting": self.audio_setting,
}
if type(self.timber_weights) is list and len(self.timber_weights) > 0:
request_json["timber_weights"] = self.timber_weights
request_json["voice_setting"]["voice_id"] = ""
try:
resp = requests.post(
self.api_url, json.dumps(request_json), headers=self.header
)
# 检查返回请求数据的status_code是否为0
# Check if response data status_code is 0
if resp.json()["base_resp"]["status_code"] == 0:
data = resp.json()["data"]["audio"]
audio_bytes = bytes.fromhex(data)
if output_file:
with open(output_file, "wb") as file_to_save:
file_to_save.write(audio_bytes)
@ -91,5 +97,6 @@ class TTSProvider(TTSProviderBase):
raise Exception(
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
)
except Exception as e:
raise Exception(f"{__name__} error: {e}")

View file

@ -7,18 +7,18 @@ from typing import Iterator, Optional, Union
from core.providers.tts.base import TTSProviderBase
from core.utils.util import parse_string_to_list
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.group_id = config.get("group_id")
self.api_key = config.get("api_key")
self.model = config.get("model")
if config.get("private_voice"):
self.voice = config.get("private_voice")
else:
self.voice = config.get("voice_id")
default_voice_setting = {
"voice_id": "female-shaonv",
"speed": 1,
@ -26,6 +26,7 @@ class TTSProvider(TTSProviderBase):
"pitch": 0,
"emotion": "happy",
}
default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]}
defult_audio_setting = {
"sample_rate": 32000,
@ -33,20 +34,23 @@ class TTSProvider(TTSProviderBase):
"format": "mp3",
"channel": 1,
}
self.voice_setting = {
**default_voice_setting,
**config.get("voice_setting", {}),
}
self.pronunciation_dict = {
**default_pronunciation_dict,
**config.get("pronunciation_dict", {}),
}
self.audio_setting = {**defult_audio_setting, **config.get("audio_setting", {})}
self.timber_weights = parse_string_to_list(config.get("timber_weights"))
if self.voice:
self.voice_setting["voice_id"] = self.voice
self.host = "api.minimax.chat"
self.api_url = f"https://{self.host}/v1/t2a_v2?GroupId={self.group_id}"
self.header = {
@ -54,15 +58,15 @@ class TTSProvider(TTSProviderBase):
"Authorization": f"Bearer {self.api_key}",
}
self.audio_file_type = defult_audio_setting.get("format", "mp3")
def generate_filename(self, extension=".mp3"):
return os.path.join(
self.output_file,
f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
)
async def text_to_speak(self, text, output_file):
"""非流式语音合成(保留原有实现)"""
"""Non-streaming speech synthesis (preserves original implementation)"""
request_json = {
"model": self.model,
"text": text,
@ -71,18 +75,20 @@ class TTSProvider(TTSProviderBase):
"pronunciation_dict": self.pronunciation_dict,
"audio_setting": self.audio_setting,
}
if type(self.timber_weights) is list and len(self.timber_weights) > 0:
request_json["timber_weights"] = self.timber_weights
request_json["voice_setting"]["voice_id"] = ""
try:
resp = requests.post(
self.api_url, json.dumps(request_json), headers=self.header
)
if resp.json()["base_resp"]["status_code"] == 0:
data = resp.json()["data"]["audio"]
audio_bytes = bytes.fromhex(data)
if output_file:
with open(output_file, "wb") as file_to_save:
file_to_save.write(audio_bytes)
@ -92,19 +98,21 @@ class TTSProvider(TTSProviderBase):
raise Exception(
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
)
except Exception as e:
raise Exception(f"{__name__} error: {e}")
def text_to_speak_stream(
self,
text: str,
self,
text: str,
chunk_callback: Optional[callable] = None
) -> Iterator[bytes]:
"""
流式语音合成方法
:param text: 要合成的文本
:param chunk_callback: 可选的回调函数,用于处理每个音频块
:return: 生成器,每次产生一个音频数据块(bytes)
Streaming speech synthesis method
:param text: Text to synthesize
:param chunk_callback: Optional callback function to process each audio chunk
:return: Generator that yields an audio data chunk (bytes) each time
"""
request_json = {
"model": self.model,
@ -114,11 +122,11 @@ class TTSProvider(TTSProviderBase):
"pronunciation_dict": self.pronunciation_dict,
"audio_setting": self.audio_setting,
}
if isinstance(self.timber_weights, list) and len(self.timber_weights) > 0:
request_json["timber_weights"] = self.timber_weights
request_json["voice_setting"]["voice_id"] = ""
try:
with requests.post(
self.api_url,
@ -126,67 +134,67 @@ class TTSProvider(TTSProviderBase):
headers=self.header,
stream=True
) as response:
# 检查HTTP状态码
# Check HTTP status code
if response.status_code != 200:
raise Exception(
f"HTTP error: {response.status_code}, response: {response.text}"
)
# 处理流式响应
# Process streaming response
for line in response.iter_lines():
if line: # 过滤空行
# 检查是否为数据行 (SSE格式)
if line: # Filter empty lines
# Check if it's a data line (SSE format)
if line.startswith(b'data:'):
try:
data = json.loads(line[5:].strip()) # 去掉"data:"前缀
data = json.loads(line[5:].strip()) # Remove "data:" prefix
# 检查API状态码
# Check API status code
if data.get("base_resp", {}).get("status_code", -1) != 0:
raise Exception(
f"API error: {data.get('base_resp', {}).get('status_msg')}"
)
# 跳过非音频数据块
# Skip non-audio data chunks
if "extra_info" in data:
continue
# 提取音频数据
# Extract audio data
audio_hex = data.get("data", {}).get("audio")
if audio_hex:
audio_chunk = bytes.fromhex(audio_hex)
if chunk_callback:
chunk_callback(audio_chunk)
yield audio_chunk
except json.JSONDecodeError:
# 忽略JSON解析错误(可能是心跳包等)
# Ignore JSON parsing errors (might be heartbeat packets, etc.)
continue
except Exception as e:
raise e
except Exception as e:
raise Exception(f"{__name__} stream error: {e}")
def save_stream_to_file(
self,
text: str,
self,
text: str,
output_file: Optional[str] = None,
progress_callback: Optional[callable] = None
) -> str:
"""
流式合成并保存到文件
:param text: 要合成的文本
:param output_file: 输出文件路径,如果为None则自动生成
:param progress_callback: 可选的回调函数,接收已写入的字节数
:return: 保存的文件路径
Stream synthesis and save to file
:param text: Text to synthesize
:param output_file: Output file path, auto-generated if None
:param progress_callback: Optional callback function that receives bytes written
:return: Saved file path
"""
if not output_file:
output_file = self.generate_filename(extension=f".{self.audio_file_type}")
os.makedirs(os.path.dirname(output_file), exist_ok=True)
total_bytes = 0
try:
with open(output_file, "wb") as audio_file:
for audio_chunk in self.text_to_speak_stream(text):
@ -195,18 +203,21 @@ class TTSProvider(TTSProviderBase):
total_bytes += len(audio_chunk)
if progress_callback:
progress_callback(total_bytes)
return output_file
except Exception as e:
# 清理可能创建的不完整文件
# Clean up potentially created incomplete file
if os.path.exists(output_file):
os.remove(output_file)
raise e
def stream_to_audio_player(self, text: str, player_command: list = None):
"""
流式合成并直接播放音频
:param text: 要合成的文本
:param player_command: 音频播放器命令,默认使用mpv
Stream synthesis and play audio directly
:param text: Text to synthesize
:param player_command: Audio player command, defaults to mpv
"""
if player_command is None:
player_command = ["mpv", "--no-cache", "--no-terminal", "--", "fd://0"]
@ -223,8 +234,9 @@ class TTSProvider(TTSProviderBase):
for audio_chunk in self.text_to_speak_stream(text):
player_process.stdin.write(audio_chunk)
player_process.stdin.flush()
player_process.stdin.close()
player_process.wait()
except Exception as e:
raise Exception(f"Audio player error: {e}")
raise Exception(f"Audio player error: {e}")

View file

@ -15,8 +15,8 @@ class TTSProvider(TTSProviderBase):
self.group_id = config.get("group_id")
self.api_key = config.get("api_key")
self.model = config.get("model")
# 初始化语音设置
# Initialize voice settings
default_voice_setting = {
"voice_id": "female-shaonv",
"speed": 1,
@ -24,52 +24,59 @@ class TTSProvider(TTSProviderBase):
"pitch": 0,
"emotion": "happy",
}
default_pronunciation_dict = {"tone": ["处理/(chu3)(li3)", "危险/dangerous"]}
default_pronunciation_dict = {
"tone": ["处理/(chu3)(li3)", "危险/dangerous"]}
default_audio_setting = {
"sample_rate": 32000,
"bitrate": 128000,
"format": "mp3",
"channel": 1,
}
# 合并配置
# Merge configurations
self.voice_setting = {
**default_voice_setting,
**config.get("voice_setting", {}),
}
self.pronunciation_dict = {
**default_pronunciation_dict,
**config.get("pronunciation_dict", {}),
}
self.audio_setting = {
**default_audio_setting,
**default_audio_setting,
**config.get("audio_setting", {})
}
self.timber_weights = parse_string_to_list(config.get("timber_weights"))
# 设置语音ID
self.timber_weights = parse_string_to_list(
config.get("timber_weights"))
# Set voice ID
if config.get("private_voice"):
self.voice_setting["voice_id"] = config.get("private_voice")
elif config.get("voice_id"):
self.voice_setting["voice_id"] = config.get("voice_id")
# WebSocket配置
# WebSocket configuration
self.ws_url = "wss://api.minimaxi.com/ws/v1/t2a_v2"
self.headers = {
"Authorization": f"Bearer {self.api_key}",
"GroupId": self.group_id
}
self.audio_file_type = self.audio_setting.get("format", "mp3")
def generate_filename(self, extension=".mp3"):
"""生成唯一的音频文件名"""
"""Generate unique audio filename"""
return os.path.join(
self.output_file,
f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
)
async def _establish_connection(self):
"""建立WebSocket连接"""
"""Establish WebSocket connection"""
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
@ -80,17 +87,19 @@ class TTSProvider(TTSProviderBase):
additional_headers=self.headers,
ssl=ssl_context
)
connected = json.loads(await ws.recv())
if connected.get("event") == "connected_success":
print("连接成功")
print("Connection successful")
return ws
return None
except Exception as e:
print(f"连接失败: {e}")
print(f"Connection failed: {e}")
return None
async def _start_task(self, websocket):
"""发送任务开始请求"""
"""Send task start request"""
start_msg = {
"event": "task_start",
"model": self.model,
@ -98,7 +107,7 @@ class TTSProvider(TTSProviderBase):
"pronunciation_dict": self.pronunciation_dict,
"audio_setting": self.audio_setting
}
if self.timber_weights and len(self.timber_weights) > 0:
start_msg["timber_weights"] = self.timber_weights
start_msg["voice_setting"]["voice_id"] = ""
@ -108,7 +117,7 @@ class TTSProvider(TTSProviderBase):
return response.get("event") == "task_started"
async def _continue_task(self, websocket, text):
"""发送继续请求并收集音频数据"""
"""Send continue request and collect audio data"""
await websocket.send(json.dumps({
"event": "task_continue",
"text": text
@ -121,36 +130,37 @@ class TTSProvider(TTSProviderBase):
audio_chunks.append(response["data"]["audio"])
if response.get("is_final"):
break
return "".join(audio_chunks)
async def _close_connection(self, websocket):
"""关闭连接"""
"""Close connection"""
if websocket:
await websocket.send(json.dumps({"event": "task_finish"}))
await websocket.close()
print("连接已关闭")
print("Connection closed")
async def text_to_speak(self, text, output_file=None):
"""主方法:文本转语音"""
"""Main method: text to speech"""
ws = await self._establish_connection()
if not ws:
raise Exception("无法建立WebSocket连接")
raise Exception("Unable to establish WebSocket connection")
try:
if not await self._start_task(ws):
raise Exception("任务启动失败")
raise Exception("Task start failed")
hex_audio = await self._continue_task(ws, text)
audio_bytes = bytes.fromhex(hex_audio)
# 保存到文件或返回二进制数据
# Save to file or return binary data
if output_file:
with open(output_file, "wb") as f:
f.write(audio_bytes)
print(f"音频已保存为{output_file}")
print(f"Audio saved as {output_file}")
return output_file
else:
# 返回音频二进制数据(不播放)
# Return audio binary data (no playback)
return audio_bytes
finally:
@ -158,23 +168,22 @@ class TTSProvider(TTSProviderBase):
async def main():
"""测试用主函数"""
# 示例配置
"""Test main function"""
# Example configuration
config = {
"group_id": "YOUR_GROUP_ID", # 替换为实际的group_id
"api_key": "YOUR_API_KEY", # 替换为实际的api_key
"model": "your-model", # 替换为实际的模型名称
"group_id": "YOUR_GROUP_ID", # Replace with actual group_id
"api_key": "YOUR_API_KEY", # Replace with actual api_key
"model": "your-model", # Replace with actual model name
"voice_id": "male-qn-qingse",
"voice_setting": {
"speed": 1.2,
"emotion": "happy"
}
}
tts = TTSProvider(config, delete_audio_file=True)
output_file = tts.generate_filename()
await tts.text_to_speak("这是一个测试文本,用于验证流式语音合成功能", output_file)
await tts.text_to_speak("This is a test text to verify streaming speech synthesis functionality", output_file)
if __name__ == "__main__":
asyncio.run(main())
asyncio.run(main())

View file

@ -11,7 +11,8 @@ class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.api_key = config.get("api_key")
self.api_url = config.get("api_url", "https://api.openai.com/v1/audio/speech")
self.api_url = config.get(
"api_url", "https://api.openai.com/v1/audio/speech")
self.model = config.get("model", "tts-1")
if config.get("private_voice"):
self.voice = config.get("private_voice")
@ -20,11 +21,11 @@ class TTSProvider(TTSProviderBase):
self.response_format = config.get("format", "wav")
self.audio_file_type = config.get("format", "wav")
# 处理空字符串的情况
# Handle empty string case
speed = config.get("speed", "1.0")
self.speed = float(speed) if speed else 1.0
self.output_file = config.get("output_dir", "tmp/")
model_key_msg = check_model_key("TTS", self.api_key)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
@ -34,6 +35,7 @@ class TTSProvider(TTSProviderBase):
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
data = {
"model": self.model,
"input": text,
@ -41,7 +43,9 @@ class TTSProvider(TTSProviderBase):
"response_format": "wav",
"speed": self.speed,
}
response = requests.post(self.api_url, json=data, headers=headers)
if response.status_code == 200:
if output_file:
with open(output_file, "wb") as audio_file:
@ -50,5 +54,5 @@ class TTSProvider(TTSProviderBase):
return response.content
else:
raise Exception(
f"OpenAI TTS请求失败: {response.status_code} - {response.text}"
f"OpenAI TTS request failed: {response.status_code} - {response.text}"
)

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