mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
fixed agent template
This commit is contained in:
parent
903f8aaecc
commit
25b24261b9
3 changed files with 1278 additions and 0 deletions
607
main/xiaozhi-server/DEVICE_ACTIVATION_GUIDE.md
Normal file
607
main/xiaozhi-server/DEVICE_ACTIVATION_GUIDE.md
Normal file
|
|
@ -0,0 +1,607 @@
|
||||||
|
# Device Activation and Registration Guide
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
1. [Overview](#overview)
|
||||||
|
2. [Architecture](#architecture)
|
||||||
|
3. [Activation Methods](#activation-methods)
|
||||||
|
4. [Step-by-Step Process](#step-by-step-process)
|
||||||
|
5. [Configuration](#configuration)
|
||||||
|
6. [Troubleshooting](#troubleshooting)
|
||||||
|
7. [API Reference](#api-reference)
|
||||||
|
8. [Database Schema](#database-schema)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
The Xiaozhi ESP32 Server system uses a secure device activation mechanism to register and manage IoT devices. This system ensures that only authorized devices can connect to the server and prevents unauthorized access.
|
||||||
|
|
||||||
|
### Key Components
|
||||||
|
|
||||||
|
- **Manager API** (Port 8002): Java backend that handles device registration and management
|
||||||
|
- **Main Server** (Port 8000/8003): Python server that handles device communication
|
||||||
|
- **MQTT Gateway** (Port 1883): Optional MQTT broker for device communication
|
||||||
|
- **Database**: MySQL database storing device information and configurations
|
||||||
|
|
||||||
|
### Activation Flow
|
||||||
|
|
||||||
|
```
|
||||||
|
Device → OTA Request → Manager API → Generate Code → User Binds → Device Registered
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
### System Components
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────┐
|
||||||
|
│ ESP32 Device │
|
||||||
|
│ (Client/Device) │
|
||||||
|
└────────┬────────┘
|
||||||
|
│
|
||||||
|
▼ OTA Request (Port 8002)
|
||||||
|
┌─────────────────┐
|
||||||
|
│ Manager API │ ◄──── Generates 6-digit code
|
||||||
|
│ (Java Backend) │ ◄──── Stores in Redis
|
||||||
|
└────────┬────────┘
|
||||||
|
│
|
||||||
|
▼ After Binding
|
||||||
|
┌─────────────────┐
|
||||||
|
│ Main Server │ ◄──── WebSocket Communication
|
||||||
|
│ (Python Server) │ ◄──── Audio/Command Processing
|
||||||
|
└─────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### Data Flow
|
||||||
|
|
||||||
|
1. **Device → Manager API**: Initial OTA configuration request
|
||||||
|
2. **Manager API → Redis**: Store activation code and device info
|
||||||
|
3. **Manager API → Device**: Return activation code
|
||||||
|
4. **User → Admin Panel**: Enter activation code
|
||||||
|
5. **Admin Panel → Database**: Create device record
|
||||||
|
6. **Device → Main Server**: Normal operation begins
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Activation Methods
|
||||||
|
|
||||||
|
### Method 1: Verification Code Binding (Recommended)
|
||||||
|
|
||||||
|
This is the primary method for device activation, suitable for production environments.
|
||||||
|
|
||||||
|
#### How It Works
|
||||||
|
|
||||||
|
1. **Device Request**: Unregistered device sends OTA request with MAC address
|
||||||
|
2. **Code Generation**: Manager API generates a 6-digit activation code
|
||||||
|
3. **Code Storage**: Code stored in Redis with 5-minute expiration
|
||||||
|
4. **User Binding**: User enters code in admin panel
|
||||||
|
5. **Device Registration**: Device record created in database
|
||||||
|
|
||||||
|
#### Advantages
|
||||||
|
- Secure and user-friendly
|
||||||
|
- No manual database access required
|
||||||
|
- Automatic expiration of unused codes
|
||||||
|
- Supports multiple users and roles
|
||||||
|
|
||||||
|
### Method 2: Direct Database Registration (Development Only)
|
||||||
|
|
||||||
|
For development and testing, devices can be added directly to the database.
|
||||||
|
|
||||||
|
#### SQL Command
|
||||||
|
|
||||||
|
```sql
|
||||||
|
INSERT INTO device (
|
||||||
|
id,
|
||||||
|
device_id,
|
||||||
|
device_name,
|
||||||
|
board,
|
||||||
|
app_version,
|
||||||
|
mac_address,
|
||||||
|
agent_id,
|
||||||
|
user_id,
|
||||||
|
creator,
|
||||||
|
auto_update,
|
||||||
|
created_at,
|
||||||
|
updated_at
|
||||||
|
) VALUES (
|
||||||
|
'68:25:dd:ba:39:78', -- Device MAC (use as ID)
|
||||||
|
'68:25:dd:ba:39:78', -- Device MAC
|
||||||
|
'Test ESP32 Device', -- Device name
|
||||||
|
'esp32', -- Board type
|
||||||
|
'1.7.6', -- Firmware version
|
||||||
|
'68:25:dd:ba:39:78', -- MAC address
|
||||||
|
(SELECT id FROM agent_template WHERE is_default = 1 LIMIT 1),
|
||||||
|
1, -- Admin user ID
|
||||||
|
1, -- Creator ID
|
||||||
|
1, -- Auto-update enabled
|
||||||
|
NOW(), -- Created timestamp
|
||||||
|
NOW() -- Updated timestamp
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Advantages
|
||||||
|
- Quick setup for testing
|
||||||
|
- No UI interaction required
|
||||||
|
- Batch device registration possible
|
||||||
|
|
||||||
|
#### Disadvantages
|
||||||
|
- Requires database access
|
||||||
|
- No automatic validation
|
||||||
|
- Not suitable for production
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step-by-Step Process
|
||||||
|
|
||||||
|
### For Device Manufacturers/Developers
|
||||||
|
|
||||||
|
#### 1. Configure Device Client
|
||||||
|
|
||||||
|
```python
|
||||||
|
# client.py configuration
|
||||||
|
SERVER_IP = "192.168.1.105" # Your server IP
|
||||||
|
OTA_PORT = 8002 # Manager API port
|
||||||
|
MQTT_BROKER_HOST = "192.168.1.105"
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. Device Sends OTA Request
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Request format
|
||||||
|
headers = {"device-id": "68:25:dd:ba:39:78"}
|
||||||
|
data = {
|
||||||
|
"application": {
|
||||||
|
"version": "1.7.6"
|
||||||
|
},
|
||||||
|
"client_id": "unique-session-id"
|
||||||
|
}
|
||||||
|
response = requests.post(
|
||||||
|
f"http://{SERVER_IP}:{OTA_PORT}/xiaozhi/ota/",
|
||||||
|
headers=headers,
|
||||||
|
json=data
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3. Handle Activation Response
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Response when device not registered
|
||||||
|
{
|
||||||
|
"activation": {
|
||||||
|
"code": "123456",
|
||||||
|
"message": "http://xiaozhi.server.com\n123456",
|
||||||
|
"challenge": "68:25:dd:ba:39:78"
|
||||||
|
},
|
||||||
|
"server_time": {...},
|
||||||
|
"firmware": {...}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### For End Users
|
||||||
|
|
||||||
|
#### 1. Get Activation Code
|
||||||
|
|
||||||
|
- Device will display or log the 6-digit code
|
||||||
|
- Code is valid for 5 minutes
|
||||||
|
- Code format: 6 random digits (e.g., "123456")
|
||||||
|
|
||||||
|
#### 2. Access Admin Panel
|
||||||
|
|
||||||
|
1. Open browser: `http://your-server-ip:8002`
|
||||||
|
2. Login with admin credentials
|
||||||
|
3. Navigate to "Device Management" (设备管理)
|
||||||
|
|
||||||
|
#### 3. Bind Device
|
||||||
|
|
||||||
|
1. Click "Bind Device" (绑定设备)
|
||||||
|
2. Enter the 6-digit activation code
|
||||||
|
3. Select Agent/Profile for the device
|
||||||
|
4. Click "Confirm" to complete binding
|
||||||
|
|
||||||
|
#### 4. Verify Activation
|
||||||
|
|
||||||
|
- Device status changes to "Online"
|
||||||
|
- Device can now communicate with server
|
||||||
|
- Full features are enabled
|
||||||
|
|
||||||
|
### For System Administrators
|
||||||
|
|
||||||
|
#### 1. Server Configuration
|
||||||
|
|
||||||
|
**Manager API Configuration** (`application.yml`):
|
||||||
|
```yaml
|
||||||
|
server:
|
||||||
|
port: 8002
|
||||||
|
servlet:
|
||||||
|
context-path: /xiaozhi
|
||||||
|
|
||||||
|
spring:
|
||||||
|
redis:
|
||||||
|
host: localhost
|
||||||
|
port: 6379
|
||||||
|
```
|
||||||
|
|
||||||
|
**Main Server Configuration** (`.config.yaml`):
|
||||||
|
```yaml
|
||||||
|
read_config_from_api: true
|
||||||
|
manager-api:
|
||||||
|
url: http://192.168.1.105:8002/xiaozhi
|
||||||
|
secret: your-secret-key
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. Database Setup
|
||||||
|
|
||||||
|
Required tables:
|
||||||
|
- `device`: Stores device information
|
||||||
|
- `agent_template`: Stores agent configurations
|
||||||
|
- `sys_params`: System parameters
|
||||||
|
|
||||||
|
#### 3. Monitor Activation Logs
|
||||||
|
|
||||||
|
**Manager API Logs**:
|
||||||
|
```
|
||||||
|
🔐 Generated NEW activation code for device 68:25:dd:ba:39:78: 123456
|
||||||
|
📱 Please bind device using code: 123456 at http://xiaozhi.server.com
|
||||||
|
```
|
||||||
|
|
||||||
|
**Main Server Logs**:
|
||||||
|
```
|
||||||
|
OTA request device ID: 68:25:dd:ba:39:78
|
||||||
|
Device activated successfully
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
### Manager API Settings
|
||||||
|
|
||||||
|
#### System Parameters (sys_params table)
|
||||||
|
|
||||||
|
| Parameter | Description | Example |
|
||||||
|
|-----------|-------------|---------|
|
||||||
|
| `server.websocket` | WebSocket URL for devices | `ws://192.168.1.105:8000/xiaozhi/v1/` |
|
||||||
|
| `server.ota` | OTA endpoint URL | `http://192.168.1.105:8002/xiaozhi/ota/` |
|
||||||
|
| `server.fronted_url` | Admin panel URL | `http://xiaozhi.server.com` |
|
||||||
|
|
||||||
|
### Redis Configuration
|
||||||
|
|
||||||
|
#### Activation Code Storage
|
||||||
|
|
||||||
|
```
|
||||||
|
Key Format: ota:activation:code:{6-digit-code}
|
||||||
|
Value: Device MAC address
|
||||||
|
TTL: 300 seconds (5 minutes)
|
||||||
|
|
||||||
|
Key Format: ota:activation:data:{safe_device_id}
|
||||||
|
Value: JSON with device details
|
||||||
|
TTL: 300 seconds (5 minutes)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Security Considerations
|
||||||
|
|
||||||
|
1. **Code Expiration**: Activation codes expire after 5 minutes
|
||||||
|
2. **Code Uniqueness**: 6-digit random codes (1 million combinations)
|
||||||
|
3. **Rate Limiting**: Implement rate limiting on OTA endpoint
|
||||||
|
4. **HTTPS**: Use HTTPS in production environments
|
||||||
|
5. **Authentication**: Manager API requires authentication for binding
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Common Issues and Solutions
|
||||||
|
|
||||||
|
#### Issue 1: Device Not Getting Activation Code
|
||||||
|
|
||||||
|
**Symptoms**:
|
||||||
|
- Device connects but no activation code generated
|
||||||
|
- Manager API shows no device query
|
||||||
|
|
||||||
|
**Solutions**:
|
||||||
|
1. Verify device is connecting to Manager API port (8002), not Main Server (8003)
|
||||||
|
2. Check Manager API is running and accessible
|
||||||
|
3. Verify Redis is running and accessible
|
||||||
|
4. Check network connectivity
|
||||||
|
|
||||||
|
**Debug Commands**:
|
||||||
|
```bash
|
||||||
|
# Test Manager API endpoint
|
||||||
|
curl -X POST http://192.168.1.105:8002/xiaozhi/ota/ \
|
||||||
|
-H "device-id: 68:25:dd:ba:39:78" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"application":{"version":"1.7.6"}}'
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Issue 2: Activation Code Not Working
|
||||||
|
|
||||||
|
**Symptoms**:
|
||||||
|
- Code entered but binding fails
|
||||||
|
- "Invalid activation code" error
|
||||||
|
|
||||||
|
**Solutions**:
|
||||||
|
1. Ensure code is entered within 5 minutes
|
||||||
|
2. Verify code is typed correctly (6 digits)
|
||||||
|
3. Check Redis for stored activation data
|
||||||
|
4. Ensure device MAC matches stored data
|
||||||
|
|
||||||
|
**Debug Commands**:
|
||||||
|
```bash
|
||||||
|
# Check Redis for activation code
|
||||||
|
redis-cli GET "ota:activation:code:123456"
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Issue 3: Device Already Registered
|
||||||
|
|
||||||
|
**Symptoms**:
|
||||||
|
- Device exists in database
|
||||||
|
- No activation code generated
|
||||||
|
- "Version information not found" error
|
||||||
|
|
||||||
|
**Solutions**:
|
||||||
|
1. Remove device from database if re-registration needed
|
||||||
|
2. Or update device record directly
|
||||||
|
3. Check device binding status
|
||||||
|
|
||||||
|
**SQL Commands**:
|
||||||
|
```sql
|
||||||
|
-- Check if device exists
|
||||||
|
SELECT * FROM device WHERE device_id = '68:25:dd:ba:39:78';
|
||||||
|
|
||||||
|
-- Remove device for re-registration
|
||||||
|
DELETE FROM device WHERE device_id = '68:25:dd:ba:39:78';
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Issue 4: Configuration Mismatch
|
||||||
|
|
||||||
|
**Symptoms**:
|
||||||
|
- Device connects to wrong server
|
||||||
|
- WebSocket URL incorrect
|
||||||
|
- MQTT credentials missing
|
||||||
|
|
||||||
|
**Solutions**:
|
||||||
|
1. Verify all configuration files are synchronized
|
||||||
|
2. Check `read_config_from_api` setting
|
||||||
|
3. Ensure Manager API has correct parameters
|
||||||
|
4. Restart all services after configuration changes
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API Reference
|
||||||
|
|
||||||
|
### OTA Endpoint
|
||||||
|
|
||||||
|
**Endpoint**: `POST /xiaozhi/ota/`
|
||||||
|
|
||||||
|
**Request Headers**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"device-id": "68:25:dd:ba:39:78",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Request Body**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"application": {
|
||||||
|
"version": "1.7.6"
|
||||||
|
},
|
||||||
|
"client_id": "unique-session-id",
|
||||||
|
"board": {
|
||||||
|
"type": "esp32"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response (Unregistered Device)**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"activation": {
|
||||||
|
"code": "123456",
|
||||||
|
"message": "http://xiaozhi.server.com\n123456",
|
||||||
|
"challenge": "68:25:dd:ba:39:78"
|
||||||
|
},
|
||||||
|
"server_time": {
|
||||||
|
"timestamp": 1755844295654,
|
||||||
|
"timezone_offset": 480
|
||||||
|
},
|
||||||
|
"firmware": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"url": ""
|
||||||
|
},
|
||||||
|
"websocket": {
|
||||||
|
"url": "ws://192.168.1.105:8000/xiaozhi/v1/"
|
||||||
|
},
|
||||||
|
"mqtt_gateway": {
|
||||||
|
"enabled": true,
|
||||||
|
"broker": "192.168.1.105",
|
||||||
|
"port": 1883,
|
||||||
|
"udp_port": 8884
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response (Registered Device)**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"server_time": {...},
|
||||||
|
"firmware": {...},
|
||||||
|
"websocket": {...},
|
||||||
|
"mqtt": {
|
||||||
|
"client_id": "GID_test@@@68_25_dd_ba_39_78@@@uuid",
|
||||||
|
"username": "base64-encoded-data",
|
||||||
|
"password": "base64-encoded-signature"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Device Binding Endpoint
|
||||||
|
|
||||||
|
**Endpoint**: `POST /device/bind/{agentId}/{deviceCode}`
|
||||||
|
|
||||||
|
**Parameters**:
|
||||||
|
- `agentId`: Agent template ID
|
||||||
|
- `deviceCode`: 6-digit activation code
|
||||||
|
|
||||||
|
**Response**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 0,
|
||||||
|
"msg": "success"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Database Schema
|
||||||
|
|
||||||
|
### Device Table
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE `device` (
|
||||||
|
`id` varchar(50) PRIMARY KEY,
|
||||||
|
`device_id` varchar(50) NOT NULL,
|
||||||
|
`device_name` varchar(100),
|
||||||
|
`board` varchar(50),
|
||||||
|
`app_version` varchar(20),
|
||||||
|
`mac_address` varchar(50),
|
||||||
|
`agent_id` varchar(50),
|
||||||
|
`user_id` bigint,
|
||||||
|
`bind_status` tinyint DEFAULT 0,
|
||||||
|
`online_status` tinyint DEFAULT 0,
|
||||||
|
`last_online` datetime,
|
||||||
|
`ip_address` varchar(50),
|
||||||
|
`created_at` datetime,
|
||||||
|
`updated_at` datetime,
|
||||||
|
`bind_code` varchar(10),
|
||||||
|
`bind_time` datetime,
|
||||||
|
KEY `idx_device_id` (`device_id`),
|
||||||
|
KEY `idx_mac_address` (`mac_address`),
|
||||||
|
KEY `idx_user_id` (`user_id`)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Agent Template Table
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE `agent_template` (
|
||||||
|
`id` varchar(50) PRIMARY KEY,
|
||||||
|
`agent_name` varchar(100),
|
||||||
|
`is_default` tinyint DEFAULT 0,
|
||||||
|
`asr_model_id` varchar(50),
|
||||||
|
`tts_model_id` varchar(50),
|
||||||
|
`llm_model_id` varchar(50),
|
||||||
|
`vad_model_id` varchar(50),
|
||||||
|
-- other configuration fields
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
### For Production Deployment
|
||||||
|
|
||||||
|
1. **Use HTTPS**: Always use HTTPS for OTA endpoints
|
||||||
|
2. **Implement Rate Limiting**: Prevent activation code brute force
|
||||||
|
3. **Log All Activations**: Maintain audit trail
|
||||||
|
4. **Monitor Failed Attempts**: Detect potential security issues
|
||||||
|
5. **Regular Cleanup**: Remove expired activation data from Redis
|
||||||
|
6. **Backup Device Data**: Regular database backups
|
||||||
|
7. **Use Strong Secrets**: Generate strong secrets for API authentication
|
||||||
|
|
||||||
|
### For Development
|
||||||
|
|
||||||
|
1. **Use Test Devices**: Maintain separate test device pool
|
||||||
|
2. **Mock Activation**: Create mock activation endpoints for testing
|
||||||
|
3. **Automate Testing**: Create automated tests for activation flow
|
||||||
|
4. **Document MAC Addresses**: Keep track of test device MACs
|
||||||
|
5. **Use Docker**: Containerize services for consistent environment
|
||||||
|
|
||||||
|
### Security Recommendations
|
||||||
|
|
||||||
|
1. **Network Isolation**: Isolate device network from main network
|
||||||
|
2. **API Authentication**: Implement JWT or OAuth for API access
|
||||||
|
3. **Device Certificates**: Consider using device certificates for production
|
||||||
|
4. **Encrypted Communication**: Use TLS for all communications
|
||||||
|
5. **Regular Updates**: Keep all components updated
|
||||||
|
6. **Access Control**: Implement role-based access control
|
||||||
|
7. **Audit Logging**: Log all device registration activities
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Appendix
|
||||||
|
|
||||||
|
### Testing Tools
|
||||||
|
|
||||||
|
#### Test OTA Connection Script
|
||||||
|
|
||||||
|
```python
|
||||||
|
# test_ota.py
|
||||||
|
import requests
|
||||||
|
import json
|
||||||
|
|
||||||
|
device_mac = "68:25:dd:ba:39:78"
|
||||||
|
manager_api_url = "http://192.168.1.105:8002/xiaozhi/ota/"
|
||||||
|
|
||||||
|
headers = {"device-id": device_mac}
|
||||||
|
data = {
|
||||||
|
"application": {"version": "1.7.6"},
|
||||||
|
"client_id": "test-client"
|
||||||
|
}
|
||||||
|
|
||||||
|
response = requests.post(manager_api_url, headers=headers, json=data)
|
||||||
|
print(json.dumps(response.json(), indent=2))
|
||||||
|
|
||||||
|
activation = response.json().get("activation")
|
||||||
|
if activation:
|
||||||
|
print(f"\n🔐 ACTIVATION CODE: {activation.get('code')}")
|
||||||
|
```
|
||||||
|
|
||||||
|
### Monitoring Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Monitor Manager API logs
|
||||||
|
tail -f manager-api.log | grep -E "activation|device"
|
||||||
|
|
||||||
|
# Monitor Redis
|
||||||
|
redis-cli MONITOR | grep "ota:activation"
|
||||||
|
|
||||||
|
# Check device status in database
|
||||||
|
mysql -u root -p xiaozhi_db -e "SELECT * FROM device WHERE online_status = 1;"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Environment Variables
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# .env file for Manager API
|
||||||
|
SPRING_PROFILES_ACTIVE=prod
|
||||||
|
REDIS_HOST=localhost
|
||||||
|
REDIS_PORT=6379
|
||||||
|
DB_HOST=localhost
|
||||||
|
DB_PORT=3306
|
||||||
|
DB_NAME=xiaozhi_db
|
||||||
|
|
||||||
|
# .env file for Main Server
|
||||||
|
MANAGER_API_URL=http://192.168.1.105:8002/xiaozhi
|
||||||
|
MANAGER_API_SECRET=your-secret-key
|
||||||
|
MQTT_BROKER_HOST=192.168.1.105
|
||||||
|
MQTT_BROKER_PORT=1883
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Support and Resources
|
||||||
|
|
||||||
|
- **GitHub Repository**: [xiaozhi-esp32-server](https://github.com/your-repo)
|
||||||
|
- **Documentation**: [Official Docs](https://docs.your-domain.com)
|
||||||
|
- **Community Forum**: [Discussion Board](https://forum.your-domain.com)
|
||||||
|
- **Issue Tracker**: [GitHub Issues](https://github.com/your-repo/issues)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Last Updated: August 2024*
|
||||||
|
*Version: 1.0.0*
|
||||||
632
main/xiaozhi-server/LLM_CONFIGURATION_GUIDE.md
Normal file
632
main/xiaozhi-server/LLM_CONFIGURATION_GUIDE.md
Normal file
|
|
@ -0,0 +1,632 @@
|
||||||
|
# LLM Configuration Guide for Xiaozhi ESP32 Server
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
1. [Overview](#overview)
|
||||||
|
2. [Supported LLM Providers](#supported-llm-providers)
|
||||||
|
3. [Adding LLM via Dashboard](#adding-llm-via-dashboard)
|
||||||
|
4. [Configuration Examples](#configuration-examples)
|
||||||
|
5. [Testing and Validation](#testing-and-validation)
|
||||||
|
6. [Troubleshooting](#troubleshooting)
|
||||||
|
7. [Performance Optimization](#performance-optimization)
|
||||||
|
8. [API Reference](#api-reference)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
The Xiaozhi ESP32 Server supports multiple Large Language Model (LLM) providers through a unified OpenAI-compatible interface. This guide explains how to add, configure, and manage different LLM providers through the Manager API dashboard.
|
||||||
|
|
||||||
|
### Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────┐
|
||||||
|
│ ESP32 Device │
|
||||||
|
│ (Audio Input) │
|
||||||
|
└────────┬────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────┐
|
||||||
|
│ Main Server │
|
||||||
|
│ (Python/ASR) │
|
||||||
|
└────────┬────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────┐
|
||||||
|
│ LLM Provider │ ◄── Groq, OpenAI, Anthropic, etc.
|
||||||
|
│ (API Service) │
|
||||||
|
└────────┬────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────┐
|
||||||
|
│ TTS Engine │
|
||||||
|
│ (Audio Output) │
|
||||||
|
└─────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Supported LLM Providers
|
||||||
|
|
||||||
|
### OpenAI-Compatible Providers
|
||||||
|
|
||||||
|
Any provider that implements the OpenAI API standard can be integrated:
|
||||||
|
|
||||||
|
| Provider | Base URL | Models | Notes |
|
||||||
|
|----------|----------|--------|-------|
|
||||||
|
| **Groq** | `https://api.groq.com/openai/v1` | llama-3.3-70b, mixtral-8x7b | Ultra-fast inference |
|
||||||
|
| **OpenAI** | `https://api.openai.com/v1` | gpt-4, gpt-3.5-turbo | Industry standard |
|
||||||
|
| **Anthropic** | `https://api.anthropic.com/v1` | claude-3-opus, claude-3-sonnet | Via adapter |
|
||||||
|
| **DeepSeek** | `https://api.deepseek.com/v1` | deepseek-coder, deepseek-chat | Code-focused |
|
||||||
|
| **Together AI** | `https://api.together.xyz/v1` | Various open models | Multiple models |
|
||||||
|
| **Perplexity** | `https://api.perplexity.ai` | pplx-70b, pplx-7b | Search-enhanced |
|
||||||
|
| **Local (Ollama)** | `http://localhost:11434/v1` | llama2, mistral, etc. | Self-hosted |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Adding LLM via Dashboard
|
||||||
|
|
||||||
|
### Step 1: Access the Dashboard
|
||||||
|
|
||||||
|
1. Navigate to: `http://192.168.1.105:8002`
|
||||||
|
2. Login with admin credentials
|
||||||
|
3. Go to **"模型配置"** (Model Configuration)
|
||||||
|
|
||||||
|
### Step 2: Fill in the Add Model Form
|
||||||
|
|
||||||
|
#### Model Information Fields
|
||||||
|
|
||||||
|
| Field | Chinese | Description | Example |
|
||||||
|
|-------|---------|-------------|---------|
|
||||||
|
| **Enable** | 启用 | Enable the model | ✅ Checked |
|
||||||
|
| **Model Name** | 模型名称 | Display name | `Groq LLM` |
|
||||||
|
| **Model Code** | 模型代码 | Unique identifier | `LLM_GroqLLM` |
|
||||||
|
| **Provider** | 提供商 | Provider type | `OpenAI接口` |
|
||||||
|
| **Sort Order** | 排序 | Display order | `1` |
|
||||||
|
| **Documentation URL** | 文档URL | API documentation | `https://console.groq.com/docs` |
|
||||||
|
| **Remarks** | 备注 | Description | `Fast inference with Llama models` |
|
||||||
|
|
||||||
|
#### Configuration Fields
|
||||||
|
|
||||||
|
| Field | Chinese | Description | Example |
|
||||||
|
|-------|---------|-------------|---------|
|
||||||
|
| **Base URL** | 基础URL | API endpoint | `https://api.groq.com/openai/v1` |
|
||||||
|
| **Model Name** | 模型名称 | Specific model | `llama-3.3-70b-versatile` |
|
||||||
|
| **API Key** | API密钥 | Authentication | `gsk_ReBJtpG...` |
|
||||||
|
| **Temperature** | 温度 | Randomness (0-1) | `0.7` |
|
||||||
|
| **Max Tokens** | 最大令牌数 | Response length | `2048` |
|
||||||
|
| **Top P** | top_p值 | Nucleus sampling | `1.0` |
|
||||||
|
| **Top K** | top_k值 | Top-k sampling | `0` |
|
||||||
|
| **Frequency Penalty** | 频率惩罚 | Repetition control | `0` |
|
||||||
|
|
||||||
|
### Step 3: Save and Apply
|
||||||
|
|
||||||
|
1. Click **保存** (Save)
|
||||||
|
2. Go to **智能体模板** (Agent Templates)
|
||||||
|
3. Select the new LLM model
|
||||||
|
4. Save the agent configuration
|
||||||
|
5. Restart the main server
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Configuration Examples
|
||||||
|
|
||||||
|
### Example 1: Groq (Recommended for Speed)
|
||||||
|
|
||||||
|
**Use Case**: Fast responses for real-time conversation with children
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"model_name": "Groq LLM",
|
||||||
|
"model_code": "LLM_GroqLLM",
|
||||||
|
"provider": "OpenAI接口",
|
||||||
|
"config": {
|
||||||
|
"base_url": "https://api.groq.com/openai/v1",
|
||||||
|
"model_name": "llama-3.3-70b-versatile",
|
||||||
|
"api_key": "gsk_YOUR_API_KEY",
|
||||||
|
"temperature": 0.7,
|
||||||
|
"max_tokens": 150,
|
||||||
|
"top_p": 0.9,
|
||||||
|
"frequency_penalty": 0.3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Form Fields**:
|
||||||
|
- 基础URL: `https://api.groq.com/openai/v1`
|
||||||
|
- 模型名称: `llama-3.3-70b-versatile`
|
||||||
|
- API密钥: `gsk_YOUR_API_KEY`
|
||||||
|
- 温度: `0.7`
|
||||||
|
- 最大令牌数: `150` (shorter for child-friendly responses)
|
||||||
|
- top_p值: `0.9`
|
||||||
|
- 频率惩罚: `0.3` (reduce repetition)
|
||||||
|
|
||||||
|
### Example 2: OpenAI GPT-4
|
||||||
|
|
||||||
|
**Use Case**: Most advanced reasoning and creativity
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"model_name": "OpenAI GPT-4",
|
||||||
|
"model_code": "LLM_GPT4",
|
||||||
|
"provider": "OpenAI接口",
|
||||||
|
"config": {
|
||||||
|
"base_url": "https://api.openai.com/v1",
|
||||||
|
"model_name": "gpt-4-turbo-preview",
|
||||||
|
"api_key": "sk-YOUR_API_KEY",
|
||||||
|
"temperature": 0.8,
|
||||||
|
"max_tokens": 200,
|
||||||
|
"top_p": 1.0,
|
||||||
|
"frequency_penalty": 0.2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Example 3: Local Ollama
|
||||||
|
|
||||||
|
**Use Case**: Privacy-focused, no internet required
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"model_name": "Local Llama",
|
||||||
|
"model_code": "LLM_Ollama",
|
||||||
|
"provider": "OpenAI接口",
|
||||||
|
"config": {
|
||||||
|
"base_url": "http://localhost:11434/v1",
|
||||||
|
"model_name": "llama2:13b",
|
||||||
|
"api_key": "not-needed",
|
||||||
|
"temperature": 0.7,
|
||||||
|
"max_tokens": 200,
|
||||||
|
"top_p": 0.95
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Example 4: DeepSeek (Chinese + English)
|
||||||
|
|
||||||
|
**Use Case**: Bilingual support
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"model_name": "DeepSeek Chat",
|
||||||
|
"model_code": "LLM_DeepSeek",
|
||||||
|
"provider": "OpenAI接口",
|
||||||
|
"config": {
|
||||||
|
"base_url": "https://api.deepseek.com/v1",
|
||||||
|
"model_name": "deepseek-chat",
|
||||||
|
"api_key": "YOUR_DEEPSEEK_KEY",
|
||||||
|
"temperature": 0.7,
|
||||||
|
"max_tokens": 200
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## System Prompt Configuration
|
||||||
|
|
||||||
|
For child-friendly AI interactions, configure the system prompt appropriately:
|
||||||
|
|
||||||
|
### Example: Cheeko - Child-Friendly Assistant
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
prompt: |
|
||||||
|
You are Cheeko, a friendly, curious, and playful AI friend for children aged 4+.
|
||||||
|
You talk in short, clear, and fun sentences.
|
||||||
|
You always:
|
||||||
|
1. Start with a cheerful greeting if it's the first message
|
||||||
|
2. Answer in simple and imaginative ways using age-appropriate words
|
||||||
|
3. Praise or encourage the child after they respond
|
||||||
|
4. End every message with a fun follow-up question
|
||||||
|
5. Use a warm and positive tone at all times
|
||||||
|
6. Avoid scary, negative, or boring content
|
||||||
|
7. Keep responses under 50 words
|
||||||
|
8. Never say "I don't know" - make playful guesses instead
|
||||||
|
9. Remember you're a voice agent - responses will be spoken aloud
|
||||||
|
|
||||||
|
response_constraints:
|
||||||
|
max_words: 50
|
||||||
|
enforce_limit: true
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Testing and Validation
|
||||||
|
|
||||||
|
### Step 1: Test API Connection
|
||||||
|
|
||||||
|
```python
|
||||||
|
# test_llm.py
|
||||||
|
import requests
|
||||||
|
import json
|
||||||
|
|
||||||
|
def test_llm_connection(base_url, api_key, model_name):
|
||||||
|
headers = {
|
||||||
|
"Authorization": f"Bearer {api_key}",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
|
||||||
|
data = {
|
||||||
|
"model": model_name,
|
||||||
|
"messages": [
|
||||||
|
{"role": "system", "content": "You are a helpful assistant."},
|
||||||
|
{"role": "user", "content": "Say 'Hello, I'm working!' in a fun way."}
|
||||||
|
],
|
||||||
|
"temperature": 0.7,
|
||||||
|
"max_tokens": 50
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = requests.post(
|
||||||
|
f"{base_url}/chat/completions",
|
||||||
|
headers=headers,
|
||||||
|
json=data,
|
||||||
|
timeout=10
|
||||||
|
)
|
||||||
|
|
||||||
|
if response.status_code == 200:
|
||||||
|
result = response.json()
|
||||||
|
print(f"✅ Success! Response: {result['choices'][0]['message']['content']}")
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
print(f"❌ Error {response.status_code}: {response.text}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Connection failed: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Test Groq
|
||||||
|
test_llm_connection(
|
||||||
|
base_url="https://api.groq.com/openai/v1",
|
||||||
|
api_key="gsk_YOUR_API_KEY",
|
||||||
|
model_name="llama-3.3-70b-versatile"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 2: Validate in System
|
||||||
|
|
||||||
|
1. Check Manager API logs:
|
||||||
|
```bash
|
||||||
|
tail -f manager-api.log | grep -i "llm"
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Check Main Server logs:
|
||||||
|
```bash
|
||||||
|
# Should see:
|
||||||
|
# Loading LLM configuration: LLM_GroqLLM
|
||||||
|
# LLM initialized successfully
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Test with device:
|
||||||
|
- Connect device
|
||||||
|
- Speak a test phrase
|
||||||
|
- Verify LLM response
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Common Issues and Solutions
|
||||||
|
|
||||||
|
#### Issue 1: "API Key Invalid"
|
||||||
|
|
||||||
|
**Symptoms**:
|
||||||
|
- 401 Unauthorized error
|
||||||
|
- "Invalid API key" in logs
|
||||||
|
|
||||||
|
**Solutions**:
|
||||||
|
1. Verify API key is correct and active
|
||||||
|
2. Check API key has proper permissions
|
||||||
|
3. Ensure no extra spaces in API key field
|
||||||
|
4. For Groq, verify at: https://console.groq.com/keys
|
||||||
|
|
||||||
|
#### Issue 2: "Model Not Found"
|
||||||
|
|
||||||
|
**Symptoms**:
|
||||||
|
- 404 error
|
||||||
|
- "Model does not exist" error
|
||||||
|
|
||||||
|
**Solutions**:
|
||||||
|
1. Verify model name is exact (case-sensitive)
|
||||||
|
2. Check provider's model list
|
||||||
|
3. For Groq models:
|
||||||
|
- `llama-3.3-70b-versatile`
|
||||||
|
- `llama-3.1-8b-instant`
|
||||||
|
- `mixtral-8x7b-32768`
|
||||||
|
- `gemma2-9b-it`
|
||||||
|
|
||||||
|
#### Issue 3: "Rate Limit Exceeded"
|
||||||
|
|
||||||
|
**Symptoms**:
|
||||||
|
- 429 Too Many Requests
|
||||||
|
- Intermittent failures
|
||||||
|
|
||||||
|
**Solutions**:
|
||||||
|
1. Check API rate limits
|
||||||
|
2. Implement retry logic
|
||||||
|
3. Consider upgrading API plan
|
||||||
|
4. Add multiple API keys for load balancing
|
||||||
|
|
||||||
|
#### Issue 4: "Timeout Errors"
|
||||||
|
|
||||||
|
**Symptoms**:
|
||||||
|
- Request timeout
|
||||||
|
- Slow responses
|
||||||
|
|
||||||
|
**Solutions**:
|
||||||
|
1. Increase timeout settings
|
||||||
|
2. Use faster models (e.g., llama-3.1-8b-instant)
|
||||||
|
3. Reduce max_tokens
|
||||||
|
4. Check network connectivity
|
||||||
|
|
||||||
|
#### Issue 5: "Response Too Long"
|
||||||
|
|
||||||
|
**Symptoms**:
|
||||||
|
- Responses cut off
|
||||||
|
- TTS fails with long text
|
||||||
|
|
||||||
|
**Solutions**:
|
||||||
|
1. Reduce max_tokens (recommended: 50-150 for children)
|
||||||
|
2. Add response constraints in prompt
|
||||||
|
3. Implement response splitting
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Performance Optimization
|
||||||
|
|
||||||
|
### Model Selection Guidelines
|
||||||
|
|
||||||
|
| Use Case | Recommended Model | Settings |
|
||||||
|
|----------|------------------|----------|
|
||||||
|
| **Real-time chat** | Groq llama-3.1-8b-instant | temp=0.7, max_tokens=100 |
|
||||||
|
| **Creative stories** | GPT-4 or Claude-3 | temp=0.9, max_tokens=200 |
|
||||||
|
| **Educational** | llama-3.3-70b-versatile | temp=0.5, max_tokens=150 |
|
||||||
|
| **Local/Offline** | Ollama llama2:7b | temp=0.7, max_tokens=100 |
|
||||||
|
| **Bilingual** | DeepSeek-chat | temp=0.7, max_tokens=150 |
|
||||||
|
|
||||||
|
### Optimization Tips
|
||||||
|
|
||||||
|
1. **Response Time**:
|
||||||
|
- Use smaller models for faster responses
|
||||||
|
- Set appropriate max_tokens (50-150 for children)
|
||||||
|
- Enable streaming if supported
|
||||||
|
|
||||||
|
2. **Quality vs Speed**:
|
||||||
|
```
|
||||||
|
Fast: llama-3.1-8b-instant (50-100ms)
|
||||||
|
Balanced: llama-3.3-70b-versatile (200-500ms)
|
||||||
|
Best: GPT-4 (1-3s)
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Cost Optimization**:
|
||||||
|
- Monitor token usage
|
||||||
|
- Use smaller models for simple queries
|
||||||
|
- Implement caching for common responses
|
||||||
|
- Set daily limits
|
||||||
|
|
||||||
|
4. **Child-Friendly Settings**:
|
||||||
|
- Temperature: 0.6-0.8 (balanced creativity)
|
||||||
|
- Max tokens: 50-150 (short attention spans)
|
||||||
|
- Frequency penalty: 0.2-0.4 (reduce repetition)
|
||||||
|
- Presence penalty: 0.1-0.3 (topic variety)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API Reference
|
||||||
|
|
||||||
|
### Model Configuration Schema
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
interface LLMConfig {
|
||||||
|
// Basic Information
|
||||||
|
id: string; // Unique identifier (e.g., "LLM_GroqLLM")
|
||||||
|
model_type: "LLM"; // Always "LLM" for language models
|
||||||
|
model_code: string; // Code identifier
|
||||||
|
model_name: string; // Display name
|
||||||
|
is_default: boolean; // Set as default model
|
||||||
|
is_enabled: boolean; // Enable/disable model
|
||||||
|
|
||||||
|
// Configuration
|
||||||
|
config_json: {
|
||||||
|
type: "openai"; // Provider type
|
||||||
|
base_url: string; // API endpoint
|
||||||
|
api_key: string; // Authentication key
|
||||||
|
model_name: string; // Specific model to use
|
||||||
|
temperature?: number; // 0.0 - 1.0
|
||||||
|
max_tokens?: number; // Maximum response length
|
||||||
|
top_p?: number; // Nucleus sampling
|
||||||
|
top_k?: number; // Top-k sampling
|
||||||
|
frequency_penalty?: number; // Repetition penalty
|
||||||
|
presence_penalty?: number; // Topic penalty
|
||||||
|
stop?: string[]; // Stop sequences
|
||||||
|
stream?: boolean; // Enable streaming
|
||||||
|
};
|
||||||
|
|
||||||
|
// Metadata
|
||||||
|
doc_link?: string; // Documentation URL
|
||||||
|
remark?: string; // Description/notes
|
||||||
|
sort?: number; // Display order
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Database Table Structure
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE `ai_model_config` (
|
||||||
|
`id` varchar(50) PRIMARY KEY,
|
||||||
|
`model_type` varchar(20) NOT NULL,
|
||||||
|
`model_code` varchar(50) NOT NULL,
|
||||||
|
`model_name` varchar(100) NOT NULL,
|
||||||
|
`is_default` tinyint DEFAULT 0,
|
||||||
|
`is_enabled` tinyint DEFAULT 1,
|
||||||
|
`config_json` text NOT NULL,
|
||||||
|
`doc_link` varchar(500),
|
||||||
|
`remark` text,
|
||||||
|
`sort` int DEFAULT 0,
|
||||||
|
`creator` bigint,
|
||||||
|
`create_date` datetime,
|
||||||
|
`updater` bigint,
|
||||||
|
`update_date` datetime,
|
||||||
|
UNIQUE KEY `uk_model_code` (`model_code`),
|
||||||
|
KEY `idx_model_type` (`model_type`)
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
### Security
|
||||||
|
|
||||||
|
1. **API Key Management**:
|
||||||
|
- Never commit API keys to version control
|
||||||
|
- Use environment variables in production
|
||||||
|
- Rotate keys regularly
|
||||||
|
- Monitor usage for anomalies
|
||||||
|
|
||||||
|
2. **Access Control**:
|
||||||
|
- Limit dashboard access
|
||||||
|
- Use role-based permissions
|
||||||
|
- Audit configuration changes
|
||||||
|
- Implement IP whitelisting
|
||||||
|
|
||||||
|
### Reliability
|
||||||
|
|
||||||
|
1. **Fallback Configuration**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"primary": "LLM_GroqLLM",
|
||||||
|
"fallback": "LLM_Ollama",
|
||||||
|
"timeout": 5000
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Health Checks**:
|
||||||
|
- Implement periodic health checks
|
||||||
|
- Monitor response times
|
||||||
|
- Track error rates
|
||||||
|
- Set up alerts
|
||||||
|
|
||||||
|
### Child Safety
|
||||||
|
|
||||||
|
1. **Content Filtering**:
|
||||||
|
- Implement safety filters
|
||||||
|
- Review model outputs
|
||||||
|
- Set appropriate temperature
|
||||||
|
- Use system prompts effectively
|
||||||
|
|
||||||
|
2. **Response Guidelines**:
|
||||||
|
- Keep responses short (< 50 words)
|
||||||
|
- Use simple vocabulary
|
||||||
|
- Maintain positive tone
|
||||||
|
- Avoid complex topics
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Monitoring and Logs
|
||||||
|
|
||||||
|
### Key Metrics to Monitor
|
||||||
|
|
||||||
|
1. **Performance Metrics**:
|
||||||
|
- Response time (p50, p95, p99)
|
||||||
|
- Token usage per request
|
||||||
|
- Error rate
|
||||||
|
- Timeout rate
|
||||||
|
|
||||||
|
2. **Usage Metrics**:
|
||||||
|
- Requests per minute
|
||||||
|
- Active devices
|
||||||
|
- Token consumption
|
||||||
|
- Cost per day
|
||||||
|
|
||||||
|
3. **Quality Metrics**:
|
||||||
|
- User engagement
|
||||||
|
- Conversation length
|
||||||
|
- Completion rate
|
||||||
|
- Feedback scores
|
||||||
|
|
||||||
|
### Log Analysis
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Check LLM initialization
|
||||||
|
grep "LLM.*init" /var/log/xiaozhi/main.log
|
||||||
|
|
||||||
|
# Monitor API calls
|
||||||
|
tail -f /var/log/xiaozhi/api.log | grep -E "groq|openai|llm"
|
||||||
|
|
||||||
|
# Track errors
|
||||||
|
grep -E "ERROR.*LLM|LLM.*failed" /var/log/xiaozhi/error.log
|
||||||
|
|
||||||
|
# Response time analysis
|
||||||
|
awk '/LLM response time/ {sum+=$NF; count++} END {print "Avg:", sum/count}' main.log
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Appendix
|
||||||
|
|
||||||
|
### A. Groq Model Specifications
|
||||||
|
|
||||||
|
| Model | Context | Speed | Best For |
|
||||||
|
|-------|---------|-------|----------|
|
||||||
|
| **llama-3.3-70b-versatile** | 8k | Fast | General purpose |
|
||||||
|
| **llama-3.1-8b-instant** | 8k | Fastest | Real-time chat |
|
||||||
|
| **mixtral-8x7b-32768** | 32k | Medium | Long context |
|
||||||
|
| **gemma2-9b-it** | 8k | Fast | Instruction following |
|
||||||
|
|
||||||
|
### B. Temperature Guidelines
|
||||||
|
|
||||||
|
| Temperature | Character | Use Case |
|
||||||
|
|------------|-----------|----------|
|
||||||
|
| 0.1 - 0.3 | Focused | Facts, education |
|
||||||
|
| 0.4 - 0.6 | Balanced | General conversation |
|
||||||
|
| 0.7 - 0.8 | Creative | Stories, imagination |
|
||||||
|
| 0.9 - 1.0 | Random | Brainstorming |
|
||||||
|
|
||||||
|
### C. Quick Setup Script
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
# quick_setup_groq.sh
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
API_KEY="gsk_YOUR_API_KEY"
|
||||||
|
MODEL="llama-3.3-70b-versatile"
|
||||||
|
DB_NAME="xiaozhi_db"
|
||||||
|
|
||||||
|
# Insert into database
|
||||||
|
mysql -u root -p $DB_NAME << EOF
|
||||||
|
INSERT INTO ai_model_config (
|
||||||
|
id, model_type, model_code, model_name,
|
||||||
|
is_default, is_enabled, config_json,
|
||||||
|
doc_link, remark, sort, create_date
|
||||||
|
) VALUES (
|
||||||
|
'LLM_GroqLLM', 'LLM', 'LLM_GroqLLM', 'Groq LLM',
|
||||||
|
0, 1,
|
||||||
|
'{"type":"openai","base_url":"https://api.groq.com/openai/v1",
|
||||||
|
"api_key":"${API_KEY}","model_name":"${MODEL}",
|
||||||
|
"temperature":0.7,"max_tokens":150}',
|
||||||
|
'https://console.groq.com/docs',
|
||||||
|
'Groq Cloud - Fast inference', 1, NOW()
|
||||||
|
) ON DUPLICATE KEY UPDATE
|
||||||
|
config_json = VALUES(config_json),
|
||||||
|
update_date = NOW();
|
||||||
|
EOF
|
||||||
|
|
||||||
|
echo "✅ Groq LLM added successfully!"
|
||||||
|
echo "🔄 Please restart the main server to apply changes."
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Support Resources
|
||||||
|
|
||||||
|
- **Groq Documentation**: https://console.groq.com/docs
|
||||||
|
- **OpenAI API Reference**: https://platform.openai.com/docs
|
||||||
|
- **Ollama Models**: https://ollama.ai/library
|
||||||
|
- **Community Forum**: https://github.com/xinnan-tech/xiaozhi-esp32-server/discussions
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Last Updated: December 2024*
|
||||||
|
*Version: 1.0.0*
|
||||||
39
main/xiaozhi-server/test_ota.py
Normal file
39
main/xiaozhi-server/test_ota.py
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
import requests
|
||||||
|
import json
|
||||||
|
|
||||||
|
# Test OTA connection to Manager API
|
||||||
|
device_mac = "68:25:dd:ba:39:78"
|
||||||
|
|
||||||
|
manager_api_url = "http://192.168.1.105:8002/xiaozhi/ota/"
|
||||||
|
|
||||||
|
headers = {"device-id": device_mac}
|
||||||
|
data = {
|
||||||
|
"application": {
|
||||||
|
"version": "1.7.6"
|
||||||
|
},
|
||||||
|
"client_id": "test-client-id"
|
||||||
|
}
|
||||||
|
|
||||||
|
print(f"Testing OTA connection to Manager API at {manager_api_url}")
|
||||||
|
print(f"Device MAC: {device_mac}")
|
||||||
|
print("-" * 60)
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = requests.post(manager_api_url, headers=headers, json=data, timeout=5)
|
||||||
|
print(f"Status Code: {response.status_code}")
|
||||||
|
print(f"Response: {json.dumps(response.json(), indent=2)}")
|
||||||
|
|
||||||
|
# Check for activation code
|
||||||
|
activation = response.json().get("activation")
|
||||||
|
if activation:
|
||||||
|
code = activation.get("code")
|
||||||
|
if code:
|
||||||
|
print("\n" + "=" * 60)
|
||||||
|
print(f"🔐 ACTIVATION CODE: {code}")
|
||||||
|
print("=" * 60)
|
||||||
|
print(f"Please bind this device using code: {code}")
|
||||||
|
else:
|
||||||
|
print("\n⚠️ No activation code in response - device may already be registered")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error: {e}")
|
||||||
Loading…
Reference in a new issue