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/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/main/manager-api/README.md b/main/manager-api/README.md index ce90156a3..901f6611d 100644 --- a/main/manager-api/README.md +++ b/main/manager-api/README.md @@ -1,4 +1,4 @@ -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 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/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 a4ad08632..619dd8324 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 @@ -150,7 +150,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), @@ -165,7 +165,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, @@ -183,7 +183,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) { @@ -201,7 +201,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) { @@ -211,7 +211,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); @@ -224,7 +224,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/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 0215cf7e6..b5145903a 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,7 +102,7 @@ public class LoginController { } @PostMapping("/register") - @Operation(summary = "注册") + @Operation(summary = "Register") public Result register(@RequestBody LoginDTO login) { if (!sysUserService.getAllowUserRegister()) { throw new RenException("当前不允许普通用户注册"); @@ -143,7 +143,7 @@ public class LoginController { } @GetMapping("/info") - @Operation(summary = "用户信息获取") + @Operation(summary = "Get user information") public Result info() { UserDetail user = SecurityUser.getUser(); Result result = new Result<>(); @@ -152,7 +152,7 @@ public class LoginController { } @PutMapping("/change-password") - @Operation(summary = "修改用户密码") + @Operation(summary = "Change user password") public Result changePassword(@RequestBody PasswordDTO passwordDTO) { // 判断非空 ValidatorUtils.validateEntity(passwordDTO); @@ -162,7 +162,7 @@ public class LoginController { } @PutMapping("/retrieve-password") - @Operation(summary = "找回密码") + @Operation(summary = "Retrieve password") public Result retrievePassword(@RequestBody RetrievePasswordDTO dto) { // 是否开启手机注册 Boolean isMobileRegister = sysParamsService @@ -195,7 +195,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-web/.env.production b/main/manager-web/.env.production index 351d791a6..b6fbd2e1d 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_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/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 @@