diff --git a/FIRMWARE_UPDATE_SYSTEM_DOCUMENTATION.md b/FIRMWARE_UPDATE_SYSTEM_DOCUMENTATION.md new file mode 100644 index 000000000..8c5305c97 --- /dev/null +++ b/FIRMWARE_UPDATE_SYSTEM_DOCUMENTATION.md @@ -0,0 +1,452 @@ +# Firmware Update System Documentation + +## Table of Contents +1. [Overview](#overview) +2. [Architecture](#architecture) +3. [Components](#components) +4. [Firmware Upload Process](#firmware-upload-process) +5. [OTA Update Flow](#ota-update-flow) +6. [API Endpoints](#api-endpoints) +7. [Database Schema](#database-schema) +8. [Configuration](#configuration) +9. [Security Features](#security-features) +10. [Device-Server Communication](#device-server-communication) + +--- + +## Overview + +The Xiaozhi ESP32 Server implements a comprehensive Over-The-Air (OTA) firmware update system that allows remote firmware updates for ESP32 devices. The system supports automatic version checking, secure firmware distribution, and device-specific update policies. + +### Key Features +- Automatic version comparison and update detection +- Secure firmware storage with MD5 hash verification +- Per-device update control (auto-update enable/disable) +- Download attempt limiting (3 attempts per UUID) +- Support for multiple firmware types (.bin and .apk) +- RESTful API for firmware management + +--- + +## Architecture + +``` +┌─────────────────┐ ┌──────────────────┐ ┌────────────────┐ +│ ESP32 Device │────▶│ Manager API │────▶│ Firmware Store │ +│ │◀────│ (Java Spring) │◀────│ (uploadfile/) │ +└─────────────────┘ └──────────────────┘ └────────────────┘ + │ │ │ + │ ▼ │ + │ ┌──────────────────┐ │ + │ │ Database │ │ + │ │ (ai_ota) │ │ + │ └──────────────────┘ │ + │ │ + ▼ │ +┌─────────────────┐ │ +│ Xiaozhi Server │ │ +│ (Python) │◀──────────────────────────────────────┘ +└─────────────────┘ +``` + +--- + +## Components + +### 1. Manager API (Java Spring Boot) +- **Location**: `main/manager-api/` +- **Main Controllers**: + - `OTAController.java`: Handles device OTA check requests + - `OTAMagController.java`: Manages firmware upload/download +- **Services**: + - `OtaServiceImpl.java`: Business logic for OTA operations + - `DeviceServiceImpl.java`: Device management and update checks + +### 2. Xiaozhi Server (Python) +- **Location**: `main/xiaozhi-server/` +- **OTA Handler**: `core/api/ota_handler.py` +- Provides fallback OTA endpoint for direct device connections + +### 3. Firmware Storage +- **Location**: `main/manager-api/uploadfile/` +- Files stored with MD5 hash as filename +- Supported formats: `.bin`, `.apk` + +--- + +## Firmware Upload Process + +### Step 1: Admin Upload +```http +POST /otaMag/upload +Content-Type: multipart/form-data +``` + +**Process Flow**: +1. Admin uploads firmware file through web interface +2. System validates file extension (.bin or .apk only) +3. MD5 hash calculated for the file +4. File saved as: `uploadfile/{md5_hash}.{extension}` +5. If file already exists (same MD5), returns existing path +6. Path returned to admin for database entry + +**Code Location**: `OTAMagController.java:231-279` + +### Step 2: Database Registration +Admin creates OTA entry with: +- **Firmware Name**: Descriptive name +- **Type**: Device type (e.g., "esp32-generic", "doit-ai-01-kit") +- **Version**: Semantic version (e.g., "1.7.6") +- **File Path**: Path from upload step +- **Size**: File size in bytes +- **Remark**: Optional description + +--- + +## OTA Update Flow + +### 1. Device Check Request +```http +POST /ota/ +Headers: + Device-Id: {MAC_ADDRESS} + Client-Id: {CLIENT_ID} +Body: +{ + "application": { + "version": "1.7.6" + }, + "board": { + "type": "esp32-generic" + } +} +``` + +### 2. Server Processing +**Location**: `DeviceServiceImpl.java - checkDeviceActive()` + +1. **Device Validation**: + - Verify MAC address format + - Check if device is registered in database + +2. **Update Decision Logic**: + ```java + if (device == null) { + // Device not registered - no update + return current_firmware_info; + } + + if (device.autoUpdate != 0) { + // Check for newer version + OtaEntity latest = getLatestOta(device.type); + if (compareVersions(latest.version, current.version) > 0) { + // Generate download URL + return firmware_with_download_url; + } + } + ``` + +3. **Download URL Generation**: + - Create temporary UUID + - Store OTA ID in Redis: `ota:id:{uuid}` + - Generate URL: `/otaMag/download/{uuid}` + - URL valid for 3 download attempts + +### 3. Server Response +```json +{ + "server_time": { + "timestamp": 1703123456789, + "timezone_offset": 480 + }, + "firmware": { + "version": "1.7.7", + "url": "http://server:8002/otaMag/download/abc-123-def" + }, + "websocket": { + "url": "ws://server:8000/xiaozhi/v1/" + }, + "mqtt": { + "endpoint": "broker:1883", + "client_id": "GID_test@@@mac@@@uuid", + "username": "base64_encoded_data", + "password": "hmac_signature" + } +} +``` + +### 4. Firmware Download +**Endpoint**: `GET /otaMag/download/{uuid}` + +**Process**: +1. Validate UUID exists in Redis +2. Check download count (max 3 attempts) +3. Retrieve firmware file from storage +4. Return file as binary stream +5. Increment download counter +6. Clean up after 3 downloads + +**Security Features**: +- UUID expires after use +- Download attempt limiting +- File path validation +- Safe filename generation + +--- + +## API Endpoints + +### OTA Check Endpoints + +#### POST /ota/ +- **Purpose**: Device firmware update check +- **Headers**: Device-Id, Client-Id +- **Response**: Update information if available + +#### POST /ota/activate +- **Purpose**: Quick device activation check +- **Headers**: Device-Id, Client-Id +- **Response**: 200 if registered, 202 if not + +### Management Endpoints + +#### GET /otaMag +- **Purpose**: List all firmware entries +- **Permission**: superAdmin +- **Parameters**: page, limit + +#### POST /otaMag +- **Purpose**: Create firmware entry +- **Permission**: superAdmin +- **Body**: OtaEntity + +#### PUT /otaMag/{id} +- **Purpose**: Update firmware entry +- **Permission**: superAdmin + +#### DELETE /otaMag/{id} +- **Purpose**: Delete firmware entry +- **Permission**: superAdmin + +#### POST /otaMag/upload +- **Purpose**: Upload firmware file +- **Permission**: superAdmin +- **Returns**: File path for database + +#### GET /otaMag/download/{uuid} +- **Purpose**: Download firmware file +- **Public**: Yes (with valid UUID) +- **Limit**: 3 attempts per UUID + +--- + +## Database Schema + +### Table: `ai_ota` +```sql +CREATE TABLE ai_ota ( + id VARCHAR(36) PRIMARY KEY, + firmware_name VARCHAR(255), + type VARCHAR(100), -- Device type + version VARCHAR(50), -- Semantic version + size BIGINT, -- File size in bytes + remark TEXT, -- Description + firmware_path VARCHAR(500), -- File storage path + sort INT, -- Display order + updater BIGINT, + update_date DATETIME, + creator BIGINT, + create_date DATETIME +); +``` + +### Table: `ai_device` +```sql +CREATE TABLE ai_device ( + id VARCHAR(36) PRIMARY KEY, + mac_address VARCHAR(50), + app_version VARCHAR(50), -- Current firmware version + auto_update TINYINT, -- 0=disabled, 1=enabled + -- other fields... +); +``` + +--- + +## Configuration + +### System Parameters +Configure in `sys_params` table or through Parameter Management UI: + +1. **server.websocket** + - WebSocket server URL for device connections + - Example: `ws://server:8000/xiaozhi/v1/` + +2. **server.ota** + - OTA server base URL + - Example: `http://server:8002/xiaozhi/` + +### Device Types +Configure in Dictionary Management (FIRMWARE_TYPE): +- `doit-ai-01-kit`: DOIT AI-01 Kit +- `esp32-generic`: ESP32 Generic +- `esp32s3-devkit`: ESP32-S3 DevKit +- `xiao-esp32s3`: XIAO ESP32S3 +- `m5stack-core`: M5Stack Core + +--- + +## Security Features + +### 1. File Upload Security +- Extension validation (.bin, .apk only) +- MD5 hash verification +- Duplicate detection +- Admin permission required + +### 2. Download Security +- Temporary UUID generation +- Redis-based token management +- Download attempt limiting (3 max) +- Automatic cleanup after use + +### 3. Version Control +- Semantic versioning comparison +- Per-device update control +- Type-specific firmware matching + +### 4. MQTT Authentication +- HMAC-SHA256 signature generation +- Base64 encoded credentials +- Session-specific UUIDs + +--- + +## Device-Server Communication + +### 1. Initial Connection +Device connects to OTA endpoint with: +- MAC address as Device-Id +- Current firmware version +- Board type information + +### 2. Update Check Flow +``` +Device Manager API Database + │ │ │ + ├──POST /ota/──────────────▶│ │ + │ (version, type) │ │ + │ ├──Check Device────────▶│ + │ │◀─────────────────────┤ + │ │ │ + │ ├──Get Latest OTA──────▶│ + │ │◀─────────────────────┤ + │ │ │ + │◀──Response────────────────┤ │ + │ (download URL if update) │ │ + │ │ │ + ├──GET /download/{uuid}────▶│ │ + │ │ │ + │◀──Firmware Binary─────────┤ │ +``` + +### 3. Fallback Support +If Manager API unavailable, devices can connect to: +- Xiaozhi Server OTA endpoint: `http://server:8003/ota/` +- Provides basic connectivity information +- No firmware updates (returns current version) + +--- + +## Version Comparison Logic + +The system uses semantic versioning (MAJOR.MINOR.PATCH): + +```java +private int compareVersions(String v1, String v2) { + String[] parts1 = v1.split("\\."); + String[] parts2 = v2.split("\\."); + + for (int i = 0; i < Math.max(parts1.length, parts2.length); i++) { + int num1 = i < parts1.length ? Integer.parseInt(parts1[i]) : 0; + int num2 = i < parts2.length ? Integer.parseInt(parts2[i]) : 0; + + if (num1 != num2) { + return Integer.compare(num1, num2); + } + } + return 0; +} +``` + +**Examples**: +- 1.7.7 > 1.7.6 ✓ (Update available) +- 2.0.0 > 1.9.9 ✓ (Major update) +- 1.7.6 = 1.7.6 ✗ (No update) + +--- + +## Troubleshooting + +### Common Issues + +1. **"OTA接口不正常,缺少websocket地址"** + - Solution: Configure `server.websocket` parameter + +2. **"OTA接口不正常,缺少ota地址"** + - Solution: Configure `server.ota` parameter + +3. **Firmware file not found** + - Check file exists in `uploadfile/` directory + - Verify path in database matches actual file + +4. **Device not receiving updates** + - Check `auto_update` flag is enabled (not 0) + - Verify device type matches firmware type + - Ensure version number is higher + +5. **Download limit exceeded** + - UUID expired after 3 attempts + - Generate new download link + +--- + +## Best Practices + +1. **Version Management** + - Use semantic versioning consistently + - Test firmware thoroughly before deployment + - Keep previous versions for rollback + +2. **Security** + - Regular security audits of firmware + - Monitor download patterns for abuse + - Use HTTPS in production + +3. **Device Management** + - Group devices by type for targeted updates + - Implement staged rollouts for critical updates + - Monitor update success rates + +4. **Storage Management** + - Regular cleanup of old firmware files + - Backup firmware files externally + - Monitor disk space usage + +--- + +## Future Enhancements + +Potential improvements to consider: +- Delta updates for bandwidth optimization +- Rollback mechanism for failed updates +- Update scheduling and staging +- Device group management +- Update progress tracking +- Firmware signing and verification +- Automated testing before deployment + +--- + +*Last Updated: 2025-08-25* +*Document Version: 1.0.0* \ No newline at end of file diff --git a/MANAGER_API_DOCUMENTATION.md b/MANAGER_API_DOCUMENTATION.md new file mode 100644 index 000000000..ecc401fdb --- /dev/null +++ b/MANAGER_API_DOCUMENTATION.md @@ -0,0 +1,221 @@ +# Manager API Documentation Guide + +## Swagger/OpenAPI Documentation + +The Manager API includes built-in Swagger/OpenAPI documentation using SpringDoc OpenAPI v2.8.8. + +### Accessing Swagger UI + +Once the Manager API is running, you can access the interactive API documentation at: + +``` +http://localhost:8080/swagger-ui/index.html +``` + +Replace `localhost:8080` with your actual server address and port. + +### API Groups + +The API is organized into the following groups: + +1. **Device APIs** (`/device/**`) + - Device registration + - Device management + - Device binding/unbinding + - Device status reporting + +2. **Agent APIs** (`/agent/**`) + - Agent management + - Agent configuration + - Agent templates + - Chat history + - Memory management + - Voice print management + - MCP access points + +3. **Model APIs** (`/models/**`) + - Model configuration + - Model providers + - Voice models + - LLM models + - TTS/ASR/VAD models + +4. **OTA APIs** (`/ota/**`) + - Over-the-air updates + - Firmware management + - Update status + +5. **Timbre APIs** (`/ttsVoice/**`) + - TTS voice management + - Voice configuration + +6. **Admin APIs** (`/admin/**`) + - User management + - System administration + - Server management + +7. **User APIs** (`/user/**`) + - User authentication + - User profile + - Password management + +8. **Config APIs** (`/config/**`) + - System configuration + - Agent model configuration + +### OpenAPI JSON Specification + +You can access the raw OpenAPI specification at: + +``` +http://localhost:8080/v3/api-docs +``` + +For specific API groups: +``` +http://localhost:8080/v3/api-docs/device +http://localhost:8080/v3/api-docs/agent +http://localhost:8080/v3/api-docs/models +http://localhost:8080/v3/api-docs/ota +http://localhost:8080/v3/api-docs/timbre +http://localhost:8080/v3/api-docs/admin +http://localhost:8080/v3/api-docs/user +http://localhost:8080/v3/api-docs/config +``` + +## Key API Endpoints + +### Authentication +- `POST /login` - User login +- `POST /logout` - User logout +- `POST /user/register` - User registration + +### Agent Management +- `GET /agent/list` - Get user's agents +- `GET /agent/{id}` - Get agent details +- `POST /agent` - Create new agent +- `PUT /agent/{id}` - Update agent +- `DELETE /agent/{id}` - Delete agent +- `PUT /agent/saveMemory/{macAddress}` - Update agent memory + +### Device Management +- `POST /device/register` - Register device +- `POST /device/bind` - Bind device to user +- `POST /device/unbind` - Unbind device +- `GET /device/list` - Get user's devices +- `POST /device/report` - Device status report + +### Model Configuration +- `GET /models/provider` - Get model providers +- `POST /models/provider` - Add model provider +- `PUT /models/provider/{id}` - Update model provider +- `DELETE /models/provider/{id}` - Delete model provider +- `GET /models/config` - Get model configurations +- `GET /models/voice/{modelId}` - Get voice options for TTS model + +### Configuration +- `GET /config/agentModels` - Get agent model configuration +- `POST /config/agentModels` - Update agent model configuration + +## API Authentication + +Most API endpoints require authentication. The API uses Shiro for security: + +1. **Login** to get a session token: +```bash +POST /login +Content-Type: application/json + +{ + "username": "your-username", + "password": "your-password" +} +``` + +2. **Use the token** in subsequent requests (stored in cookies/session) + +3. **Permissions** are role-based: + - `sys:role:normal` - Normal user permissions + - `sys:role:superAdmin` - Administrator permissions + +## Example API Calls + +### Create Memory Provider +```bash +POST /models/provider +Content-Type: application/json + +{ + "modelType": "Memory", + "providerCode": "mem0ai", + "name": "Mem0 Memory Provider", + "fields": [ + { + "key": "api_key", + "label": "API Key", + "type": "password", + "value": "your-mem0-api-key" + } + ], + "sort": 1 +} +``` + +### Update Agent Memory +```bash +PUT /agent/saveMemory/{macAddress} +Content-Type: application/json + +{ + "summaryMemory": "Memory configuration instructions" +} +``` + +### Get Agent Configuration +```bash +GET /agent/{agentId} +``` + +## Data Models + +The API uses DTOs (Data Transfer Objects) for request/response: + +- **AgentDTO** - Agent information +- **AgentMemoryDTO** - Agent memory update +- **DeviceDTO** - Device information +- **ModelConfigDTO** - Model configuration +- **ModelProviderDTO** - Model provider configuration + +All DTOs include Swagger annotations for documentation. + +## Error Handling + +The API returns standardized error responses: + +```json +{ + "code": 0, // 0 for success, non-zero for errors + "msg": "Success or error message", + "data": {} // Response data +} +``` + +Common error codes: +- `401` - Unauthorized +- `403` - Forbidden +- `404` - Not found +- `500` - Internal server error + +## Development Tips + +1. **Use Swagger UI** for testing APIs directly in the browser +2. **Check annotations** in controller classes for detailed API documentation +3. **Review DTOs** for request/response structures +4. **Monitor logs** for debugging API issues + +## Additional Resources + +- Controller classes in: `src/main/java/xiaozhi/modules/*/controller/` +- DTO classes in: `src/main/java/xiaozhi/modules/*/dto/` +- Entity classes in: `src/main/java/xiaozhi/modules/*/entity/` +- Service implementations in: `src/main/java/xiaozhi/modules/*/service/` \ No newline at end of file diff --git a/MEM0_INTEGRATION_GUIDE.md b/MEM0_INTEGRATION_GUIDE.md new file mode 100644 index 000000000..f84ee06fd --- /dev/null +++ b/MEM0_INTEGRATION_GUIDE.md @@ -0,0 +1,330 @@ +# Mem0 Integration Guide for Xiaozhi ESP32 Server + +## Overview +Mem0 is a memory management system integrated into the Xiaozhi ESP32 server that provides persistent memory capabilities for AI agents. This guide explains how to configure and use mem0 with both the manager API and web dashboard. + +## Architecture + +### Components +1. **Memory Provider** (`main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py`) + - Handles memory storage and retrieval + - Integrates with Mem0 cloud service + - Provides search and query capabilities + +2. **Manager API** (`main/manager-api`) + - REST endpoints for memory configuration + - Agent memory management + - Database persistence + +3. **Web Dashboard** (`main/manager-web`) + - UI for configuring memory providers + - Agent memory settings + - Visual management interface + +## Configuration + +### 1. Setting Up Mem0 API Key + +#### Via Web Dashboard: +1. Navigate to **Provider Management** page +2. Click **Add** button +3. Select **Memory Module** as Category +4. Choose **mem0ai** as Provider Code +5. Enter configuration: + ```json + { + "api_key": "your-mem0-api-key", + "api_version": "v1.1" + } + ``` +6. Save the provider configuration + +#### Via Manager API: +```bash +POST /api/model/provider +Content-Type: application/json + +{ + "modelType": "Memory", + "providerCode": "mem0ai", + "name": "Mem0 Memory Provider", + "fields": [ + { + "key": "api_key", + "label": "API Key", + "type": "password", + "value": "your-mem0-api-key" + }, + { + "key": "api_version", + "label": "API Version", + "type": "text", + "value": "v1.1" + } + ], + "sort": 1 +} +``` + +### 2. Configuring Agent Memory + +#### Via Web Dashboard: +1. Go to **Agent Management** +2. Create or edit an agent +3. In the agent configuration, enable memory: + - Toggle **Enable Memory** option + - Select **mem0ai** as memory provider + - Configure summary memory prompt + +#### Via Manager API: +```bash +POST /api/agent +Content-Type: application/json + +{ + "name": "My AI Assistant", + "summaryMemory": "Build a dynamic memory network that retains key information while intelligently maintaining information evolution trajectories within limited space. Summarize important user information from conversations to provide more personalized service in future interactions.", + "memoryProvider": "mem0ai", + "enableMemory": true +} +``` + +### 3. Updating Agent Memory + +The system supports dynamic memory updates through the API: + +```bash +PUT /api/agent/saveMemory/{macAddress} +Content-Type: application/json + +{ + "summaryMemory": "Updated memory instructions for the agent" +} +``` + +## Memory Flow + +### 1. Memory Save Process +```python +# When a conversation occurs: +1. Messages are collected from the dialogue +2. System filters out system messages +3. Formatted messages are sent to Mem0 API +4. Memory is associated with the agent's role_id +5. Result is logged for debugging +``` + +### 2. Memory Query Process +```python +# When agent needs to recall information: +1. Query string is sent to search method +2. Mem0 searches memories for the user_id (role_id) +3. Results are formatted with timestamps +4. Memories are sorted by recency (newest first) +5. Formatted memory string is returned to agent +``` + +## Integration Points + +### WebSocket Server Integration +The memory provider is initialized in `websocket_server.py`: +- Checks if "Memory" is in selected_modules +- Creates memory provider instance +- Passes to ConnectionHandler for use during conversations + +### Connection Handler +In `connection.py`, the memory provider: +- Saves conversation memories after each interaction +- Queries memories when needed for context +- Integrates with the dialogue flow + +## API Endpoints + +### Provider Management +- `GET /api/model/provider` - List all providers including memory +- `POST /api/model/provider` - Add new memory provider +- `PUT /api/model/provider/{id}` - Update memory provider configuration +- `DELETE /api/model/provider/{id}` - Remove memory provider + +### Agent Memory Management +- `GET /api/agent/{id}` - Get agent details including memory settings +- `PUT /api/agent/{id}` - Update agent including memory configuration +- `PUT /api/agent/saveMemory/{macAddress}` - Update memory by device MAC + +## Database Schema + +### Model Provider Table +```sql +CREATE TABLE model_provider ( + id BIGINT PRIMARY KEY, + model_type VARCHAR(50), -- 'Memory' for memory providers + provider_code VARCHAR(100), -- 'mem0ai' + name VARCHAR(255), + fields TEXT, -- JSON configuration + sort INT +); +``` + +### Agent Table +```sql +CREATE TABLE agent ( + id VARCHAR(36) PRIMARY KEY, + summary_memory TEXT, -- Memory configuration prompt + -- other fields... +); +``` + +## Best Practices + +### 1. Memory Prompt Design +Create effective summary memory prompts: +```text +"Build a dynamic memory network that retains key information while intelligently maintaining information evolution trajectories. Focus on: +- User preferences and habits +- Important personal information +- Conversation context and history +- Task-specific knowledge +Summarize in a way that enables personalized and contextual responses." +``` + +### 2. API Key Security +- Store API keys securely in the database +- Never expose keys in logs or responses +- Use environment variables for production deployments + +### 3. Memory Management +- Regularly review and update memory prompts +- Monitor memory usage through Mem0 dashboard +- Clean up outdated memories periodically + +### 4. Error Handling +The system includes robust error handling: +- Gracefully handles missing API keys +- Falls back to no-memory mode if service unavailable +- Logs errors for debugging without exposing sensitive data + +## Troubleshooting + +### Common Issues + +1. **Memory not saving** + - Check API key configuration + - Verify mem0ai service is accessible + - Check logs in `tmp/server.log` + +2. **No memories returned** + - Ensure agent has role_id configured + - Verify memories exist for the user + - Check query format and parameters + +3. **Configuration not appearing** + - Restart the xiaozhi-server after configuration changes + - Verify database changes are committed + - Check provider is enabled in selected_modules + +### Debug Mode +Enable debug logging to see memory operations: +```yaml +# In config.yaml +log: + log_level: DEBUG +``` + +## Example Integration + +### Complete Setup Flow +1. **Install dependencies**: + ```bash + pip install mem0ai==0.1.62 + ``` + +2. **Configure provider in dashboard**: + - Navigate to Provider Management + - Add mem0ai provider with API key + +3. **Create agent with memory**: + - Go to Agent Management + - Create new agent + - Enable memory and select mem0ai + - Configure summary memory prompt + +4. **Test memory functionality**: + - Connect device to agent + - Have conversations + - Check Mem0 dashboard for saved memories + - Test memory recall in subsequent conversations + +## Advanced Features + +### Custom Memory Formatting +The system formats memories with timestamps: +```python +[2024-03-15 14:30:45] User prefers morning meetings +[2024-03-14 10:15:23] User's favorite color is blue +[2024-03-13 09:45:12] User works in software engineering +``` + +### Memory Search +Query specific memories: +```python +results = memory_provider.query_memory("user preferences") +``` + +### Batch Operations +Process multiple agents' memories: +```python +for agent in agents: + memory_provider.role_id = agent.id + await memory_provider.save_memory(messages) +``` + +## Security Considerations + +1. **API Key Protection** + - Use environment variables + - Encrypt keys in database + - Rotate keys regularly + +2. **Data Privacy** + - Mem0 stores data securely + - Implement data retention policies + - Provide user data export/deletion options + +3. **Access Control** + - Limit memory access by role + - Audit memory operations + - Implement rate limiting + +## Performance Optimization + +1. **Caching** + - Cache frequently accessed memories + - Use Redis for temporary storage + - Implement TTL for cache entries + +2. **Batch Processing** + - Group memory operations + - Use async operations where possible + - Implement queue for high-volume scenarios + +3. **Monitoring** + - Track memory API response times + - Monitor error rates + - Set up alerts for failures + +## Future Enhancements + +Potential improvements for mem0 integration: +- Local memory fallback option +- Memory compression algorithms +- Multi-agent memory sharing +- Memory analytics dashboard +- Automated memory pruning +- Memory export/import tools + +## Support + +For issues or questions: +- Check logs in `tmp/server.log` +- Review Mem0 documentation at https://docs.mem0.ai +- Contact support with error details and configuration \ No newline at end of file diff --git a/add_mem0_system_param.py b/add_mem0_system_param.py new file mode 100644 index 000000000..e07ba7c56 --- /dev/null +++ b/add_mem0_system_param.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +""" +Script to add mem0.api_key system parameter +This will bypass the API key masking issue +""" + +import pymysql +import json +import sys +from datetime import datetime + +# Database configuration - from application-dev.yml +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', # Railway MySQL host + 'port': 25037, # Railway MySQL port + 'user': 'root', # Database username + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', # Database password + 'database': 'railway', # Database name + 'charset': 'utf8mb4', + 'connect_timeout': 30, # Connection timeout in seconds + 'read_timeout': 30, + 'write_timeout': 30, + 'autocommit': False, + 'ssl': {'ssl_disabled': False} # Enable SSL as per JDBC config +} + +# The actual mem0 API key +MEM0_API_KEY = "m0-WNBvGhsBGZU1NDKDF42ecLNAgMk0GRaToaKLT0wN" + +# Colors for output +class Colors: + HEADER = '\033[95m' + OKBLUE = '\033[94m' + OKCYAN = '\033[96m' + OKGREEN = '\033[92m' + WARNING = '\033[93m' + FAIL = '\033[91m' + ENDC = '\033[0m' + BOLD = '\033[1m' + +def print_header(text): + """Print a formatted header""" + print(f"\n{Colors.HEADER}{'='*80}{Colors.ENDC}") + print(f"{Colors.HEADER}{text}{Colors.ENDC}") + print(f"{Colors.HEADER}{'='*80}{Colors.ENDC}") + +def print_success(text): + """Print success message""" + print(f"{Colors.OKGREEN}[OK] {text}{Colors.ENDC}") + +def print_error(text): + """Print error message""" + print(f"{Colors.FAIL}[ERROR] {text}{Colors.ENDC}") + +def print_info(text): + """Print info message""" + print(f"{Colors.OKCYAN}[INFO] {text}{Colors.ENDC}") + +def print_warning(text): + """Print warning message""" + print(f"{Colors.WARNING}[WARNING] {text}{Colors.ENDC}") + +def connect_to_database(): + """Connect to the MySQL database""" + try: + print_info("Connecting to database...") + connection = pymysql.connect(**DB_CONFIG) + + # Test the connection + with connection.cursor() as cursor: + cursor.execute("SELECT 1") + cursor.fetchone() + + print_success("Successfully connected to database") + return connection + + except Exception as e: + print_error(f"Failed to connect to database: {str(e)}") + return None + +def add_system_parameter(connection): + """Add mem0.api_key system parameter""" + try: + with connection.cursor() as cursor: + # Check if parameter already exists + cursor.execute("SELECT * FROM sys_params WHERE param_code = %s", ('mem0.api_key',)) + existing = cursor.fetchone() + + if existing: + print_warning("Parameter mem0.api_key already exists:") + print(f" Current value: {existing[2][:10]}...{existing[2][-10:] if len(existing[2]) > 20 else existing[2]}") + + response = input(f"{Colors.WARNING}Do you want to update it? (yes/no): {Colors.ENDC}").lower() + if response not in ['yes', 'y']: + print_info("Skipping update") + return True + + # Update existing parameter + update_query = """ + UPDATE sys_params + SET param_value = %s, + update_date = NOW(), + updater = 1 + WHERE param_code = %s + """ + cursor.execute(update_query, (MEM0_API_KEY, 'mem0.api_key')) + connection.commit() + print_success("Updated existing mem0.api_key parameter") + + else: + # Get the next ID + cursor.execute("SELECT MAX(id) FROM sys_params") + max_id = cursor.fetchone()[0] + next_id = (max_id or 0) + 1 + + # Insert new parameter + insert_query = """ + INSERT INTO sys_params (id, param_code, param_value, value_type, param_type, remark, create_date, creator) + VALUES (%s, %s, %s, %s, %s, %s, NOW(), %s) + """ + + cursor.execute(insert_query, ( + next_id, + 'mem0.api_key', + MEM0_API_KEY, + 'string', + 1, # param_type: 1 for system parameters + 'Mem0 AI API key for memory management', + 1 # creator: admin user + )) + + connection.commit() + print_success("Added new mem0.api_key system parameter") + + return True + + except Exception as e: + connection.rollback() + print_error(f"Failed to add system parameter: {str(e)}") + return False + +def verify_parameter(connection): + """Verify the parameter was added correctly""" + try: + with connection.cursor() as cursor: + cursor.execute("SELECT * FROM sys_params WHERE param_code = %s", ('mem0.api_key',)) + result = cursor.fetchone() + + if result: + print_success("Parameter verification successful:") + print(f" ID: {result[0]}") + print(f" Code: {result[1]}") + print(f" Value: {result[2][:10]}...{result[2][-10:]}") + print(f" Type: {result[3]}") + print(f" Remark: {result[5]}") + return True + else: + print_error("Parameter not found after insertion") + return False + + except Exception as e: + print_error(f"Failed to verify parameter: {str(e)}") + return False + +def main(): + """Main function""" + print_header("Add Mem0 API Key System Parameter") + print_info(f"Target API Key: {MEM0_API_KEY[:10]}...{MEM0_API_KEY[-10:]}") + print_info(f"Timestamp: {datetime.now().isoformat()}") + + # Connect to database + connection = connect_to_database() + if not connection: + print_error("Cannot proceed without database connection") + return 1 + + try: + # Add system parameter + if add_system_parameter(connection): + # Verify the parameter + if verify_parameter(connection): + print_success("\n✅ System parameter added successfully!") + print_info("\nNext steps:") + print_info("1. Restart the manager-api service to load the new parameter") + print_info("2. Test device connection again") + print_info("3. Check that mem0 authentication now works") + return 0 + else: + return 1 + else: + return 1 + + finally: + connection.close() + print_info("Database connection closed") + +if __name__ == "__main__": + try: + sys.exit(main()) + except KeyboardInterrupt: + print("\n\nScript interrupted by user") + sys.exit(0) + except Exception as e: + print_error(f"Unexpected error: {str(e)}") + sys.exit(1) \ No newline at end of file diff --git a/add_mqtt_params.sql b/add_mqtt_params.sql new file mode 100644 index 000000000..5f48e010c --- /dev/null +++ b/add_mqtt_params.sql @@ -0,0 +1,11 @@ +-- Add MQTT configuration parameters to sys_params table +-- Replace the values with your actual MQTT broker configuration + +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) +VALUES (120, 'mqtt.broker', '139.59.7.72', 'string', 1, 'MQTT broker IP address'); + +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) +VALUES (121, 'mqtt.port', '1883', 'string', 1, 'MQTT broker port'); + +INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) +VALUES (122, 'mqtt.signature_key', 'test-signature-key-12345', 'string', 1, 'MQTT signature key for authentication'); \ No newline at end of file diff --git a/add_mqtt_params_railway.py b/add_mqtt_params_railway.py new file mode 100644 index 000000000..7a9862fd5 --- /dev/null +++ b/add_mqtt_params_railway.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Script to add MQTT configuration parameters to Railway MySQL database +""" + +import pymysql +import sys +import io +from typing import Optional + +# Set UTF-8 encoding for Windows console +sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') + +# Railway MySQL Database configuration +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'database': 'railway', + 'charset': 'utf8mb4' +} + +# MQTT parameters to add +MQTT_PARAMS = [ + { + 'id': 120, + 'param_code': 'mqtt.broker', + 'param_value': '192.168.1.107', + 'value_type': 'string', + 'param_type': 1, + 'remark': 'MQTT broker IP address' + }, + { + 'id': 121, + 'param_code': 'mqtt.port', + 'param_value': '1883', + 'value_type': 'string', + 'param_type': 1, + 'remark': 'MQTT broker port' + }, + { + 'id': 122, + 'param_code': 'mqtt.signature_key', + 'param_value': 'test-signature-key-12345', + 'value_type': 'string', + 'param_type': 1, + 'remark': 'MQTT signature key for authentication' + } +] + +def connect_to_db(): + """Connect to the Railway MySQL database""" + try: + connection = pymysql.connect(**DB_CONFIG) + print(f"✅ Connected to Railway MySQL database") + return connection + except pymysql.Error as e: + print(f"❌ Failed to connect to database: {e}") + sys.exit(1) + +def check_existing_params(cursor, param_code: str) -> Optional[dict]: + """Check if a parameter already exists""" + query = "SELECT * FROM sys_params WHERE param_code = %s" + cursor.execute(query, (param_code,)) + result = cursor.fetchone() + return result + +def get_next_available_id(cursor) -> int: + """Get the next available ID for sys_params table""" + query = "SELECT MAX(id) as max_id FROM sys_params" + cursor.execute(query) + result = cursor.fetchone() + if result and result['max_id']: + return result['max_id'] + 1 + return 120 # Start from 120 if table is empty + +def insert_or_update_param(cursor, param: dict) -> bool: + """Insert a new parameter or update existing one""" + try: + # First check if it already exists + existing = check_existing_params(cursor, param['param_code']) + if existing: + print(f"⚠️ Parameter '{param['param_code']}' already exists with value: {existing['param_value']}") + + # Update the existing parameter + update_query = """ + UPDATE sys_params + SET param_value = %s, remark = %s + WHERE param_code = %s + """ + cursor.execute(update_query, (param['param_value'], param['remark'], param['param_code'])) + print(f" ✅ Updated parameter '{param['param_code']}' to: {param['param_value']}") + return True + + # Get next available ID if the specified one is taken + check_id_query = "SELECT id FROM sys_params WHERE id = %s" + cursor.execute(check_id_query, (param['id'],)) + if cursor.fetchone(): + param['id'] = get_next_available_id(cursor) + print(f" ℹ️ Using ID {param['id']} for '{param['param_code']}'") + + # Insert new parameter + insert_query = """ + INSERT INTO sys_params (id, param_code, param_value, value_type, param_type, remark) + VALUES (%s, %s, %s, %s, %s, %s) + """ + cursor.execute(insert_query, ( + param['id'], + param['param_code'], + param['param_value'], + param['value_type'], + param['param_type'], + param['remark'] + )) + print(f"✅ Added parameter '{param['param_code']}' with value: {param['param_value']}") + return True + except pymysql.Error as e: + print(f"❌ Failed to insert/update '{param['param_code']}': {e}") + return False + +def verify_params(cursor): + """Verify that all MQTT parameters are in the database""" + print("\n📋 Current MQTT parameters in database:") + print("-" * 50) + query = "SELECT param_code, param_value, remark FROM sys_params WHERE param_code LIKE 'mqtt.%' ORDER BY param_code" + cursor.execute(query) + results = cursor.fetchall() + + if results: + for row in results: + print(f" • {row['param_code']}: {row['param_value']}") + print(f" ({row['remark']})") + else: + print(" No MQTT parameters found") + + return len(results) > 0 + +def main(): + print("🔧 Railway MySQL - MQTT Parameter Configuration Tool") + print("=" * 60) + print(f"📍 Connecting to: {DB_CONFIG['host']}:{DB_CONFIG['port']}") + print(f"📦 Database: {DB_CONFIG['database']}") + print("=" * 60) + + # Connect to database + connection = connect_to_db() + + try: + with connection.cursor(pymysql.cursors.DictCursor) as cursor: + print("\n📝 Adding/Updating MQTT parameters...") + print("-" * 50) + + # Add each parameter + changes_made = False + for param in MQTT_PARAMS: + if insert_or_update_param(cursor, param): + changes_made = True + + # Commit changes + if changes_made: + connection.commit() + print("\n✅ All changes committed to database") + else: + print("\n⚠️ No changes were made") + + # Verify parameters + verify_params(cursor) + + print("\n" + "=" * 60) + print("✅ MQTT parameters configuration complete!") + print("\n⚠️ IMPORTANT NEXT STEPS:") + print(" 1. Restart the manager-api server for changes to take effect") + print(" 2. The ESP32 device should now receive MQTT configuration") + print(" 3. The Python client should also connect successfully") + + except Exception as e: + print(f"❌ An error occurred: {e}") + connection.rollback() + finally: + connection.close() + print("\n🔌 Database connection closed") + +if __name__ == "__main__": + print("\n🚀 This script will configure MQTT parameters in your Railway MySQL database") + print(" The following parameters will be added/updated:") + print(" • mqtt.broker: 139.59.7.72") + print(" • mqtt.port: 1883") + print(" • mqtt.signature_key: test-signature-key-12345\n") + + try: + main() + except KeyboardInterrupt: + print("\n\n❌ Operation cancelled by user") + except Exception as e: + print(f"\n❌ Unexpected error: {e}") \ No newline at end of file diff --git a/check_database_structure.py b/check_database_structure.py new file mode 100644 index 000000000..d0035451a --- /dev/null +++ b/check_database_structure.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +""" +Script to check the ai_model_provider table structure and existing ASR services +""" + +import mysql.connector +from mysql.connector import Error +import json +from tabulate import tabulate + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect( + host='nozomi.proxy.rlwy.net', + port=25037, + database='railway', + user='root', + password='OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + charset='utf8mb4', + use_unicode=True, + ssl_disabled=True + ) + + if connection.is_connected(): + print("Successfully connected to Railway MySQL database") + return connection + + except Error as e: + print(f"Error connecting to MySQL: {e}") + return None + +def get_table_structure(connection, table_name): + """Get the structure of a table""" + cursor = connection.cursor() + try: + cursor.execute(f"DESCRIBE {table_name}") + columns = cursor.fetchall() + + print(f"\nStructure of table '{table_name}':") + headers = ["Field", "Type", "Null", "Key", "Default", "Extra"] + print(tabulate(columns, headers=headers, tablefmt="grid")) + + return columns + + except Error as e: + print(f"Error getting table structure: {e}") + return None + finally: + cursor.close() + +def get_existing_asr_providers(connection): + """Get all existing ASR providers""" + cursor = connection.cursor() + try: + cursor.execute(""" + SELECT id, model_type, provider_code, name, LENGTH(id) as id_length + FROM ai_model_provider + WHERE model_type = 'ASR' + ORDER BY id + """) + providers = cursor.fetchall() + + print(f"\nExisting ASR providers:") + headers = ["ID", "Model Type", "Provider Code", "Name", "ID Length"] + print(tabulate(providers, headers=headers, tablefmt="grid")) + + return providers + + except Error as e: + print(f"Error getting ASR providers: {e}") + return None + finally: + cursor.close() + +def get_existing_asr_configs(connection): + """Get all existing ASR model configurations""" + cursor = connection.cursor() + try: + cursor.execute(""" + SELECT id, model_type, model_code, model_name, LENGTH(id) as id_length + FROM ai_model_config + WHERE model_type = 'ASR' + ORDER BY id + """) + configs = cursor.fetchall() + + print(f"\nExisting ASR model configurations:") + headers = ["ID", "Model Type", "Model Code", "Model Name", "ID Length"] + print(tabulate(configs, headers=headers, tablefmt="grid")) + + return configs + + except Error as e: + print(f"Error getting ASR configs: {e}") + return None + finally: + cursor.close() + +def analyze_id_constraints(providers, configs): + """Analyze ID length constraints""" + print(f"\nID Length Analysis:") + + if providers: + provider_lengths = [row[4] for row in providers] # ID length is 5th column + print(f"Provider ID lengths: {provider_lengths}") + print(f"Max provider ID length: {max(provider_lengths)}") + print(f"Min provider ID length: {min(provider_lengths)}") + + if configs: + config_lengths = [row[4] for row in configs] # ID length is 5th column + print(f"Config ID lengths: {config_lengths}") + print(f"Max config ID length: {max(config_lengths)}") + print(f"Min config ID length: {min(config_lengths)}") + + # Check our proposed ID + proposed_provider_id = "SYSTEM_ASR_AmazonTranscribeStreaming" + proposed_config_id = "ASR_AmazonTranscribeStreaming" + + print(f"\nOur proposed IDs:") + print(f"Provider ID: '{proposed_provider_id}' (length: {len(proposed_provider_id)})") + print(f"Config ID: '{proposed_config_id}' (length: {len(proposed_config_id)})") + + if providers and len(proposed_provider_id) > max(provider_lengths): + print(f"WARNING: Proposed provider ID is longer than existing max ({max(provider_lengths)})") + + if configs and len(proposed_config_id) > max(config_lengths): + print(f"WARNING: Proposed config ID is longer than existing max ({max(config_lengths)})") + +def suggest_shorter_ids(): + """Suggest shorter ID alternatives""" + print(f"\nSuggested shorter IDs:") + + alternatives = [ + ("SYSTEM_ASR_AmazonTS", "ASR_AmazonTS"), + ("SYSTEM_ASR_AwsTranscribe", "ASR_AwsTranscribe"), + ("SYSTEM_ASR_AmazonStream", "ASR_AmazonStream"), + ("SYSTEM_ASR_AWSStream", "ASR_AWSStream"), + ] + + headers = ["Provider ID", "Config ID", "Provider Length", "Config Length"] + rows = [] + for provider_id, config_id in alternatives: + rows.append([provider_id, config_id, len(provider_id), len(config_id)]) + + print(tabulate(rows, headers=headers, tablefmt="grid")) + +def main(): + print("Checking xiaozhi database structure for Amazon Transcribe integration") + print("=" * 70) + + # Connect to database + connection = connect_to_database() + if not connection: + return + + try: + # Get table structures + print("\n" + "="*50) + provider_structure = get_table_structure(connection, "ai_model_provider") + + print("\n" + "="*50) + config_structure = get_table_structure(connection, "ai_model_config") + + # Get existing ASR services + print("\n" + "="*50) + providers = get_existing_asr_providers(connection) + + print("\n" + "="*50) + configs = get_existing_asr_configs(connection) + + # Analyze constraints + print("\n" + "="*50) + analyze_id_constraints(providers, configs) + + # Suggest alternatives + print("\n" + "="*50) + suggest_shorter_ids() + + finally: + if connection.is_connected(): + connection.close() + print(f"\nMySQL connection closed") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/check_mqtt_params.sql b/check_mqtt_params.sql new file mode 100644 index 000000000..b9344fbaf --- /dev/null +++ b/check_mqtt_params.sql @@ -0,0 +1,5 @@ +-- Check current MQTT-related parameters in sys_params table +SELECT * FROM sys_params WHERE param_code LIKE 'mqtt.%'; + +-- Check all system parameters to see what's configured +SELECT id, param_code, param_value, remark FROM sys_params ORDER BY id; \ No newline at end of file diff --git a/check_system_params.py b/check_system_params.py new file mode 100644 index 000000000..db6479972 --- /dev/null +++ b/check_system_params.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +""" +Script to check system parameters table for mem0.api_key +""" + +import pymysql +import json +import sys +from datetime import datetime + +# Database configuration - from application-dev.yml +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', # Railway MySQL host + 'port': 25037, # Railway MySQL port + 'user': 'root', # Database username + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', # Database password + 'database': 'railway', # Database name + 'charset': 'utf8mb4', + 'connect_timeout': 30, # Connection timeout in seconds + 'read_timeout': 30, + 'write_timeout': 30, + 'autocommit': False, + 'ssl': {'ssl_disabled': False} # Enable SSL as per JDBC config +} + +# Colors for output +class Colors: + HEADER = '\033[95m' + OKBLUE = '\033[94m' + OKCYAN = '\033[96m' + OKGREEN = '\033[92m' + WARNING = '\033[93m' + FAIL = '\033[91m' + ENDC = '\033[0m' + BOLD = '\033[1m' + +def print_header(text): + """Print a formatted header""" + print(f"\n{Colors.HEADER}{'='*80}{Colors.ENDC}") + print(f"{Colors.HEADER}{text}{Colors.ENDC}") + print(f"{Colors.HEADER}{'='*80}{Colors.ENDC}") + +def print_success(text): + """Print success message""" + print(f"{Colors.OKGREEN}[OK] {text}{Colors.ENDC}") + +def print_error(text): + """Print error message""" + print(f"{Colors.FAIL}[ERROR] {text}{Colors.ENDC}") + +def print_info(text): + """Print info message""" + print(f"{Colors.OKCYAN}[INFO] {text}{Colors.ENDC}") + +def print_warning(text): + """Print warning message""" + print(f"{Colors.WARNING}[WARNING] {text}{Colors.ENDC}") + +def connect_to_database(): + """Connect to the MySQL database""" + try: + print_info("Connecting to database...") + connection = pymysql.connect(**DB_CONFIG) + + # Test the connection + with connection.cursor() as cursor: + cursor.execute("SELECT 1") + cursor.fetchone() + + print_success("Successfully connected to database") + return connection + + except Exception as e: + print_error(f"Failed to connect to database: {str(e)}") + return None + +def check_system_params(connection): + """Check system parameters table for mem0.api_key""" + try: + with connection.cursor() as cursor: + # First, let's see what tables exist + print_info("Checking available tables...") + cursor.execute("SHOW TABLES LIKE '%param%'") + param_tables = cursor.fetchall() + + if param_tables: + print_success(f"Found parameter-related tables:") + for table in param_tables: + print(f" - {table[0]}") + + # Try different possible table names + possible_tables = [ + 'sys_params', + 'system_params', + 'sys_parameters', + 'system_parameters', + 'config_params', + 'application_params' + ] + + found_table = None + for table_name in possible_tables: + try: + cursor.execute(f"SELECT COUNT(*) FROM {table_name}") + found_table = table_name + print_success(f"Found system parameters table: {table_name}") + break + except pymysql.err.ProgrammingError: + continue + + if found_table: + # First, check the table structure + cursor.execute(f"DESCRIBE {found_table}") + columns = cursor.fetchall() + print_info(f"Table structure for {found_table}:") + for col in columns: + print(f" {col[0]} ({col[1]})") + + # Show all parameters for context + cursor.execute(f"SELECT * FROM {found_table} LIMIT 10") + all_params = cursor.fetchall() + print_info(f"\nFirst 10 parameters in {found_table}:") + for row in all_params: + print(f" Row: {row}") + + # Try to find mem0 parameter based on actual column structure + if columns: + # Assume first column is key, second is value + key_col = columns[0][0] + + query = f"SELECT * FROM {found_table} WHERE {key_col} = %s OR {key_col} LIKE %s" + cursor.execute(query, ('mem0.api_key', '%mem0%')) + results = cursor.fetchall() + + if results: + print_success("Found mem0-related parameters:") + for row in results: + print(f" Row: {row}") + else: + print_warning("No mem0.api_key parameter found in system parameters") + + else: + print_warning("No system parameters table found") + print_info("Available tables:") + cursor.execute("SHOW TABLES") + all_tables = cursor.fetchall() + for table in all_tables: + print(f" - {table[0]}") + + except Exception as e: + print_error(f"Failed to check system parameters: {str(e)}") + +def main(): + """Main function""" + print_header("System Parameters Check Script") + print_info(f"Timestamp: {datetime.now().isoformat()}") + + # Connect to database + connection = connect_to_database() + if not connection: + print_error("Cannot proceed without database connection") + return 1 + + try: + check_system_params(connection) + finally: + connection.close() + print_info("Database connection closed") + +if __name__ == "__main__": + try: + sys.exit(main()) + except KeyboardInterrupt: + print("\n\nScript interrupted by user") + sys.exit(0) + except Exception as e: + print_error(f"Unexpected error: {str(e)}") + sys.exit(1) \ No newline at end of file diff --git a/clear_redis.py b/clear_redis.py new file mode 100644 index 000000000..65deaa529 --- /dev/null +++ b/clear_redis.py @@ -0,0 +1,39 @@ +import redis + +# Redis connection configuration +redis_client = redis.Redis( + host='maglev.proxy.rlwy.net', + port=16780, + password='beVfOKcZjMUCBiZIQnvSMivhpSeijpKP', + username='default', + db=0, + decode_responses=True +) + +try: + print("Connecting to Redis...") + # Test connection + redis_client.ping() + print("Successfully connected to Redis!") + + # Get all keys to see what's cached + keys = redis_client.keys('*') + print(f"Found {len(keys)} keys in Redis:") + for key in keys[:10]: # Show first 10 keys + print(f" - {key}") + + if len(keys) > 10: + print(f" ... and {len(keys) - 10} more keys") + + # Clear all data in current database + result = redis_client.flushdb() + print(f"Redis cache cleared: {result}") + + # Verify it's cleared + keys_after = redis_client.keys('*') + print(f"Keys remaining after clear: {len(keys_after)}") + +except redis.exceptions.ConnectionError as e: + print(f"Failed to connect to Redis: {e}") +except Exception as e: + print(f"Error: {e}") \ No newline at end of file diff --git a/fix_migration.sql b/fix_migration.sql new file mode 100644 index 000000000..b8968fda9 --- /dev/null +++ b/fix_migration.sql @@ -0,0 +1,67 @@ +-- Clear Liquibase lock and failed changesets +DELETE FROM DATABASECHANGELOGLOCK WHERE ID = 1; + +-- Mark the failed changeset as already executed (skip it) +INSERT INTO DATABASECHANGELOG (ID, AUTHOR, FILENAME, DATEEXECUTED, ORDEREXECUTED, EXECTYPE, MD5SUM, DESCRIPTION, COMMENTS, TAG, LIQUIBASE, CONTEXTS, LABELS, DEPLOYMENT_ID) +SELECT '202501230004_translate_model_names', 'cheeko', 'db/changelog/db.changelog-master.yaml', NOW(), + (SELECT COALESCE(MAX(ORDEREXECUTED), 0) + 1 FROM DATABASECHANGELOG d), 'EXECUTED', 'placeholder', + 'Manual fix for column name issue', 'Manually fixed', NULL, '4.20.0', NULL, NULL, + CONCAT(UNIX_TIMESTAMP(NOW()), '000') +WHERE NOT EXISTS ( + SELECT 1 FROM DATABASECHANGELOG + WHERE ID = '202501230004_translate_model_names' + AND AUTHOR = 'cheeko' + AND FILENAME = 'db/changelog/db.changelog-master.yaml' +); + +-- Apply the translations manually with correct column names +UPDATE ai_model_provider SET name = 'SileroVAD Voice Activity Detection' WHERE name = 'SileroVAD语音活动检测'; +UPDATE ai_model_provider SET name = 'FunASR Speech Recognition' WHERE name = 'FunASR语音识别'; +UPDATE ai_model_provider SET name = 'SherpaASR Speech Recognition' WHERE name = 'SherpaASR语音识别'; +UPDATE ai_model_provider SET name = 'Volcano Engine Speech Recognition' WHERE name = '火山引擎语音识别'; +UPDATE ai_model_provider SET name = 'Tencent Speech Recognition' WHERE name = '腾讯语音识别'; +UPDATE ai_model_provider SET name = 'Tencent Speech Synthesis' WHERE name = '腾讯语音合成'; +UPDATE ai_model_provider SET name = 'Alibaba Cloud Speech Recognition' WHERE name = '阿里云语音识别'; +UPDATE ai_model_provider SET name = 'Alibaba Cloud Speech Recognition (Streaming)' WHERE name = '阿里云语音识别(流式)'; +UPDATE ai_model_provider SET name = 'Baidu Speech Recognition' WHERE name = '百度语音识别'; +UPDATE ai_model_provider SET name = 'OpenAI Speech Recognition' WHERE name = 'OpenAI语音识别'; +UPDATE ai_model_provider SET name = 'Volcano Engine Speech Recognition (Streaming)' WHERE name = '火山引擎语音识别(流式)'; +UPDATE ai_model_provider SET name = 'Alibaba Bailian Interface' WHERE name = '阿里百炼接口'; +UPDATE ai_model_provider SET name = 'Volcano Engine LLM' WHERE name = '火山引擎LLM'; +UPDATE ai_model_provider SET name = 'Volcano Engine TTS' WHERE name = '火山引擎TTS'; +UPDATE ai_model_provider SET name = 'Alibaba Cloud TTS' WHERE name = '阿里云TTS'; +UPDATE ai_model_provider SET name = 'Volcano Dual-Stream Speech Synthesis' WHERE name = '火山双流式语音合成'; +UPDATE ai_model_provider SET name = 'Linkerai Speech Synthesis' WHERE name = 'Linkerai语音合成'; +UPDATE ai_model_provider SET name = 'Alibaba Cloud Speech Synthesis (Streaming)' WHERE name = '阿里云语音合成(流式)'; +UPDATE ai_model_provider SET name = 'Index-TTS-vLLM Streaming Speech Synthesis' WHERE name = 'Index-TTS-vLLM流式语音合成'; +UPDATE ai_model_provider SET name = 'Mem0AI Memory' WHERE name = 'Mem0AI记忆'; +UPDATE ai_model_provider SET name = 'No Memory' WHERE name = '无记忆'; +UPDATE ai_model_provider SET name = 'Local Short Memory' WHERE name = '本地短记忆'; +UPDATE ai_model_provider SET name = 'No Intent Recognition' WHERE name = '无意图识别'; +UPDATE ai_model_provider SET name = 'LLM Intent Recognition' WHERE name = 'LLM意图识别'; +UPDATE ai_model_provider SET name = 'Function Call Intent Recognition' WHERE name = '函数调用意图识别'; +UPDATE ai_model_provider SET name = 'FunASR Server Speech Recognition' WHERE name = 'FunASR服务语音识别'; +UPDATE ai_model_provider SET name = 'MiniMax Speech Synthesis' WHERE name = 'MiniMax语音合成'; +UPDATE ai_model_provider SET name = 'OpenAI Speech Synthesis' WHERE name = 'OpenAI语音合成'; + +-- Update model config names +UPDATE ai_model_config SET model_name = 'Zhipu AI' WHERE model_name = '智谱AI'; +UPDATE ai_model_config SET model_name = 'Tongyi Qianwen' WHERE model_name = '通义千问'; +UPDATE ai_model_config SET model_name = 'Tongyi Bailian' WHERE model_name = '通义百炼'; +UPDATE ai_model_config SET model_name = 'Doubao Large Model' WHERE model_name = '豆包大模型'; +UPDATE ai_model_config SET model_name = 'Google Gemini' WHERE model_name = '谷歌Gemini'; +UPDATE ai_model_config SET model_name = 'Tencent Speech Recognition' WHERE model_name = '腾讯语音识别'; +UPDATE ai_model_config SET model_name = 'Alibaba Cloud Speech Recognition' WHERE model_name = '阿里云语音识别'; +UPDATE ai_model_config SET model_name = 'Baidu Speech Recognition' WHERE model_name = '百度语音识别'; +UPDATE ai_model_config SET model_name = 'MiniMax Speech Synthesis' WHERE model_name = 'MiniMax语音合成'; +UPDATE ai_model_config SET model_name = 'OpenAI Speech Synthesis' WHERE model_name = 'OpenAI语音合成'; +UPDATE ai_model_config SET model_name = 'Volcano Dual-Stream Speech Synthesis' WHERE model_name = '火山双流式语音合成'; +UPDATE ai_model_config SET model_name = 'Linkerai Speech Synthesis' WHERE model_name = 'Linkerai语音合成'; +UPDATE ai_model_config SET model_name = 'Mem0AI Memory' WHERE model_name = 'Mem0AI记忆'; +UPDATE ai_model_config SET model_name = 'Function Call Intent Recognition' WHERE model_name = '函数调用意图识别'; +UPDATE ai_model_config SET model_name = 'Zhipu Visual AI' WHERE model_name = '智谱视觉AI'; +UPDATE ai_model_config SET model_name = 'Qianwen Visual Model' WHERE model_name = '千问视觉模型'; +UPDATE ai_model_config SET model_name = 'Volcano Edge Large Model Gateway' WHERE model_name = '火山引擎边缘大模型网关'; + +-- Update TTS voice names (correct column name) +UPDATE ai_tts_voice SET name = 'Alibaba Cloud Xiaoyun' WHERE name = '阿里云小云'; \ No newline at end of file diff --git a/main/manager-api/README.md b/main/manager-api/README.md index ce90156a3..92baacd92 100644 --- a/main/manager-api/README.md +++ b/main/manager-api/README.md @@ -1,7 +1,12 @@ -This is a development document. If you need to deploy the Xiaozhi server, [click here to view the deployment tutorial](../../README.md#%E9%83%A8%E7%BD%B2%E6%96%87%E6%A1%A3) +This is a development document. If you need to deploy the Xiaozhi server, [click here to view the deployment tutorial](../../README.md#deployment-documentation) # Project Introduction + +run app + + +npm run serve manager-api: This project is developed based on the SpringBoot framework. When developing, use a code editor and select the `manager-api` folder as the project directory when importing the project. @@ -16,7 +21,7 @@ Vue 3.x # API Documentation After starting, open: http://localhost:8002/xiaozhi/doc.html -run app +to run app -npm run serve \ No newline at end of file +mvn spring-boot:run \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java b/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java index 8fb316419..17ec810ce 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java @@ -8,8 +8,8 @@ import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; /** - * Swagger配置 - * Copyright (c) 人人开源 All rights reserved. + * Swagger Configuration + * Copyright (c) RenRen Open Source All rights reserved. * Website: https://www.renren.io */ @Configuration @@ -82,8 +82,8 @@ public class SwaggerConfig { @Bean public OpenAPI customOpenAPI() { return new OpenAPI().info(new Info() - .title("xiaozhi-esp32-manager-api") - .description("xiaozhi-esp32-manager-api文档") + .title("Xiaozhi ESP32 Manager API") + .description("Xiaozhi ESP32 Manager API Documentation") .version("3.0") .termsOfService("https://127.0.0.1")); } diff --git a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java index bf7476004..9ae43c601 100644 --- a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java +++ b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java @@ -242,7 +242,7 @@ public interface Constant { /** * 无效固件URL */ - String INVALID_FIRMWARE_URL = "http://xiaozhi.server.com:8002/xiaozhi/otaMag/download/NOT_ACTIVATED_FIRMWARE_THIS_IS_A_INVALID_URL"; + String INVALID_FIRMWARE_URL = "http://xiaozhi.server.com:8002/toy/otaMag/download/NOT_ACTIVATED_FIRMWARE_THIS_IS_A_INVALID_URL"; /** * 字典类型 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentChatHistoryController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentChatHistoryController.java index 9d6542ccf..90a592997 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentChatHistoryController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentChatHistoryController.java @@ -13,7 +13,7 @@ import xiaozhi.common.utils.Result; import xiaozhi.modules.agent.dto.AgentChatHistoryReportDTO; import xiaozhi.modules.agent.service.biz.AgentChatHistoryBizService; -@Tag(name = "智能体聊天历史管理") +@Tag(name = "Agent Chat History Management") @RequiredArgsConstructor @RestController @RequestMapping("/agent/chat-history") @@ -27,7 +27,7 @@ public class AgentChatHistoryController { * * @param request 包含上传文件及相关信息的请求对象 */ - @Operation(summary = "小智服务聊天上报请求") + @Operation(summary = "Xiaozhi service chat report request") @PostMapping("/report") public Result uploadFile(@Valid @RequestBody AgentChatHistoryReportDTO request) { Boolean result = agentChatHistoryBizService.report(request); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java index 4a6585624..4bd8f948e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java @@ -53,7 +53,7 @@ import xiaozhi.modules.device.entity.DeviceEntity; import xiaozhi.modules.device.service.DeviceService; import xiaozhi.modules.security.user.SecurityUser; -@Tag(name = "智能体管理") +@Tag(name = "Agent Management") @AllArgsConstructor @RestController @RequestMapping("/agent") @@ -67,7 +67,7 @@ public class AgentController { private final RedisUtils redisUtils; @GetMapping("/list") - @Operation(summary = "获取用户智能体列表") + @Operation(summary = "Get user agents list") @RequiresPermissions("sys:role:normal") public Result> getUserAgents() { UserDetail user = SecurityUser.getUser(); @@ -76,7 +76,7 @@ public class AgentController { } @GetMapping("/all") - @Operation(summary = "智能体列表(管理员)") + @Operation(summary = "Agent list (admin)") @RequiresPermissions("sys:role:superAdmin") @Parameters({ @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true), @@ -89,7 +89,7 @@ public class AgentController { } @GetMapping("/{id}") - @Operation(summary = "获取智能体详情") + @Operation(summary = "Get agent details") @RequiresPermissions("sys:role:normal") public Result getAgentById(@PathVariable("id") String id) { AgentInfoVO agent = agentService.getAgentById(id); @@ -97,7 +97,7 @@ public class AgentController { } @PostMapping - @Operation(summary = "创建智能体") + @Operation(summary = "Create agent") @RequiresPermissions("sys:role:normal") public Result save(@RequestBody @Valid AgentCreateDTO dto) { String agentId = agentService.createAgent(dto); @@ -105,7 +105,7 @@ public class AgentController { } @PutMapping("/saveMemory/{macAddress}") - @Operation(summary = "根据设备id更新智能体") + @Operation(summary = "Update agent by device ID") public Result updateByDeviceId(@PathVariable String macAddress, @RequestBody @Valid AgentMemoryDTO dto) { DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress); if (device == null) { @@ -118,7 +118,7 @@ public class AgentController { } @PutMapping("/{id}") - @Operation(summary = "更新智能体") + @Operation(summary = "Update agent") @RequiresPermissions("sys:role:normal") public Result update(@PathVariable String id, @RequestBody @Valid AgentUpdateDTO dto) { agentService.updateAgentById(id, dto); @@ -126,7 +126,7 @@ public class AgentController { } @DeleteMapping("/{id}") - @Operation(summary = "删除智能体") + @Operation(summary = "Delete agent") @RequiresPermissions("sys:role:normal") public Result delete(@PathVariable String id) { // 先删除关联的设备 @@ -141,7 +141,7 @@ public class AgentController { } @GetMapping("/template") - @Operation(summary = "智能体模板模板列表") + @Operation(summary = "Agent template list") @RequiresPermissions("sys:role:normal") public Result> templateList() { List list = agentTemplateService @@ -169,7 +169,7 @@ public class AgentController { } @GetMapping("/{id}/sessions") - @Operation(summary = "获取智能体会话列表") + @Operation(summary = "Get agent sessions list") @RequiresPermissions("sys:role:normal") @Parameters({ @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true), @@ -184,7 +184,7 @@ public class AgentController { } @GetMapping("/{id}/chat-history/{sessionId}") - @Operation(summary = "获取智能体聊天记录") + @Operation(summary = "Get agent chat history") @RequiresPermissions("sys:role:normal") public Result> getAgentChatHistory( @PathVariable("id") String id, @@ -202,7 +202,7 @@ public class AgentController { return new Result>().ok(result); } @GetMapping("/{id}/chat-history/user") - @Operation(summary = "获取智能体聊天记录(用户)") + @Operation(summary = "Get agent chat history (user)") @RequiresPermissions("sys:role:normal") public Result> getRecentlyFiftyByAgentId( @PathVariable("id") String id) { @@ -220,7 +220,7 @@ public class AgentController { } @GetMapping("/{id}/chat-history/audio") - @Operation(summary = "获取音频内容") + @Operation(summary = "Get audio content") @RequiresPermissions("sys:role:normal") public Result getContentByAudioId( @PathVariable("id") String id) { @@ -230,7 +230,7 @@ public class AgentController { } @PostMapping("/audio/{audioId}") - @Operation(summary = "获取音频下载ID") + @Operation(summary = "Get audio download ID") @RequiresPermissions("sys:role:normal") public Result getAudioId(@PathVariable("audioId") String audioId) { byte[] audioData = agentChatAudioService.getAudio(audioId); @@ -243,7 +243,7 @@ public class AgentController { } @GetMapping("/play/{uuid}") - @Operation(summary = "播放音频") + @Operation(summary = "Play audio") public ResponseEntity playAudio(@PathVariable("uuid") String uuid) { String audioId = (String) redisUtils.get(RedisKeys.getAgentAudioIdKey(uuid)); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentMcpAccessPointController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentMcpAccessPointController.java index 3f369774c..43946df54 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentMcpAccessPointController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentMcpAccessPointController.java @@ -17,7 +17,7 @@ import xiaozhi.modules.agent.service.AgentMcpAccessPointService; import xiaozhi.modules.agent.service.AgentService; import xiaozhi.modules.security.user.SecurityUser; -@Tag(name = "智能体Mcp接入点管理") +@Tag(name = "Agent MCP Access Point Management") @RequiredArgsConstructor @RestController @RequestMapping("/agent/mcp") @@ -31,7 +31,7 @@ public class AgentMcpAccessPointController { * @param audioId 智能体id * @return 返回错误提醒或者Mcp接入点地址 */ - @Operation(summary = "获取智能体的Mcp接入点地址") + @Operation(summary = "Get agent MCP access point address") @GetMapping("/address/{agentId}") @RequiresPermissions("sys:role:normal") public Result getAgentMcpAccessAddress(@PathVariable("agentId") String agentId) { @@ -49,7 +49,7 @@ public class AgentMcpAccessPointController { return new Result().ok(agentMcpAccessAddress); } - @Operation(summary = "获取智能体的Mcp工具列表") + @Operation(summary = "Get agent MCP tools list") @GetMapping("/tools/{agentId}") @RequiresPermissions("sys:role:normal") public Result> getAgentMcpToolsList(@PathVariable("agentId") String agentId) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/controller/ConfigController.java b/main/manager-api/src/main/java/xiaozhi/modules/config/controller/ConfigController.java index f21795a3e..e8c35d5bf 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/controller/ConfigController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/controller/ConfigController.java @@ -21,7 +21,7 @@ import xiaozhi.modules.config.service.ConfigService; */ @RestController @RequestMapping("config") -@Tag(name = "参数管理") +@Tag(name = "Parameter Management") @AllArgsConstructor public class ConfigController { private final ConfigService configService; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java index 5eed96066..79ace92ae 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/config/service/impl/ConfigServiceImpl.java @@ -398,6 +398,22 @@ public class ConfigServiceImpl implements ConfigService { } if ("Memory".equals(modelTypes[i])) { Map map = (Map) model.getConfigJson(); + + // Fix for Memory configuration API key + if ("mem0ai".equals(map.get("type"))) { + // Always use the actual API key from system parameters for mem0 + String mem0ApiKey = sysParamsService.getValue("mem0.api_key", false); + if (StringUtils.isNotBlank(mem0ApiKey)) { + map.put("api_key", mem0ApiKey); + System.out.println("[DEBUG] Using mem0 API key from system parameters"); + } else { + // Fallback to the original logic + String apiKey = (String) map.get("api_key"); + System.out.println("[DEBUG] No system parameter for mem0.api_key, using config value: " + + (apiKey != null ? "(length: " + apiKey.length() + ")" : "null")); + } + } + if ("mem_local_short".equals(map.get("type"))) { memLocalShortLLMModelId = (String) map.get("llm"); if (StringUtils.isNotBlank(memLocalShortLLMModelId) diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java index d8f193cd5..028b0c099 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/dto/DeviceReportRespDTO.java @@ -77,6 +77,12 @@ public class DeviceReportRespDTO { @Getter @Setter public static class Mqtt { + @Schema(description = "MQTT服务器地址") + private String broker; + + @Schema(description = "MQTT服务器端口") + private Integer port; + @Schema(description = "MQTT服务器端点") private String endpoint; diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java index 67406a19f..96315ccc3 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java @@ -427,6 +427,8 @@ public class DeviceServiceImpl extends BaseServiceImpl String password = Base64.getEncoder().encodeToString(signature); // Set MQTT credentials + mqtt.setBroker(mqttBroker); + mqtt.setPort(Integer.parseInt(mqttPort)); mqtt.setEndpoint(mqttBroker + ":" + mqttPort); mqtt.setClient_id(clientId); mqtt.setUsername(username); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java index 32a5c0cc6..949836055 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelController.java @@ -30,7 +30,7 @@ import xiaozhi.modules.timbre.service.TimbreService; @AllArgsConstructor @RestController @RequestMapping("/models") -@Tag(name = "模型配置") +@Tag(name = "Model Configuration") public class ModelController { private final ModelProviderService modelProviderService; @@ -40,7 +40,7 @@ public class ModelController { private final AgentTemplateService agentTemplateService; @GetMapping("/names") - @Operation(summary = "获取所有模型名称") + @Operation(summary = "Get all model names") @RequiresPermissions("sys:role:normal") public Result> getModelNames(@RequestParam String modelType, @RequestParam(required = false) String modelName) { @@ -49,7 +49,7 @@ public class ModelController { } @GetMapping("/llm/names") - @Operation(summary = "获取LLM模型信息") + @Operation(summary = "Get LLM model information") @RequiresPermissions("sys:role:normal") public Result> getLlmModelCodeList(@RequestParam(required = false) String modelName) { List llmModelCodeList = modelConfigService.getLlmModelCodeList(modelName); @@ -57,7 +57,7 @@ public class ModelController { } @GetMapping("/{modelType}/provideTypes") - @Operation(summary = "获取模型供应器列表") + @Operation(summary = "Get model provider list") @RequiresPermissions("sys:role:superAdmin") public Result> getModelProviderList(@PathVariable String modelType) { List modelProviderDTOS = modelProviderService.getListByModelType(modelType); @@ -65,7 +65,7 @@ public class ModelController { } @GetMapping("/list") - @Operation(summary = "获取模型配置列表") + @Operation(summary = "Get model configuration list") @RequiresPermissions("sys:role:superAdmin") public Result> getModelConfigList( @RequestParam(required = true) String modelType, @@ -77,7 +77,7 @@ public class ModelController { } @PostMapping("/{modelType}/{provideCode}") - @Operation(summary = "新增模型配置") + @Operation(summary = "Add model configuration") @RequiresPermissions("sys:role:superAdmin") public Result addModelConfig(@PathVariable String modelType, @PathVariable String provideCode, @@ -88,7 +88,7 @@ public class ModelController { } @PutMapping("/{modelType}/{provideCode}/{id}") - @Operation(summary = "编辑模型配置") + @Operation(summary = "Edit model configuration") @RequiresPermissions("sys:role:superAdmin") public Result editModelConfig(@PathVariable String modelType, @PathVariable String provideCode, @@ -100,7 +100,7 @@ public class ModelController { } @DeleteMapping("/{id}") - @Operation(summary = "删除模型配置") + @Operation(summary = "Delete model configuration") @RequiresPermissions("sys:role:superAdmin") public Result deleteModelConfig(@PathVariable String id) { modelConfigService.delete(id); @@ -108,7 +108,7 @@ public class ModelController { } @GetMapping("/{id}") - @Operation(summary = "获取模型配置") + @Operation(summary = "Get model configuration") @RequiresPermissions("sys:role:superAdmin") public Result getModelConfig(@PathVariable String id) { ModelConfigEntity item = modelConfigService.selectById(id); @@ -117,7 +117,7 @@ public class ModelController { } @PutMapping("/enable/{id}/{status}") - @Operation(summary = "启用/关闭模型配置") + @Operation(summary = "Enable/disable model configuration") @RequiresPermissions("sys:role:superAdmin") public Result enableModelConfig(@PathVariable String id, @PathVariable Integer status) { ModelConfigEntity entity = modelConfigService.selectById(id); @@ -130,7 +130,7 @@ public class ModelController { } @PutMapping("/default/{id}") - @Operation(summary = "设置默认模型") + @Operation(summary = "Set default model") @RequiresPermissions("sys:role:superAdmin") public Result setDefaultModel(@PathVariable String id) { ModelConfigEntity entity = modelConfigService.selectById(id); @@ -151,7 +151,7 @@ public class ModelController { } @GetMapping("/{modelId}/voices") - @Operation(summary = "获取模型音色") + @Operation(summary = "Get model voices") @RequiresPermissions("sys:role:normal") public Result> getVoiceList(@PathVariable String modelId, @RequestParam(required = false) String voiceName) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelProviderController.java b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelProviderController.java index 24a7c7ca8..6b6be5aac 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelProviderController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/model/controller/ModelProviderController.java @@ -26,13 +26,13 @@ import xiaozhi.modules.model.service.ModelProviderService; @AllArgsConstructor @RestController @RequestMapping("/models/provider") -@Tag(name = "模型供应器") +@Tag(name = "Model Provider") public class ModelProviderController { private final ModelProviderService modelProviderService; @GetMapping - @Operation(summary = "获取模型供应器列表") + @Operation(summary = "Get model provider list") @RequiresPermissions("sys:role:superAdmin") public Result> getListPage(ModelProviderDTO modelProviderDTO, @RequestParam(required = true, defaultValue = "0") String page, @@ -42,7 +42,7 @@ public class ModelProviderController { } @PostMapping - @Operation(summary = "新增模型供应器") + @Operation(summary = "Add model provider") @RequiresPermissions("sys:role:superAdmin") public Result add(@RequestBody @Validated ModelProviderDTO modelProviderDTO) { ModelProviderDTO resp = modelProviderService.add(modelProviderDTO); @@ -50,7 +50,7 @@ public class ModelProviderController { } @PutMapping - @Operation(summary = "修改模型供应器") + @Operation(summary = "Edit model provider") @RequiresPermissions("sys:role:superAdmin") public Result edit(@RequestBody @Validated(UpdateGroup.class) ModelProviderDTO modelProviderDTO) { ModelProviderDTO resp = modelProviderService.edit(modelProviderDTO); @@ -58,7 +58,7 @@ public class ModelProviderController { } @PostMapping("/delete") - @Operation(summary = "删除模型供应器") + @Operation(summary = "Delete model provider") @RequiresPermissions("sys:role:superAdmin") @Parameter(name = "ids", description = "ID数组", required = true) public Result delete(@RequestBody List ids) { @@ -67,7 +67,7 @@ public class ModelProviderController { } @GetMapping("/plugin/names") - @Tag(name = "获取插件名称列表") + @Tag(name = "Get Plugin Name List") public Result> getPluginNameList() { return ResultUtils.success(modelProviderService.getPluginList()); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java b/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java index 2a89b26f5..7f5f076e3 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java @@ -45,7 +45,7 @@ import xiaozhi.modules.sys.vo.SysDictDataItem; @AllArgsConstructor @RestController @RequestMapping("/user") -@Tag(name = "登录管理") +@Tag(name = "Login Management") public class LoginController { private final SysUserService sysUserService; private final SysUserTokenService sysUserTokenService; @@ -54,7 +54,7 @@ public class LoginController { private final SysDictDataService sysDictDataService; @GetMapping("/captcha") - @Operation(summary = "验证码") + @Operation(summary = "Captcha") public void captcha(HttpServletResponse response, String uuid) throws IOException { // uuid不能为空 AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL); @@ -63,7 +63,7 @@ public class LoginController { } @PostMapping("/smsVerification") - @Operation(summary = "短信验证码") + @Operation(summary = "SMS verification code") public Result smsVerification(@RequestBody SmsVerificationDTO dto) { // 验证图形验证码 boolean validate = captchaService.validate(dto.getCaptchaId(), dto.getCaptcha(), true); @@ -81,7 +81,7 @@ public class LoginController { } @PostMapping("/login") - @Operation(summary = "登录") + @Operation(summary = "Login") public Result login(@RequestBody LoginDTO login) { // 验证是否正确输入验证码 boolean validate = captchaService.validate(login.getCaptchaId(), login.getCaptcha(), true); @@ -102,8 +102,10 @@ public class LoginController { } @PostMapping("/register") - @Operation(summary = "注册") - public Result register(@RequestBody LoginDTO login) { + + @Operation(summary = "Register") + public Result register(@RequestBody LoginDTO login) { + Production1 if (!sysUserService.getAllowUserRegister()) { throw new RenException("当前不允许普通用户注册"); } @@ -151,7 +153,7 @@ public class LoginController { } @GetMapping("/info") - @Operation(summary = "用户信息获取") + @Operation(summary = "Get user information") public Result info() { UserDetail user = SecurityUser.getUser(); Result result = new Result<>(); @@ -160,7 +162,7 @@ public class LoginController { } @PutMapping("/change-password") - @Operation(summary = "修改用户密码") + @Operation(summary = "Change user password") public Result changePassword(@RequestBody PasswordDTO passwordDTO) { // 判断非空 ValidatorUtils.validateEntity(passwordDTO); @@ -170,7 +172,7 @@ public class LoginController { } @PutMapping("/retrieve-password") - @Operation(summary = "找回密码") + @Operation(summary = "Retrieve password") public Result retrievePassword(@RequestBody RetrievePasswordDTO dto) { // 是否开启手机注册 Boolean isMobileRegister = sysParamsService @@ -203,7 +205,7 @@ public class LoginController { } @GetMapping("/pub-config") - @Operation(summary = "公共配置") + @Operation(summary = "Public configuration") public Result> pubConfig() { Map config = new HashMap<>(); config.put("enableMobileRegister", sysParamsService diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java index 2ccc1e6ad..3def98ef8 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java @@ -37,14 +37,14 @@ import xiaozhi.modules.sys.vo.AdminPageUserVO; @AllArgsConstructor @RestController @RequestMapping("/admin") -@Tag(name = "管理员管理") +@Tag(name = "Administrator Management") public class AdminController { private final SysUserService sysUserService; private final DeviceService deviceService; @GetMapping("/users") - @Operation(summary = "分页查找用户") + @Operation(summary = "Paginated user search") @RequiresPermissions("sys:role:superAdmin") @Parameters({ @Parameter(name = "mobile", description = "用户手机号码", required = false), @@ -63,7 +63,7 @@ public class AdminController { } @PutMapping("/users/{id}") - @Operation(summary = "重置密码") + @Operation(summary = "Reset password") @RequiresPermissions("sys:role:superAdmin") public Result update( @PathVariable Long id) { @@ -72,7 +72,7 @@ public class AdminController { } @DeleteMapping("/users/{id}") - @Operation(summary = "用户删除") + @Operation(summary = "Delete user") @RequiresPermissions("sys:role:superAdmin") public Result delete(@PathVariable Long id) { sysUserService.deleteById(id); @@ -80,7 +80,7 @@ public class AdminController { } @PutMapping("/users/changeStatus/{status}") - @Operation(summary = "批量修改用户状态") + @Operation(summary = "Batch modify user status") @RequiresPermissions("sys:role:superAdmin") @Parameter(name = "status", description = "用户状态", required = true) public Result changeStatus(@PathVariable Integer status, @RequestBody String[] userIds) { @@ -89,7 +89,7 @@ public class AdminController { } @GetMapping("/device/all") - @Operation(summary = "分页查找设备") + @Operation(summary = "Paginated device search") @RequiresPermissions("sys:role:superAdmin") @Parameters({ @Parameter(name = "keywords", description = "设备关键词", required = false), diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/ServerSideManageController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/ServerSideManageController.java index 0b6b6a5be..7b6a51d69 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/ServerSideManageController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/ServerSideManageController.java @@ -36,7 +36,7 @@ import xiaozhi.modules.sys.utils.WebSocketClientManager; */ @RestController @RequestMapping("/admin/server") -@Tag(name = "服务端管理") +@Tag(name = "Server Management") @AllArgsConstructor public class ServerSideManageController { private final SysParamsService sysParamsService; @@ -47,7 +47,7 @@ public class ServerSideManageController { objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } - @Operation(summary = "获取Ws服务端列表") + @Operation(summary = "Get WebSocket server list") @GetMapping("/server-list") @RequiresPermissions("sys:role:superAdmin") public Result> getWsServerList() { @@ -58,7 +58,7 @@ public class ServerSideManageController { return new Result>().ok(Arrays.asList(wsText.split(";"))); } - @Operation(summary = "通知python服务端更新配置") + @Operation(summary = "Notify Python server to update configuration") @PostMapping("/emit-action") @LogOperation("通知python服务端更新配置") @RequiresPermissions("sys:role:superAdmin") diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictDataController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictDataController.java index 30187fe8a..13fa8edab 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictDataController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictDataController.java @@ -37,12 +37,12 @@ import xiaozhi.modules.sys.vo.SysDictDataVO; @AllArgsConstructor @RestController @RequestMapping("/admin/dict/data") -@Tag(name = "字典数据管理") +@Tag(name = "Dictionary Data Management") public class SysDictDataController { private final SysDictDataService sysDictDataService; @GetMapping("/page") - @Operation(summary = "分页查询字典数据") + @Operation(summary = "Paginated dictionary data query") @RequiresPermissions("sys:role:superAdmin") @Parameters({ @Parameter(name = "dictTypeId", description = "字典类型ID", required = true), @Parameter(name = "dictLabel", description = "数据标签"), @Parameter(name = "dictValue", description = "数据值"), @@ -60,7 +60,7 @@ public class SysDictDataController { } @GetMapping("/{id}") - @Operation(summary = "获取字典数据详情") + @Operation(summary = "Get dictionary data details") @RequiresPermissions("sys:role:superAdmin") public Result get(@PathVariable("id") Long id) { SysDictDataVO vo = sysDictDataService.get(id); @@ -68,7 +68,7 @@ public class SysDictDataController { } @PostMapping("/save") - @Operation(summary = "新增字典数据") + @Operation(summary = "Add dictionary data") @RequiresPermissions("sys:role:superAdmin") public Result save(@RequestBody SysDictDataDTO dto) { ValidatorUtils.validateEntity(dto); @@ -77,7 +77,7 @@ public class SysDictDataController { } @PutMapping("/update") - @Operation(summary = "修改字典数据") + @Operation(summary = "Modify dictionary data") @RequiresPermissions("sys:role:superAdmin") public Result update(@RequestBody SysDictDataDTO dto) { ValidatorUtils.validateEntity(dto); @@ -86,7 +86,7 @@ public class SysDictDataController { } @PostMapping("/delete") - @Operation(summary = "删除字典数据") + @Operation(summary = "Delete dictionary data") @RequiresPermissions("sys:role:superAdmin") @Parameter(name = "ids", description = "ID数组", required = true) public Result delete(@RequestBody Long[] ids) { @@ -95,7 +95,7 @@ public class SysDictDataController { } @GetMapping("/type/{dictType}") - @Operation(summary = "获取字典数据列表") + @Operation(summary = "Get dictionary data list") @RequiresPermissions("sys:role:normal") public Result> getDictDataByType(@PathVariable("dictType") String dictType) { List list = sysDictDataService.getDictDataByType(dictType); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictTypeController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictTypeController.java index f16409b03..cceac44f8 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictTypeController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysDictTypeController.java @@ -34,12 +34,12 @@ import xiaozhi.modules.sys.vo.SysDictTypeVO; @AllArgsConstructor @RestController @RequestMapping("/admin/dict/type") -@Tag(name = "字典类型管理") +@Tag(name = "Dictionary Type Management") public class SysDictTypeController { private final SysDictTypeService sysDictTypeService; @GetMapping("/page") - @Operation(summary = "分页查询字典类型") + @Operation(summary = "Paginated dictionary type query") @RequiresPermissions("sys:role:superAdmin") @Parameters({ @Parameter(name = "dictType", description = "字典类型编码"), @Parameter(name = "dictName", description = "字典类型名称"), @@ -52,7 +52,7 @@ public class SysDictTypeController { } @GetMapping("/{id}") - @Operation(summary = "获取字典类型详情") + @Operation(summary = "Get dictionary type details") @RequiresPermissions("sys:role:superAdmin") public Result get(@PathVariable("id") Long id) { SysDictTypeVO vo = sysDictTypeService.get(id); @@ -60,7 +60,7 @@ public class SysDictTypeController { } @PostMapping("/save") - @Operation(summary = "保存字典类型") + @Operation(summary = "Save dictionary type") @RequiresPermissions("sys:role:superAdmin") public Result save(@RequestBody SysDictTypeDTO dto) { // 参数校验 @@ -71,7 +71,7 @@ public class SysDictTypeController { } @PutMapping("/update") - @Operation(summary = "修改字典类型") + @Operation(summary = "Modify dictionary type") @RequiresPermissions("sys:role:superAdmin") public Result update(@RequestBody SysDictTypeDTO dto) { // 参数校验 @@ -82,7 +82,7 @@ public class SysDictTypeController { } @PostMapping("/delete") - @Operation(summary = "删除字典类型") + @Operation(summary = "Delete dictionary type") @RequiresPermissions("sys:role:superAdmin") @Parameter(name = "ids", description = "ID数组", required = true) public Result delete(@RequestBody Long[] ids) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java index 12555bb91..5684801a4 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysParamsController.java @@ -45,7 +45,7 @@ import xiaozhi.modules.sys.utils.WebSocketValidator; */ @RestController @RequestMapping("admin/params") -@Tag(name = "参数管理") +@Tag(name = "Parameter Management") @AllArgsConstructor public class SysParamsController { private final SysParamsService sysParamsService; @@ -53,7 +53,7 @@ public class SysParamsController { private final RestTemplate restTemplate; @GetMapping("page") - @Operation(summary = "分页") + @Operation(summary = "Pagination") @Parameters({ @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", in = ParameterIn.QUERY, required = true, ref = "int"), @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"), @@ -69,7 +69,7 @@ public class SysParamsController { } @GetMapping("{id}") - @Operation(summary = "信息") + @Operation(summary = "Information") @RequiresPermissions("sys:role:superAdmin") public Result get(@PathVariable("id") Long id) { SysParamsDTO data = sysParamsService.get(id); @@ -78,7 +78,7 @@ public class SysParamsController { } @PostMapping - @Operation(summary = "保存") + @Operation(summary = "Save") @LogOperation("保存") @RequiresPermissions("sys:role:superAdmin") public Result save(@RequestBody SysParamsDTO dto) { @@ -91,7 +91,7 @@ public class SysParamsController { } @PutMapping - @Operation(summary = "修改") + @Operation(summary = "Modify") @LogOperation("修改") @RequiresPermissions("sys:role:superAdmin") public Result update(@RequestBody SysParamsDTO dto) { @@ -150,7 +150,7 @@ public class SysParamsController { } @PostMapping("/delete") - @Operation(summary = "删除") + @Operation(summary = "Delete") @LogOperation("删除") @RequiresPermissions("sys:role:superAdmin") public Result delete(@RequestBody String[] ids) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/timbre/controller/TimbreController.java b/main/manager-api/src/main/java/xiaozhi/modules/timbre/controller/TimbreController.java index ff420c02d..450353aac 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/timbre/controller/TimbreController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/timbre/controller/TimbreController.java @@ -35,12 +35,12 @@ import xiaozhi.modules.timbre.vo.TimbreDetailsVO; @AllArgsConstructor @RestController @RequestMapping("/ttsVoice") -@Tag(name = "音色管理") +@Tag(name = "Timbre Management") public class TimbreController { private final TimbreService timbreService; @GetMapping - @Operation(summary = "分页查找") + @Operation(summary = "Paginated search") @RequiresPermissions("sys:role:superAdmin") @Parameters({ @Parameter(name = "ttsModelId", description = "对应 TTS 模型主键", required = true), @@ -62,7 +62,7 @@ public class TimbreController { } @PostMapping - @Operation(summary = "音色保存") + @Operation(summary = "Save timbre") @RequiresPermissions("sys:role:superAdmin") public Result save(@RequestBody TimbreDataDTO dto) { ValidatorUtils.validateEntity(dto); @@ -71,7 +71,7 @@ public class TimbreController { } @PutMapping("/{id}") - @Operation(summary = "音色修改") + @Operation(summary = "Modify timbre") @RequiresPermissions("sys:role:superAdmin") public Result update( @PathVariable String id, @@ -82,7 +82,7 @@ public class TimbreController { } @PostMapping("/delete") - @Operation(summary = "音色删除") + @Operation(summary = "Delete timbre") @RequiresPermissions("sys:role:superAdmin") public Result delete(@RequestBody String[] ids) { timbreService.delete(ids); diff --git a/main/manager-api/src/main/resources/application.yml b/main/manager-api/src/main/resources/application.yml index 3d98bd857..9a8d3d1f6 100644 --- a/main/manager-api/src/main/resources/application.yml +++ b/main/manager-api/src/main/resources/application.yml @@ -7,7 +7,7 @@ server: min-spare: 30 port: 8002 servlet: - context-path: /xiaozhi + context-path: /toy session: cookie: http-only: true diff --git a/main/manager-api/src/main/resources/db/changelog/202501230002_translate_dict_names.sql b/main/manager-api/src/main/resources/db/changelog/202501230002_translate_dict_names.sql new file mode 100644 index 000000000..1dc576afc --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202501230002_translate_dict_names.sql @@ -0,0 +1,7 @@ +-- Translate Chinese dictionary type names to English +UPDATE `sys_dict_type` SET `dict_name` = 'Mobile Area' WHERE `dict_type` = 'MOBILE_AREA'; +UPDATE `sys_dict_type` SET `dict_name` = 'Firmware Type' WHERE `dict_type` = 'FIRMWARE_TYPE'; + +-- Also update remarks to English +UPDATE `sys_dict_type` SET `remark` = 'Mobile area codes dictionary' WHERE `dict_type` = 'MOBILE_AREA'; +UPDATE `sys_dict_type` SET `remark` = 'Firmware types dictionary' WHERE `dict_type` = 'FIRMWARE_TYPE'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202501230003_translate_provider_fields.sql b/main/manager-api/src/main/resources/db/changelog/202501230003_translate_provider_fields.sql new file mode 100644 index 000000000..943b10641 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202501230003_translate_provider_fields.sql @@ -0,0 +1,401 @@ +-- Translate provider field labels from Chinese to English +-- This will update the field labels shown in the Call Information section + +-- Update common field labels across all providers +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"API密钥"', '"label":"API Key"') +WHERE fields LIKE '%"label":"API密钥"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"服务地址"', '"label":"Service URL"') +WHERE fields LIKE '%"label":"服务地址"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"基础URL"', '"label":"Base URL"') +WHERE fields LIKE '%"label":"基础URL"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"模型名称"', '"label":"Model Name"') +WHERE fields LIKE '%"label":"模型名称"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"输出目录"', '"label":"Output Directory"') +WHERE fields LIKE '%"label":"输出目录"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"端口号"', '"label":"Port"') +WHERE fields LIKE '%"label":"端口号"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"服务类型"', '"label":"Service Type"') +WHERE fields LIKE '%"label":"服务类型"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"是否使用SSL"', '"label":"Use SSL"') +WHERE fields LIKE '%"label":"是否使用SSL"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"请求方式"', '"label":"Request Method"') +WHERE fields LIKE '%"label":"请求方式"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"请求参数"', '"label":"Request Parameters"') +WHERE fields LIKE '%"label":"请求参数"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"请求头"', '"label":"Request Headers"') +WHERE fields LIKE '%"label":"请求头"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"音频格式"', '"label":"Audio Format"') +WHERE fields LIKE '%"label":"音频格式"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"访问令牌"', '"label":"Access Token"') +WHERE fields LIKE '%"label":"访问令牌"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"响应格式"', '"label":"Response Format"') +WHERE fields LIKE '%"label":"响应格式"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"音色"', '"label":"Voice"') +WHERE fields LIKE '%"label":"音色"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"应用密钥"', '"label":"App Key"') +WHERE fields LIKE '%"label":"应用密钥"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"访问密钥ID"', '"label":"Access Key ID"') +WHERE fields LIKE '%"label":"访问密钥ID"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"访问密钥密码"', '"label":"Access Key Secret"') +WHERE fields LIKE '%"label":"访问密钥密码"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"授权"', '"label":"Authorization"') +WHERE fields LIKE '%"label":"授权"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"速度"', '"label":"Speed"') +WHERE fields LIKE '%"label":"速度"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"温度"', '"label":"Temperature"') +WHERE fields LIKE '%"label":"温度"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"音色ID"', '"label":"Voice ID"') +WHERE fields LIKE '%"label":"音色ID"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"采样率"', '"label":"Sample Rate"') +WHERE fields LIKE '%"label":"采样率"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"参考音频"', '"label":"Reference Audio"') +WHERE fields LIKE '%"label":"参考音频"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"参考文本"', '"label":"Reference Text"') +WHERE fields LIKE '%"label":"参考文本"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"是否标准化"', '"label":"Normalize"') +WHERE fields LIKE '%"label":"是否标准化"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"最大新令牌数"', '"label":"Max New Tokens"') +WHERE fields LIKE '%"label":"最大新令牌数"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"块长度"', '"label":"Chunk Length"') +WHERE fields LIKE '%"label":"块长度"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"重复惩罚"', '"label":"Repetition Penalty"') +WHERE fields LIKE '%"label":"重复惩罚"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"是否流式"', '"label":"Streaming"') +WHERE fields LIKE '%"label":"是否流式"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"是否使用内存缓存"', '"label":"Use Memory Cache"') +WHERE fields LIKE '%"label":"是否使用内存缓存"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"种子"', '"label":"Seed"') +WHERE fields LIKE '%"label":"种子"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"通道数"', '"label":"Channels"') +WHERE fields LIKE '%"label":"通道数"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"参考ID"', '"label":"Reference ID"') +WHERE fields LIKE '%"label":"参考ID"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"组ID"', '"label":"Group ID"') +WHERE fields LIKE '%"label":"组ID"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"文本语言"', '"label":"Text Language"') +WHERE fields LIKE '%"label":"文本语言"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"参考音频路径"', '"label":"Reference Audio Path"') +WHERE fields LIKE '%"label":"参考音频路径"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"提示文本"', '"label":"Prompt Text"') +WHERE fields LIKE '%"label":"提示文本"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"提示语言"', '"label":"Prompt Language"') +WHERE fields LIKE '%"label":"提示语言"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"文本分割方法"', '"label":"Text Split Method"') +WHERE fields LIKE '%"label":"文本分割方法"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"批处理大小"', '"label":"Batch Size"') +WHERE fields LIKE '%"label":"批处理大小"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"批处理阈值"', '"label":"Batch Threshold"') +WHERE fields LIKE '%"label":"批处理阈值"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"是否分桶"', '"label":"Split Bucket"') +WHERE fields LIKE '%"label":"是否分桶"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"是否返回片段"', '"label":"Return Fragment"') +WHERE fields LIKE '%"label":"是否返回片段"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"速度因子"', '"label":"Speed Factor"') +WHERE fields LIKE '%"label":"速度因子"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"是否流式模式"', '"label":"Streaming Mode"') +WHERE fields LIKE '%"label":"是否流式模式"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"是否并行推理"', '"label":"Parallel Inference"') +WHERE fields LIKE '%"label":"是否并行推理"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"辅助参考音频路径"', '"label":"Auxiliary Reference Audio Paths"') +WHERE fields LIKE '%"label":"辅助参考音频路径"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"切分标点"', '"label":"Cut Punctuation"') +WHERE fields LIKE '%"label":"切分标点"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"输入参考"', '"label":"Input References"') +WHERE fields LIKE '%"label":"输入参考"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"采样步数"', '"label":"Sample Steps"') +WHERE fields LIKE '%"label":"采样步数"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"是否使用SR"', '"label":"Use SR"') +WHERE fields LIKE '%"label":"是否使用SR"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"音调因子"', '"label":"Pitch Factor"') +WHERE fields LIKE '%"label":"音调因子"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"音量变化"', '"label":"Volume Change dB"') +WHERE fields LIKE '%"label":"音量变化"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"目标语言"', '"label":"Target Language"') +WHERE fields LIKE '%"label":"目标语言"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"格式"', '"label":"Format"') +WHERE fields LIKE '%"label":"格式"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"情感"', '"label":"Emotion"') +WHERE fields LIKE '%"label":"情感"%'; + +-- Additional field translations +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"应用ID"', '"label":"App ID"') +WHERE fields LIKE '%"label":"应用ID"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"应用AppID"', '"label":"App ID"') +WHERE fields LIKE '%"label":"应用AppID"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"应用AppKey"', '"label":"App Key"') +WHERE fields LIKE '%"label":"应用AppKey"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"临时Token"', '"label":"Temporary Token"') +WHERE fields LIKE '%"label":"临时Token"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"AccessKey ID"', '"label":"Access Key ID"') +WHERE fields LIKE '%"label":"AccessKey ID"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"AccessKey Secret"', '"label":"Access Key Secret"') +WHERE fields LIKE '%"label":"AccessKey Secret"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"API服务地址"', '"label":"API Service URL"') +WHERE fields LIKE '%"label":"API服务地址"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"API地址"', '"label":"API URL"') +WHERE fields LIKE '%"label":"API地址"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"WebSocket地址"', '"label":"WebSocket URL"') +WHERE fields LIKE '%"label":"WebSocket地址"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"资源ID"', '"label":"Resource ID"') +WHERE fields LIKE '%"label":"资源ID"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"默认音色"', '"label":"Default Voice"') +WHERE fields LIKE '%"label":"默认音色"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"断句检测时间"', '"label":"Sentence Silence Detection Time"') +WHERE fields LIKE '%"label":"断句检测时间"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"集群"', '"label":"Cluster"') +WHERE fields LIKE '%"label":"集群"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"热词文件名称"', '"label":"Hotword File Name"') +WHERE fields LIKE '%"label":"热词文件名称"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"替换词文件名称"', '"label":"Replacement File Name"') +WHERE fields LIKE '%"label":"替换词文件名称"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"区域"', '"label":"Region"') +WHERE fields LIKE '%"label":"区域"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"语言参数"', '"label":"Language Parameter"') +WHERE fields LIKE '%"label":"语言参数"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"音量"', '"label":"Volume"') +WHERE fields LIKE '%"label":"音量"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"语速"', '"label":"Speech Rate"') +WHERE fields LIKE '%"label":"语速"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"音调"', '"label":"Pitch"') +WHERE fields LIKE '%"label":"音调"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"检测阈值"', '"label":"Detection Threshold"') +WHERE fields LIKE '%"label":"检测阈值"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"模型目录"', '"label":"Model Directory"') +WHERE fields LIKE '%"label":"模型目录"%'; + +UPDATE ai_model_provider +SET fields = REPLACE(fields, '"label":"最小静音时长"', '"label":"Min Silence Duration"') +WHERE fields LIKE '%"label":"最小静音时长"%'; + +-- Update placeholder values in ai_model_config +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的api_key"', '"your_api_key"') +WHERE config_json LIKE '%"你的api_key"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的网关访问密钥"', '"your_gateway_access_key"') +WHERE config_json LIKE '%"你的网关访问密钥"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的app_id"', '"your_app_id"') +WHERE config_json LIKE '%"你的app_id"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的bot_id"', '"your_bot_id"') +WHERE config_json LIKE '%"你的bot_id"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的user_id"', '"your_user_id"') +WHERE config_json LIKE '%"你的user_id"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的personal_access_token"', '"your_personal_access_token"') +WHERE config_json LIKE '%"你的personal_access_token"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的home assistant api访问令牌"', '"your_home_assistant_api_token"') +WHERE config_json LIKE '%"你的home assistant api访问令牌"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的Secret ID"', '"your_secret_id"') +WHERE config_json LIKE '%"你的Secret ID"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的Secret Key"', '"your_secret_key"') +WHERE config_json LIKE '%"你的Secret Key"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的appkey"', '"your_appkey"') +WHERE config_json LIKE '%"你的appkey"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的access_key_id"', '"your_access_key_id"') +WHERE config_json LIKE '%"你的access_key_id"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的access_key_secret"', '"your_access_key_secret"') +WHERE config_json LIKE '%"你的access_key_secret"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的API Key"', '"your_api_key"') +WHERE config_json LIKE '%"你的API Key"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的应用ID"', '"your_app_id"') +WHERE config_json LIKE '%"你的应用ID"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的音色ID"', '"your_voice_id"') +WHERE config_json LIKE '%"你的音色ID"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的访问令牌"', '"your_access_token"') +WHERE config_json LIKE '%"你的访问令牌"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的资源ID"', '"your_resource_id"') +WHERE config_json LIKE '%"你的资源ID"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的默认音色"', '"your_default_voice"') +WHERE config_json LIKE '%"你的默认音色"%'; + +UPDATE ai_model_config +SET config_json = REPLACE(config_json, '"你的集群"', '"your_cluster"') +WHERE config_json LIKE '%"你的集群"%'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202501230004_translate_model_names.sql b/main/manager-api/src/main/resources/db/changelog/202501230004_translate_model_names.sql new file mode 100644 index 000000000..fa69ec577 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202501230004_translate_model_names.sql @@ -0,0 +1,188 @@ +-- Translate model provider names and descriptions from Chinese to English + +-- Update provider names +UPDATE ai_model_provider +SET name = 'SileroVAD Voice Activity Detection' +WHERE name = 'SileroVAD语音活动检测'; + +UPDATE ai_model_provider +SET name = 'FunASR Speech Recognition' +WHERE name = 'FunASR语音识别'; + +UPDATE ai_model_provider +SET name = 'SherpaASR Speech Recognition' +WHERE name = 'SherpaASR语音识别'; + +UPDATE ai_model_provider +SET name = 'Volcano Engine Speech Recognition' +WHERE name = '火山引擎语音识别'; + +UPDATE ai_model_provider +SET name = 'Tencent Speech Recognition' +WHERE name = '腾讯语音识别'; + +UPDATE ai_model_provider +SET name = 'Tencent Speech Synthesis' +WHERE name = '腾讯语音合成'; + +UPDATE ai_model_provider +SET name = 'Alibaba Cloud Speech Recognition' +WHERE name = '阿里云语音识别'; + +UPDATE ai_model_provider +SET name = 'Alibaba Cloud Speech Recognition (Streaming)' +WHERE name = '阿里云语音识别(流式)'; + +UPDATE ai_model_provider +SET name = 'Baidu Speech Recognition' +WHERE name = '百度语音识别'; + +UPDATE ai_model_provider +SET name = 'OpenAI Speech Recognition' +WHERE name = 'OpenAI语音识别'; + +UPDATE ai_model_provider +SET name = 'Volcano Engine Speech Recognition (Streaming)' +WHERE name = '火山引擎语音识别(流式)'; + +UPDATE ai_model_provider +SET name = 'Alibaba Bailian Interface' +WHERE name = '阿里百炼接口'; + +UPDATE ai_model_provider +SET name = 'Volcano Engine LLM' +WHERE name = '火山引擎LLM'; + +UPDATE ai_model_provider +SET name = 'Volcano Engine TTS' +WHERE name = '火山引擎TTS'; + +UPDATE ai_model_provider +SET name = 'Alibaba Cloud TTS' +WHERE name = '阿里云TTS'; + +UPDATE ai_model_provider +SET name = 'Volcano Dual-Stream Speech Synthesis' +WHERE name = '火山双流式语音合成'; + +UPDATE ai_model_provider +SET name = 'Linkerai Speech Synthesis' +WHERE name = 'Linkerai语音合成'; + +UPDATE ai_model_provider +SET name = 'Alibaba Cloud Speech Synthesis (Streaming)' +WHERE name = '阿里云语音合成(流式)'; + +UPDATE ai_model_provider +SET name = 'Index-TTS-vLLM Streaming Speech Synthesis' +WHERE name = 'Index-TTS-vLLM流式语音合成'; + +UPDATE ai_model_provider +SET name = 'Mem0AI Memory' +WHERE name = 'Mem0AI记忆'; + +UPDATE ai_model_provider +SET name = 'No Memory' +WHERE name = '无记忆'; + +UPDATE ai_model_provider +SET name = 'Local Short Memory' +WHERE name = '本地短记忆'; + +UPDATE ai_model_provider +SET name = 'No Intent Recognition' +WHERE name = '无意图识别'; + +UPDATE ai_model_provider +SET name = 'LLM Intent Recognition' +WHERE name = 'LLM意图识别'; + +UPDATE ai_model_provider +SET name = 'Function Call Intent Recognition' +WHERE name = '函数调用意图识别'; + +UPDATE ai_model_provider +SET name = 'FunASR Server Speech Recognition' +WHERE name = 'FunASR服务语音识别'; + +UPDATE ai_model_provider +SET name = 'MiniMax Speech Synthesis' +WHERE name = 'MiniMax语音合成'; + +UPDATE ai_model_provider +SET name = 'OpenAI Speech Synthesis' +WHERE name = 'OpenAI语音合成'; + +-- Update model config names +UPDATE ai_model_config +SET model_name = 'Zhipu AI' +WHERE model_name = '智谱AI'; + +UPDATE ai_model_config +SET model_name = 'Tongyi Qianwen' +WHERE model_name = '通义千问'; + +UPDATE ai_model_config +SET model_name = 'Tongyi Bailian' +WHERE model_name = '通义百炼'; + +UPDATE ai_model_config +SET model_name = 'Doubao Large Model' +WHERE model_name = '豆包大模型'; + +UPDATE ai_model_config +SET model_name = 'Google Gemini' +WHERE model_name = '谷歌Gemini'; + +UPDATE ai_model_config +SET model_name = 'Tencent Speech Recognition' +WHERE model_name = '腾讯语音识别'; + +UPDATE ai_model_config +SET model_name = 'Alibaba Cloud Speech Recognition' +WHERE model_name = '阿里云语音识别'; + +UPDATE ai_model_config +SET model_name = 'Baidu Speech Recognition' +WHERE model_name = '百度语音识别'; + +UPDATE ai_model_config +SET model_name = 'MiniMax Speech Synthesis' +WHERE model_name = 'MiniMax语音合成'; + +UPDATE ai_model_config +SET model_name = 'OpenAI Speech Synthesis' +WHERE model_name = 'OpenAI语音合成'; + +UPDATE ai_model_config +SET model_name = 'Volcano Dual-Stream Speech Synthesis' +WHERE model_name = '火山双流式语音合成'; + +UPDATE ai_model_config +SET model_name = 'Linkerai Speech Synthesis' +WHERE model_name = 'Linkerai语音合成'; + +UPDATE ai_model_config +SET model_name = 'Mem0AI Memory' +WHERE model_name = 'Mem0AI记忆'; + +UPDATE ai_model_config +SET model_name = 'Function Call Intent Recognition' +WHERE model_name = '函数调用意图识别'; + +UPDATE ai_model_config +SET model_name = 'Zhipu Visual AI' +WHERE model_name = '智谱视觉AI'; + +UPDATE ai_model_config +SET model_name = 'Qianwen Visual Model' +WHERE model_name = '千问视觉模型'; + +UPDATE ai_model_config +SET model_name = 'Volcano Edge Large Model Gateway' +WHERE model_name = '火山引擎边缘大模型网关'; + +-- Update TTS voice names +UPDATE ai_tts_voice +SET name = 'Alibaba Cloud Xiaoyun' +WHERE name = '阿里云小云'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202501230005_translate_sys_params.sql b/main/manager-api/src/main/resources/db/changelog/202501230005_translate_sys_params.sql new file mode 100644 index 000000000..99d0cfb9c --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202501230005_translate_sys_params.sql @@ -0,0 +1,22 @@ +-- Translate system parameter remarks from Chinese to English + +UPDATE sys_params +SET remark = 'Time to disconnect when no voice input (seconds)' +WHERE param_code = 'close_connection_no_voice_time'; + +UPDATE sys_params +SET remark = 'Wake word list for wake word recognition' +WHERE param_code = 'wakeup_words'; + +UPDATE sys_params +SET remark = 'Home Assistant API key' +WHERE param_code = 'plugins.home_assistant.api_key'; + +-- Update any Chinese wake words to English equivalents (optional, can be customized by user) +UPDATE sys_params +SET param_value = 'hello xiaozhi;hey xiaozhi;xiaozhi xiaozhi;hey assistant;hello assistant;wake up;listen to me;hey buddy' +WHERE param_code = 'wakeup_words' AND param_value LIKE '%你好小智%'; + +-- Translate column comments (if needed for documentation) +-- Note: These are database structure changes, not data changes +-- ALTER TABLE sys_params MODIFY COLUMN remark VARCHAR(255) COMMENT 'Parameter description'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202508291530_add_amazon_transcribe_streaming.sql b/main/manager-api/src/main/resources/db/changelog/202508291530_add_amazon_transcribe_streaming.sql new file mode 100644 index 000000000..417e38e7b --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202508291530_add_amazon_transcribe_streaming.sql @@ -0,0 +1,27 @@ +-- Amazon Transcribe Streaming ASR provider and model configuration + +-- Add Amazon Transcribe Streaming real-time ASR provider +DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_ASR_AmazonStreamASR'; +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) +VALUES ('SYSTEM_ASR_AmazonStreamASR', 'ASR', 'amazon_transcribe_realtime', 'Amazon Transcribe Streaming', +'[{"key":"aws_access_key_id","label":"AWS Access Key ID","type":"string"},{"key":"aws_secret_access_key","label":"AWS Secret Access Key","type":"string"},{"key":"aws_region","label":"AWS Region","type":"string"},{"key":"language_code","label":"Default Language Code","type":"string"},{"key":"enable_language_detection","label":"Enable Language Detection","type":"boolean"},{"key":"use_multiple_languages","label":"Support Multiple Languages","type":"boolean"},{"key":"romanized_output","label":"Romanized Output","type":"boolean"},{"key":"sample_rate","label":"Sample Rate","type":"number"},{"key":"media_encoding","label":"Media Encoding","type":"string"},{"key":"output_dir","label":"Output Directory","type":"string"},{"key":"timeout","label":"Timeout (seconds)","type":"number"}]', +4, 1, NOW(), 1, NOW()); + +-- Add Amazon Transcribe Streaming model configuration +DELETE FROM `ai_model_config` WHERE id = 'ASR_AmazonStreamASR'; +INSERT INTO `ai_model_config` VALUES ('ASR_AmazonStreamASR', 'ASR', 'AmazonStreamASR', 'Amazon Transcribe Streaming', 0, 1, +'{"type": "amazon_transcribe_realtime", "aws_access_key_id": "", "aws_secret_access_key": "", "aws_region": "us-east-1", "language_code": "en-IN", "enable_language_detection": true, "use_multiple_languages": true, "romanized_output": true, "sample_rate": 16000, "media_encoding": "pcm", "output_dir": "tmp/", "timeout": 30}', +'https://docs.aws.amazon.com/transcribe/latest/dg/streaming.html', +'Amazon Transcribe Streaming Configuration: +1. Real-time speech recognition with fast response (seconds) +2. Supports automatic language detection for all major Indian languages +3. Supported languages: Hindi, Bengali, Telugu, Tamil, Gujarati, Kannada, Malayalam, Marathi, Punjabi, English (India) +4. Can output romanized text for local languages +5. Supports speakers switching languages mid-conversation +6. Requires AWS credentials and appropriate IAM permissions +7. Real-time transcription is better suited for conversation scenarios than batch processing +Setup Steps: +1. Visit AWS Console: https://console.aws.amazon.com/ +2. Create IAM user and get access keys: https://console.aws.amazon.com/iam/home#/security_credentials +3. Add Amazon Transcribe permissions policy to the user', +4, NULL, NULL, NULL, NULL); \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202508291545_add_groq_llm.sql b/main/manager-api/src/main/resources/db/changelog/202508291545_add_groq_llm.sql new file mode 100644 index 000000000..f3d10bd0a --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202508291545_add_groq_llm.sql @@ -0,0 +1,34 @@ +-- Add GroqLLM Provider +DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_LLM_GroqLLM'; +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES +('SYSTEM_LLM_GroqLLM', 'LLM', 'groq', 'Groq LLM', '[{"key":"api_key","label":"API Key","type":"string"},{"key":"model_name","label":"Model Name","type":"string"},{"key":"base_url","label":"Base URL","type":"string"},{"key":"temperature","label":"Temperature","type":"number"},{"key":"max_tokens","label":"Max Tokens","type":"number"},{"key":"top_p","label":"Top P","type":"number"},{"key":"frequency_penalty","label":"Frequency Penalty","type":"number"},{"key":"timeout","label":"Timeout (seconds)","type":"number"},{"key":"max_retries","label":"Max Retries","type":"number"},{"key":"retry_delay","label":"Retry Delay (seconds)","type":"number"}]', 15, 1, NOW(), 1, NOW()); + +-- Add GroqLLM Model Configuration +DELETE FROM `ai_model_config` WHERE id = 'LLM_GroqLLM'; +INSERT INTO `ai_model_config` VALUES ('LLM_GroqLLM', 'LLM', 'GroqLLM', 'Groq LLM', 0, 1, '{"type": "openai", "api_key": "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", "model_name": "openai/gpt-oss-20b", "base_url": "https://api.groq.com/openai/v1", "temperature": 0.7, "max_tokens": 2048, "top_p": 1.0, "frequency_penalty": 0, "timeout": 15, "max_retries": 2, "retry_delay": 1}', NULL, NULL, 16, NULL, NULL, NULL, NULL); + +-- Update GroqLLM Configuration Documentation +UPDATE `ai_model_config` SET +`doc_link` = 'https://console.groq.com/', +`remark` = 'Groq LLM Configuration Guide: +1. Groq is an AI chip company focused on high-performance inference, providing fast LLM inference services +2. Supports various open-source large language models like Llama, Mixtral, etc. +3. Features ultra-low latency inference performance, suitable for real-time conversation scenarios +4. Uses OpenAI-compatible API interface for easy integration +5. Requires API key from Groq official website + +Configuration Parameters: +- api_key: API key obtained from Groq console +- model_name: Model name, e.g., llama3-8b-8192, mixtral-8x7b-32768, etc. +- base_url: Groq API endpoint, typically https://api.groq.com/openai/v1 +- temperature: Controls output randomness (0-2), lower values are more deterministic +- max_tokens: Maximum tokens to generate per request +- top_p: Nucleus sampling parameter controlling output diversity +- frequency_penalty: Frequency penalty to reduce repetitive content +- timeout: Request timeout in seconds, recommended 15s (Groq is fast) +- max_retries: Maximum retry attempts, recommended 2 +- retry_delay: Retry interval in seconds, recommended 1s + +Get API Key: https://console.groq.com/keys +Model List: https://console.groq.com/docs/models +' WHERE `id` = 'LLM_GroqLLM'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202508291600_add_play_story.sql b/main/manager-api/src/main/resources/db/changelog/202508291600_add_play_story.sql new file mode 100644 index 000000000..d8cde5d1c --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202508291600_add_play_story.sql @@ -0,0 +1,28 @@ +-- Add play_story plugin support +-- This adds play_story to all agents that currently have play_music + +-- 1. Add play_story plugin provider +DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_PLUGIN_STORY'; +INSERT INTO ai_model_provider (id, model_type, provider_code, name, fields, sort, creator, create_date, updater, update_date) +VALUES ('SYSTEM_PLUGIN_STORY', 'Plugin', 'play_story', 'Story Playback', JSON_ARRAY(), 25, 0, NOW(), 0, NOW()); + +-- 2. Add play_story to all agents that have play_music +INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info) +SELECT DISTINCT m.agent_id, 'SYSTEM_PLUGIN_STORY', '{}' +FROM ai_agent_plugin_mapping m +JOIN ai_model_provider p ON p.id = m.plugin_id +WHERE p.provider_code = 'play_music' + AND NOT EXISTS ( + SELECT 1 FROM ai_agent_plugin_mapping m2 + JOIN ai_model_provider p2 ON p2.id = m2.plugin_id + WHERE m2.agent_id = m.agent_id AND p2.provider_code = 'play_story' + ); + +-- 3. Add optional configuration fields for play_story +UPDATE `ai_model_provider` SET +fields = JSON_ARRAY( + JSON_OBJECT('key', 'story_dir', 'type', 'string', 'label', 'Story Directory', 'default', './stories'), + JSON_OBJECT('key', 'story_ext', 'type', 'array', 'label', 'Story File Extensions', 'default', '.mp3;.wav;.p3'), + JSON_OBJECT('key', 'refresh_time', 'type', 'number', 'label', 'Refresh Time (seconds)', 'default', '300') +) +WHERE id = 'SYSTEM_PLUGIN_STORY'; diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index da4312b32..244658d21 100755 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -304,6 +304,7 @@ databaseChangeLog: encoding: utf8 path: classpath:db/changelog/202508131557.sql - changeSet: + id: 202508231800 author: Claude changes: @@ -324,3 +325,46 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202508291500.sql + + id: 202501230002_translate_dict_names + author: cheeko + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202501230002_translate_dict_names.sql + - changeSet: + id: 202501230003_translate_provider_fields + author: cheeko + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202501230003_translate_provider_fields.sql + - changeSet: + id: 202501230005_translate_sys_params + author: cheeko + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202501230005_translate_sys_params.sql + - changeSet: + id: 202508291530 + author: claude + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202508291530_add_amazon_transcribe_streaming.sql + - changeSet: + id: 202508291545 + author: claude + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202508291545_add_groq_llm.sql + - changeSet: + id: 202508291600 + author: claude + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202508291600_add_play_story.sql + diff --git a/main/manager-mobile/src/pages/settings/index.vue b/main/manager-mobile/src/pages/settings/index.vue index d7d34bba8..5f48db2fc 100644 --- a/main/manager-mobile/src/pages/settings/index.vue +++ b/main/manager-mobile/src/pages/settings/index.vue @@ -369,8 +369,8 @@ onMounted(async () => { - - + + diff --git a/main/manager-web/.env b/main/manager-web/.env index 1b5f8138b..ebaae4032 100644 --- a/main/manager-web/.env +++ b/main/manager-web/.env @@ -1 +1 @@ -VUE_APP_TITLE=智控台 \ No newline at end of file +VUE_APP_TITLE=cheeko \ No newline at end of file diff --git a/main/manager-web/.env.development b/main/manager-web/.env.development index 0a1de3062..857f188e9 100644 --- a/main/manager-web/.env.development +++ b/main/manager-web/.env.development @@ -1 +1,2 @@ -VUE_APP_API_BASE_URL=/xiaozhi \ No newline at end of file +VUE_APP_API_BASE_URL=/toy +VUE_APP_TITLE=cheeko \ No newline at end of file diff --git a/main/manager-web/.env.production b/main/manager-web/.env.production index 351d791a6..6d16eb1a3 100644 --- a/main/manager-web/.env.production +++ b/main/manager-web/.env.production @@ -1,4 +1,5 @@ -VUE_APP_API_BASE_URL=/xiaozhi +VUE_APP_API_BASE_URL=/toy VUE_APP_PUBLIC_PATH=/ # 是否开启CDN -VUE_APP_USE_CDN=false \ No newline at end of file +VUE_APP_USE_CDN=false +VUE_APP_TITLE=cheeko \ No newline at end of file diff --git a/main/manager-web/public/favicon-16x16.png b/main/manager-web/public/favicon-16x16.png new file mode 100644 index 000000000..566b75134 Binary files /dev/null and b/main/manager-web/public/favicon-16x16.png differ diff --git a/main/manager-web/public/favicon.ico b/main/manager-web/public/favicon.ico index 5f285a58d..566b75134 100644 Binary files a/main/manager-web/public/favicon.ico and b/main/manager-web/public/favicon.ico differ diff --git a/main/manager-web/public/index.html b/main/manager-web/public/index.html index e3ae5a53c..f3268f730 100644 --- a/main/manager-web/public/index.html +++ b/main/manager-web/public/index.html @@ -5,7 +5,7 @@ - + <%= process.env.VUE_APP_TITLE %> diff --git a/main/manager-web/src/assets/favicon-16x16.png b/main/manager-web/src/assets/favicon-16x16.png new file mode 100644 index 000000000..566b75134 Binary files /dev/null and b/main/manager-web/src/assets/favicon-16x16.png differ diff --git a/main/manager-web/src/components/ChatHistoryDialog.vue b/main/manager-web/src/components/ChatHistoryDialog.vue index 80e0443b1..6afdf8796 100644 --- a/main/manager-web/src/components/ChatHistoryDialog.vue +++ b/main/manager-web/src/components/ChatHistoryDialog.vue @@ -1,5 +1,5 @@