diff --git a/.gitignore b/.gitignore index 5709d1cf6..959faccdc 100644 --- a/.gitignore +++ b/.gitignore @@ -183,3 +183,7 @@ main/xiaozhi-server/mysql uploadfile *.json .vscode + +# Spring Boot configuration files (contain sensitive data) +main/manager-api/src/main/resources/application.yml +main/manager-api/src/main/resources/application-dev.yml diff --git a/FIRMWARE_UPDATE_SYSTEM_DOCUMENTATION.md b/FIRMWARE_UPDATE_SYSTEM_DOCUMENTATION.md deleted file mode 100644 index 8c5305c97..000000000 --- a/FIRMWARE_UPDATE_SYSTEM_DOCUMENTATION.md +++ /dev/null @@ -1,452 +0,0 @@ -# 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/add_mem0_system_param.py b/add_mem0_system_param.py deleted file mode 100644 index e07ba7c56..000000000 --- a/add_mem0_system_param.py +++ /dev/null @@ -1,205 +0,0 @@ -#!/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_railway.py b/add_mqtt_params_railway.py deleted file mode 100644 index 7a9862fd5..000000000 --- a/add_mqtt_params_railway.py +++ /dev/null @@ -1,197 +0,0 @@ -#!/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_agent_functions.py b/check_agent_functions.py deleted file mode 100644 index 30506105d..000000000 --- a/check_agent_functions.py +++ /dev/null @@ -1,360 +0,0 @@ -#!/usr/bin/env python3 -""" -Script to check agent templates and functions structure, and fix Story Playback function placement -""" - -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_all_tables(connection): - """Get all tables in the database""" - cursor = connection.cursor() - try: - cursor.execute("SHOW TABLES") - tables = cursor.fetchall() - - print(f"\nAll tables in the database:") - for table in tables: - print(f" - {table[0]}") - - return [table[0] for table in tables] - - except Error as e: - print(f"Error getting tables: {e}") - return None - finally: - cursor.close() - -def search_agent_related_tables(connection): - """Search for agent-related tables""" - cursor = connection.cursor() - try: - cursor.execute("SHOW TABLES LIKE '%agent%'") - agent_tables = cursor.fetchall() - - cursor.execute("SHOW TABLES LIKE '%template%'") - template_tables = cursor.fetchall() - - cursor.execute("SHOW TABLES LIKE '%function%'") - function_tables = cursor.fetchall() - - print(f"\nAgent-related tables:") - for table in agent_tables: - print(f" - {table[0]}") - - print(f"\nTemplate-related tables:") - for table in template_tables: - print(f" - {table[0]}") - - print(f"\nFunction-related tables:") - for table in function_tables: - print(f" - {table[0]}") - - return agent_tables + template_tables + function_tables - - except Error as e: - print(f"Error searching agent tables: {e}") - return None - finally: - cursor.close() - -def examine_table_structure(connection, table_name): - """Get detailed structure of a table""" - cursor = connection.cursor() - try: - print(f"\n{'='*60}") - print(f"Structure of table '{table_name}':") - print('='*60) - - cursor.execute(f"DESCRIBE {table_name}") - columns = cursor.fetchall() - - headers = ["Field", "Type", "Null", "Key", "Default", "Extra"] - print(tabulate(columns, headers=headers, tablefmt="grid")) - - # Get sample data - cursor.execute(f"SELECT * FROM {table_name} LIMIT 5") - sample_data = cursor.fetchall() - - if sample_data: - print(f"\nSample data from '{table_name}':") - column_names = [desc[0] for desc in cursor.description] - print(tabulate(sample_data, headers=column_names, tablefmt="grid")) - - return columns - - except Error as e: - print(f"Error examining table {table_name}: {e}") - return None - finally: - cursor.close() - -def search_story_playback(connection): - """Search for Story Playback function references""" - cursor = connection.cursor() - try: - print(f"\n{'='*60}") - print("Searching for 'Story Playback' references in the database...") - print('='*60) - - # Get all tables - cursor.execute("SHOW TABLES") - tables = [table[0] for table in cursor.fetchall()] - - found_references = [] - - for table in tables: - try: - # Get column names for this table - cursor.execute(f"DESCRIBE {table}") - columns = cursor.fetchall() - text_columns = [col[0] for col in columns if 'text' in col[1].lower() or 'varchar' in col[1].lower() or 'json' in col[1].lower()] - - if text_columns: - # Search in each text column - for column in text_columns: - search_query = f"SELECT * FROM {table} WHERE {column} LIKE '%Story Playback%' OR {column} LIKE '%story_playback%' OR {column} LIKE '%storyplayback%'" - cursor.execute(search_query) - results = cursor.fetchall() - - if results: - found_references.append({ - 'table': table, - 'column': column, - 'results': results - }) - print(f"\nFound 'Story Playback' in {table}.{column}:") - column_names = [desc[0] for desc in cursor.description] - print(tabulate(results, headers=column_names, tablefmt="grid")) - - except Error as e: - # Skip tables that might cause errors - continue - - return found_references - - except Error as e: - print(f"Error searching for Story Playback: {e}") - return None - finally: - cursor.close() - -def check_agent_templates(connection): - """Check agent templates and their configurations""" - cursor = connection.cursor() - try: - print(f"\n{'='*60}") - print("Checking agent templates...") - print('='*60) - - # Look for agent template related tables - possible_tables = ['agent_template', 'agent_templates', 'toy', 'agent_config', 'agent_configuration'] - - for table_name in possible_tables: - try: - cursor.execute(f"SELECT * FROM {table_name} LIMIT 3") - results = cursor.fetchall() - - if results: - print(f"\nFound data in table '{table_name}':") - column_names = [desc[0] for desc in cursor.description] - print(tabulate(results, headers=column_names, tablefmt="grid")) - - # Check if any columns contain JSON that might have function configurations - for i, row in enumerate(results[:1]): # Check first row only - for j, cell in enumerate(row): - if isinstance(cell, str) and (cell.strip().startswith('{') or cell.strip().startswith('[')): - try: - json_data = json.loads(cell) - print(f"\nJSON data in {table_name}.{column_names[j]} (row {i+1}):") - print(json.dumps(json_data, indent=2)) - except: - pass - - except Error: - continue - - except Error as e: - print(f"Error checking agent templates: {e}") - finally: - cursor.close() - -def fix_story_playback_function(connection): - """Fix Story Playback function to be in Selected Functions for all agent templates""" - cursor = connection.cursor() - try: - print(f"\n{'='*60}") - print("Attempting to fix Story Playback function placement...") - print('='*60) - - # First, let's find where the functions are stored - # Look for common table names that might store agent configurations - possible_tables = ['toy', 'agent_template', 'agent_config'] - - for table_name in possible_tables: - try: - # Get all records from the table - cursor.execute(f"SELECT * FROM {table_name}") - results = cursor.fetchall() - column_names = [desc[0] for desc in cursor.description] - - if results: - print(f"\nChecking table '{table_name}' for function configurations...") - - for i, row in enumerate(results): - row_dict = dict(zip(column_names, row)) - - # Look for JSON fields that might contain function configurations - for col_name, cell_value in row_dict.items(): - if isinstance(cell_value, str) and cell_value.strip().startswith('{'): - try: - json_data = json.loads(cell_value) - - # Look for function-related keys - if any(key in json_data for key in ['selected_functions', 'unselected_functions', 'functions', 'selectedFunctions', 'unselectedFunctions']): - print(f"\nFound function configuration in {table_name}, row {i+1}, column '{col_name}':") - print(f"Record ID/identifier: {row_dict.get('id', row_dict.get('template_id', 'Unknown'))}") - - # Check if Story Playback is in unselected functions - needs_update = False - updated_data = json_data.copy() - - # Handle different possible key names - unselected_key = None - selected_key = None - - for key in ['unselected_functions', 'unselectedFunctions']: - if key in json_data: - unselected_key = key - break - - for key in ['selected_functions', 'selectedFunctions']: - if key in json_data: - selected_key = key - break - - if unselected_key and selected_key: - unselected_functions = json_data.get(unselected_key, []) - selected_functions = json_data.get(selected_key, []) - - # Look for Story Playback in unselected functions - story_playback_item = None - for func in unselected_functions: - if isinstance(func, dict) and 'Story Playback' in str(func): - story_playback_item = func - break - elif isinstance(func, str) and 'Story Playback' in func: - story_playback_item = func - break - - if story_playback_item: - print(f"Found Story Playback in unselected functions: {story_playback_item}") - - # Move it to selected functions - updated_data[unselected_key] = [f for f in unselected_functions if f != story_playback_item] - updated_data[selected_key] = selected_functions + [story_playback_item] - - # Update the database - update_query = f"UPDATE {table_name} SET {col_name} = %s WHERE " - if 'id' in row_dict: - update_query += "id = %s" - update_params = [json.dumps(updated_data), row_dict['id']] - else: - # Use the first column as identifier - first_col = column_names[0] - update_query += f"{first_col} = %s" - update_params = [json.dumps(updated_data), row_dict[first_col]] - - print(f"Executing update query: {update_query}") - print(f"Parameters: {update_params[1]} (ID), [JSON data]") - - cursor.execute(update_query, update_params) - connection.commit() - - print(f"✓ Successfully moved Story Playback to selected functions for record {row_dict.get('id', row_dict[column_names[0]])}") - needs_update = True - else: - print(f"Story Playback not found in unselected functions for this record") - - # Print the current function configuration - print(f"Current function configuration:") - print(json.dumps(json_data, indent=2)) - - except json.JSONDecodeError: - continue - - except Error as e: - print(f"Error processing table {table_name}: {e}") - continue - - print(f"\nFunction placement fix completed!") - - except Error as e: - print(f"Error fixing Story Playback function: {e}") - finally: - cursor.close() - -def main(): - print("Checking xiaozhi database for agent templates and Story Playback function") - print("=" * 80) - - # Connect to database - connection = connect_to_database() - if not connection: - return - - try: - # Get all tables - print("\n" + "="*60) - tables = get_all_tables(connection) - - # Search for agent-related tables - print("\n" + "="*60) - agent_tables = search_agent_related_tables(connection) - - # Examine key tables - key_tables = ['toy'] # Start with 'toy' as it's likely the main agent config table - for table in key_tables: - if table in tables: - examine_table_structure(connection, table) - - # Search for Story Playback references - search_story_playback(connection) - - # Check agent templates - check_agent_templates(connection) - - # Fix Story Playback function placement - fix_story_playback_function(connection) - - 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_database_structure.py b/check_database_structure.py deleted file mode 100644 index d0035451a..000000000 --- a/check_database_structure.py +++ /dev/null @@ -1,186 +0,0 @@ -#!/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_story_function_mapping.py b/check_story_function_mapping.py deleted file mode 100644 index f3b634ca7..000000000 --- a/check_story_function_mapping.py +++ /dev/null @@ -1,379 +0,0 @@ -#!/usr/bin/env python3 -""" -Comprehensive script to check Story Playback function mapping in both database and local config -""" - -import mysql.connector -from mysql.connector import Error -import json -import yaml -import os - -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 check_story_plugin_in_database(connection): - """Check if Story Playback plugin exists in database""" - cursor = connection.cursor() - try: - print(f"\n{'='*60}") - print("1. Checking Story Playback Plugin in Database") - print('='*60) - - # Check if SYSTEM_PLUGIN_STORY exists in ai_model_provider - cursor.execute(""" - SELECT id, model_type, provider_code, name, fields - FROM ai_model_provider - WHERE id = 'SYSTEM_PLUGIN_STORY' OR name LIKE '%Story%' - """) - - story_plugins = cursor.fetchall() - - if story_plugins: - print(f"Found Story Playback plugins:") - for plugin in story_plugins: - plugin_id, model_type, provider_code, name, fields = plugin - print(f" ID: {plugin_id}") - print(f" Type: {model_type}") - print(f" Provider Code: {provider_code}") - print(f" Name: {name}") - if fields: - try: - fields_json = json.loads(fields) - print(f" Fields: {json.dumps(fields_json, indent=4)}") - except: - print(f" Fields: {fields}") - print() - else: - print("No Story Playback plugin found in database!") - - return story_plugins - - except Error as e: - print(f"Error checking story plugin: {e}") - return None - finally: - cursor.close() - -def check_intent_functions_in_database(connection): - """Check Intent function call configurations in database""" - cursor = connection.cursor() - try: - print(f"\n{'='*60}") - print("2. Checking Intent Function Call Configurations") - print('='*60) - - # Check if there's an Intent function call configuration - cursor.execute(""" - SELECT id, model_type, provider_code, name, fields - FROM ai_model_provider - WHERE model_type = 'Intent' AND provider_code = 'function_call' - """) - - intent_configs = cursor.fetchall() - - if intent_configs: - print(f"Found Intent function call configurations:") - for config in intent_configs: - config_id, model_type, provider_code, name, fields = config - print(f" ID: {config_id}") - print(f" Name: {name}") - if fields: - try: - fields_json = json.loads(fields) - print(f" Fields: {json.dumps(fields_json, indent=2)}") - - # Look for functions list - for field in fields_json: - if field.get('key') == 'functions' and 'default' in field: - functions = field['default'] - print(f" Available functions: {functions}") - if 'play_story' in str(functions).lower(): - print(" [✓] play_story found in functions!") - else: - print(" [✗] play_story NOT found in functions!") - except Exception as e: - print(f" Fields (raw): {fields}") - print(f" Error parsing fields: {e}") - print() - else: - print("No Intent function call configuration found!") - - return intent_configs - - except Error as e: - print(f"Error checking intent functions: {e}") - return None - finally: - cursor.close() - -def check_agent_plugin_mappings(connection): - """Check which agents have Story Playback mapped""" - cursor = connection.cursor() - try: - print(f"\n{'='*60}") - print("3. Checking Agent-Plugin Mappings for Story Playback") - print('='*60) - - # Get all agents and check their Story Playback mapping - cursor.execute(""" - SELECT - a.id as agent_id, - a.agent_name, - apm.plugin_id, - apm.param_info - FROM ai_agent a - LEFT JOIN ai_agent_plugin_mapping apm - ON a.id = apm.agent_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY' - ORDER BY a.agent_name - """) - - mappings = cursor.fetchall() - - total_agents = len(set([m[0] for m in mappings if m[0] is not None])) - agents_with_story = len([m for m in mappings if m[2] == 'SYSTEM_PLUGIN_STORY']) - - print(f"Agent Story Playback Mapping Status:") - print(f"Total agents: {total_agents}") - print(f"Agents with Story Playback: {agents_with_story}") - print() - - for mapping in mappings: - agent_id, agent_name, plugin_id, param_info = mapping - if plugin_id == 'SYSTEM_PLUGIN_STORY': - print(f"[✓] {agent_name} (ID: {agent_id}) - HAS Story Playback") - if param_info: - try: - params = json.loads(param_info) - print(f" Parameters: {json.dumps(params, indent=6)}") - except: - print(f" Parameters: {param_info}") - else: - print(f"[✗] {agent_name} (ID: {agent_id}) - MISSING Story Playback") - - return mappings - - except Error as e: - print(f"Error checking agent mappings: {e}") - return None - finally: - cursor.close() - -def check_local_config_file(): - """Check the local config file for play_story function""" - try: - print(f"\n{'='*60}") - print("4. Checking Local Config File") - print('='*60) - - config_path = "D:/cheekofinal/xiaozhi-esp32-server/main/xiaozhi-server/data/.config.yaml" - - if not os.path.exists(config_path): - print(f"Config file not found: {config_path}") - return None - - with open(config_path, 'r', encoding='utf-8') as file: - config_content = file.read() - - print(f"Config file location: {config_path}") - print(f"File size: {len(config_content)} characters") - - # Look for Intent section - if 'Intent:' in config_content: - print(f"[✓] Intent section found in config") - - # Look for function_call - if 'function_call:' in config_content: - print(f"[✓] function_call section found") - - # Look for functions list - if 'functions:' in config_content: - print(f"[✓] functions list found") - - # Extract functions section - lines = config_content.split('\n') - in_functions = False - functions = [] - - for line in lines: - if 'functions:' in line and 'function_call:' in config_content[max(0, config_content.find(line)-200):config_content.find(line)]: - in_functions = True - continue - elif in_functions: - if line.strip().startswith('- '): - func_name = line.strip()[2:].strip() - functions.append(func_name) - elif line.strip() and not line.startswith(' ') and not line.startswith('#'): - break - - print(f"Functions found in config:") - for func in functions: - if 'story' in func.lower(): - print(f" [✓] {func}") - else: - print(f" - {func}") - - if 'play_story' in functions: - print(f"[✓] play_story is configured in local config!") - else: - print(f"[✗] play_story is NOT configured in local config!") - - return functions - else: - print(f"[✗] functions list not found in function_call section") - else: - print(f"[✗] function_call section not found in Intent") - else: - print(f"[✗] Intent section not found in config") - - return None - - except Exception as e: - print(f"Error checking local config: {e}") - return None - -def fix_missing_story_function_in_database(connection): - """Fix missing Story Playback function in Intent configuration if needed""" - cursor = connection.cursor() - try: - print(f"\n{'='*60}") - print("5. Fixing Intent Function Configuration if Needed") - print('='*60) - - # Get the Intent function call configuration - cursor.execute(""" - SELECT id, fields - FROM ai_model_provider - WHERE model_type = 'Intent' AND provider_code = 'function_call' - LIMIT 1 - """) - - result = cursor.fetchone() - - if result: - config_id, fields = result - print(f"Found Intent config ID: {config_id}") - - try: - fields_json = json.loads(fields) - - # Find the functions field - functions_field = None - for i, field in enumerate(fields_json): - if field.get('key') == 'functions': - functions_field = field - field_index = i - break - - if functions_field: - current_functions = functions_field.get('default', '') - print(f"Current functions: {current_functions}") - - # Check if play_story is already there - if 'play_story' not in current_functions.lower(): - # Add play_story to the functions - if current_functions: - # Parse existing functions (assuming they're in a string format) - if current_functions.endswith(';'): - updated_functions = current_functions + 'play_story' - else: - updated_functions = current_functions + ';play_story' - else: - updated_functions = 'play_story' - - # Update the field - fields_json[field_index]['default'] = updated_functions - - # Update database - cursor.execute(""" - UPDATE ai_model_provider - SET fields = %s - WHERE id = %s - """, (json.dumps(fields_json), config_id)) - - connection.commit() - - print(f"[✓] Updated Intent functions to: {updated_functions}") - print(f"[✓] play_story added to Intent configuration!") - else: - print(f"[✓] play_story already exists in Intent configuration") - else: - print(f"[✗] functions field not found in Intent configuration") - - except json.JSONDecodeError as e: - print(f"[✗] Error parsing Intent configuration JSON: {e}") - - else: - print(f"[✗] No Intent function call configuration found in database") - - except Error as e: - print(f"Error fixing Intent configuration: {e}") - connection.rollback() - finally: - cursor.close() - -def main(): - print("Comprehensive Story Playback Function Mapping Check") - print("=" * 80) - - # Check database - connection = connect_to_database() - if connection: - try: - # Check story plugin exists - story_plugins = check_story_plugin_in_database(connection) - - # Check intent function configurations - intent_configs = check_intent_functions_in_database(connection) - - # Check agent mappings - agent_mappings = check_agent_plugin_mappings(connection) - - # Fix Intent configuration if needed - fix_missing_story_function_in_database(connection) - - finally: - connection.close() - - # Check local config - local_functions = check_local_config_file() - - # Summary - print(f"\n{'='*60}") - print("SUMMARY") - print('='*60) - - if story_plugins: - print("[✓] Story Playback plugin exists in database") - else: - print("[✗] Story Playback plugin MISSING from database") - - if local_functions and 'play_story' in local_functions: - print("[✓] play_story configured in local config") - else: - print("[✗] play_story MISSING from local config") - - print(f"\nThe script has checked both database and local configurations.") - print(f"If any issues were found, they should now be fixed!") - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/check_sys_params_structure.py b/check_sys_params_structure.py deleted file mode 100644 index 6a777bf47..000000000 --- a/check_sys_params_structure.py +++ /dev/null @@ -1,271 +0,0 @@ -#!/usr/bin/env python3 -""" -Check sys_params table structure and add default plugins configuration -""" - -import mysql.connector -from mysql.connector import Error -import json - -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("Connected to Railway MySQL database") - return connection - - except Error as e: - print(f"Database connection error: {e}") - return None - -def check_sys_params_structure(connection): - """Check the structure of sys_params table""" - cursor = connection.cursor() - try: - print("\n1. Checking sys_params table structure...") - print("=" * 50) - - cursor.execute("DESCRIBE sys_params") - columns = cursor.fetchall() - - print("sys_params columns:") - for col in columns: - print(f" {col[0]} - {col[1]}") - - return [col[0] for col in columns] - - except Error as e: - print(f"Error checking sys_params: {e}") - return [] - finally: - cursor.close() - -def check_existing_params(connection, column_names): - """Check existing system parameters""" - cursor = connection.cursor() - try: - print("\n2. Checking existing system parameters...") - print("=" * 50) - - # Build query based on actual column names - key_col = None - value_col = None - - for col in column_names: - if 'key' in col.lower(): - key_col = col - elif 'value' in col.lower(): - value_col = col - - if not key_col or not value_col: - print("Could not identify key/value columns") - return None, None - - print(f"Using columns: {key_col} (key), {value_col} (value)") - - # Get plugin-related parameters - query = f"SELECT {key_col}, {value_col} FROM sys_params WHERE {key_col} LIKE '%plugin%' OR {key_col} LIKE '%function%' OR {key_col} LIKE '%default%'" - cursor.execute(query) - - params = cursor.fetchall() - - if params: - print("Found related parameters:") - for key, value in params: - print(f" {key}: {value[:100] if value else 'NULL'}...") - else: - print("No plugin-related parameters found") - - return key_col, value_col - - except Error as e: - print(f"Error checking parameters: {e}") - return None, None - finally: - cursor.close() - -def add_default_plugins_parameter(connection, key_col, value_col, column_names): - """Add or update default plugins parameter""" - cursor = connection.cursor() - try: - print("\n3. Adding/Updating default plugins parameter...") - print("=" * 50) - - # Check if default_agent_plugins exists - query = f"SELECT {value_col} FROM sys_params WHERE {key_col} = 'default_agent_plugins'" - cursor.execute(query) - - existing = cursor.fetchone() - - default_plugins = { - "plugins": [ - "SYSTEM_PLUGIN_MUSIC", - "SYSTEM_PLUGIN_STORY", - "SYSTEM_PLUGIN_WEATHER", - "SYSTEM_PLUGIN_NEWS_NEWSNOW" - ], - "functions": [ - "play_music", - "play_story", - "get_weather", - "get_news_from_newsnow", - "get_indian_news_api", - "get_lunar" - ] - } - - if existing: - print("default_agent_plugins already exists, updating...") - - update_query = f"UPDATE sys_params SET {value_col} = %s WHERE {key_col} = %s" - cursor.execute(update_query, (json.dumps(default_plugins), 'default_agent_plugins')) - - print("Updated default_agent_plugins") - else: - print("Creating new default_agent_plugins parameter...") - - # Build insert query based on available columns - insert_cols = [key_col, value_col] - insert_values = ['default_agent_plugins', json.dumps(default_plugins)] - - # Add other columns if they exist - if 'type' in column_names: - insert_cols.append('type') - insert_values.append(1) - elif 'param_type' in column_names: - insert_cols.append('param_type') - insert_values.append(1) - - if 'remark' in column_names: - insert_cols.append('remark') - insert_values.append('Default plugins and functions for new agents') - elif 'description' in column_names: - insert_cols.append('description') - insert_values.append('Default plugins and functions for new agents') - - # Add timestamp columns if they exist - for col in ['create_date', 'created_at', 'create_time']: - if col in column_names: - insert_cols.append(col) - insert_values.append('NOW()') - break - - # Build query - placeholders = ['%s'] * len(insert_values) - # Replace NOW() placeholders - for i, val in enumerate(insert_values): - if val == 'NOW()': - placeholders[i] = 'NOW()' - insert_values[i] = None - - insert_query = f"INSERT INTO sys_params ({', '.join(insert_cols)}) VALUES ({', '.join(placeholders)})" - insert_query = insert_query.replace('%s', '%s').replace("'NOW()'", "NOW()") - - # Filter out None values for NOW() - insert_values = [v for v in insert_values if v is not None] - - print(f"Insert query: {insert_query}") - cursor.execute(insert_query, insert_values) - - print("Created default_agent_plugins parameter") - - connection.commit() - return True - - except Error as e: - print(f"Error adding default plugins: {e}") - connection.rollback() - return False - finally: - cursor.close() - -def verify_trigger(connection): - """Verify the trigger exists""" - cursor = connection.cursor() - try: - print("\n4. Verifying trigger...") - print("=" * 50) - - cursor.execute(""" - SELECT TRIGGER_NAME, EVENT_MANIPULATION, EVENT_OBJECT_TABLE - FROM information_schema.TRIGGERS - WHERE TRIGGER_SCHEMA = 'railway' - AND TRIGGER_NAME = 'add_story_to_new_agent' - """) - - trigger = cursor.fetchone() - - if trigger: - print(f"Trigger exists: {trigger[0]}") - print(f" Event: {trigger[1]} on {trigger[2]}") - print("New agents will automatically get Story Playback!") - else: - print("Trigger not found (may have failed to create)") - - return trigger is not None - - except Error as e: - print(f"Error verifying trigger: {e}") - return False - finally: - cursor.close() - -def main(): - print("Configuring Default Plugins for New Agents") - print("=" * 70) - - connection = connect_to_database() - if not connection: - return - - try: - # 1. Check sys_params structure - column_names = check_sys_params_structure(connection) - - if column_names: - # 2. Check existing parameters - key_col, value_col = check_existing_params(connection, column_names) - - if key_col and value_col: - # 3. Add/update default plugins - add_default_plugins_parameter(connection, key_col, value_col, column_names) - - # 4. Verify trigger - trigger_exists = verify_trigger(connection) - - # Summary - print(f"\n{'='*70}") - print("FINAL STATUS") - print('='*70) - - print("Configuration complete!") - - if trigger_exists: - print("[OK] Database trigger active - new agents will get Story Playback automatically") - else: - print("[INFO] No trigger - agent creation code should add default plugins") - - print("\nDefault plugins configured:") - print(" - SYSTEM_PLUGIN_MUSIC") - print(" - SYSTEM_PLUGIN_STORY") - print(" - SYSTEM_PLUGIN_WEATHER") - print(" - SYSTEM_PLUGIN_NEWS_NEWSNOW") - - print("\nAll new agents will now have Story Playback by default!") - - finally: - connection.close() - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/check_system_params.py b/check_system_params.py deleted file mode 100644 index db6479972..000000000 --- a/check_system_params.py +++ /dev/null @@ -1,178 +0,0 @@ -#!/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/final_fix_story_playback.py b/final_fix_story_playback.py deleted file mode 100644 index d1f9030c9..000000000 --- a/final_fix_story_playback.py +++ /dev/null @@ -1,197 +0,0 @@ -#!/usr/bin/env python3 -""" -Final script to fix Story Playback function placement -""" - -import mysql.connector -from mysql.connector import Error -import json - -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 check_agents_and_templates(connection): - """Check both agent templates and actual agents""" - cursor = connection.cursor() - try: - print("\n1. Checking agent templates...") - cursor.execute("SELECT id, agent_name FROM ai_agent_template") - templates = cursor.fetchall() - - print(f"Found {len(templates)} agent templates:") - for template in templates: - print(f" Template ID: {template[0]}, Name: {template[1]}") - - print("\n2. Checking actual agents...") - cursor.execute("SELECT id, agent_name FROM ai_agent") - agents = cursor.fetchall() - - print(f"Found {len(agents)} agents:") - for agent in agents: - print(f" Agent ID: {agent[0]}, Name: {agent[1]}") - - print("\n3. Checking current Story Playback mappings...") - cursor.execute(""" - SELECT agent_id, param_info FROM ai_agent_plugin_mapping - WHERE plugin_id = 'SYSTEM_PLUGIN_STORY' - """) - story_mappings = cursor.fetchall() - - print(f"Found {len(story_mappings)} existing Story Playback mappings:") - for mapping in story_mappings: - print(f" Agent ID: {mapping[0]}") - - return agents, templates, story_mappings - - except Error as e: - print(f"Error checking agents and templates: {e}") - return [], [], [] - finally: - cursor.close() - -def add_missing_story_playback_mappings(connection, agents, story_mappings): - """Add Story Playback to agents that don't have it""" - cursor = connection.cursor() - try: - # Get list of agent IDs that already have Story Playback - existing_story_agent_ids = [mapping[0] for mapping in story_mappings] - - # Default parameters for Story Playback plugin - param_info = { - "story_dir": "./stories", - "story_ext": ".mp3;.wav;.m4a", - "refresh_time": "300" - } - - updates_made = 0 - - print(f"\n4. Adding Story Playback to agents without it...") - - for agent_id, agent_name in agents: - if agent_id not in existing_story_agent_ids: - print(f"Adding Story Playback to: {agent_name} (ID: {agent_id})") - - cursor.execute(""" - INSERT INTO ai_agent_plugin_mapping - (agent_id, plugin_id, param_info) - VALUES (%s, %s, %s) - """, (agent_id, "SYSTEM_PLUGIN_STORY", json.dumps(param_info))) - - updates_made += 1 - print(f" Added successfully") - else: - print(f"Already has Story Playback: {agent_name} (ID: {agent_id})") - - if updates_made > 0: - connection.commit() - print(f"\nCommitted {updates_made} new Story Playback mappings to database") - else: - print(f"\nNo updates needed - all agents already have Story Playback") - - return updates_made - - except Error as e: - print(f"Error adding Story Playback mappings: {e}") - connection.rollback() - return 0 - finally: - cursor.close() - -def verify_final_state(connection): - """Verify all agents now have Story Playback""" - cursor = connection.cursor() - try: - print(f"\n5. Final verification...") - - cursor.execute(""" - SELECT - a.id, - a.agent_name, - CASE WHEN apm.plugin_id IS NOT NULL THEN 'YES' ELSE 'NO' END as has_story_playback - FROM ai_agent a - LEFT JOIN ai_agent_plugin_mapping apm - ON a.id = apm.agent_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY' - ORDER BY a.agent_name - """) - - results = cursor.fetchall() - - total_agents = len(results) - with_story_playback = sum(1 for result in results if result[2] == 'YES') - - print(f"\nFinal Story Playback status:") - for result in results: - agent_id, agent_name, has_playback = result - status_symbol = "[YES]" if has_playback == 'YES' else "[NO] " - print(f" {status_symbol} {agent_name}") - - print(f"\nSUMMARY:") - print(f"Total agents: {total_agents}") - print(f"With Story Playback: {with_story_playback}") - - if with_story_playback == total_agents: - print("SUCCESS: All agents now have Story Playback function!") - else: - print(f"WARNING: {total_agents - with_story_playback} agents still missing Story Playback") - - return with_story_playback == total_agents - - except Error as e: - print(f"Error verifying final state: {e}") - return False - finally: - cursor.close() - -def main(): - print("Fixing Story Playback function for all agents") - print("=" * 50) - - connection = connect_to_database() - if not connection: - return - - try: - # Check current state - agents, templates, story_mappings = check_agents_and_templates(connection) - - if not agents: - print("ERROR: No agents found in database!") - return - - # Add Story Playback to agents that don't have it - updates_made = add_missing_story_playback_mappings(connection, agents, story_mappings) - - # Verify the final state - success = verify_final_state(connection) - - if success: - print("\nMission accomplished! All agents now have access to Story Playback function.") - else: - print("\nSome issues remain. Please check the output above.") - - finally: - if connection.is_connected(): - connection.close() - print(f"\nDatabase connection closed") - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/fix_default_agent_template.py b/fix_default_agent_template.py deleted file mode 100644 index f05ef544d..000000000 --- a/fix_default_agent_template.py +++ /dev/null @@ -1,366 +0,0 @@ -#!/usr/bin/env python3 -""" -Script to ensure play_story is included in default agent template -""" - -import mysql.connector -from mysql.connector import Error -import json - -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("Connected to Railway MySQL database") - return connection - - except Error as e: - print(f"Database connection error: {e}") - return None - -def check_agent_templates(connection): - """Check all agent templates and their plugin configurations""" - cursor = connection.cursor() - try: - print("\n1. Checking Agent Templates...") - print("=" * 50) - - # Get all agent templates - cursor.execute(""" - SELECT id, agent_name, agent_code - FROM ai_agent_template - ORDER BY sort, id - """) - - templates = cursor.fetchall() - - print(f"Found {len(templates)} agent templates:") - for template_id, agent_name, agent_code in templates: - print(f" - {agent_name or agent_code} (ID: {template_id})") - - return templates - - except Error as e: - print(f"Error checking templates: {e}") - return [] - finally: - cursor.close() - -def check_template_plugin_mappings(connection): - """Check if templates have default plugin mappings""" - cursor = connection.cursor() - try: - print("\n2. Checking Template Plugin Mappings...") - print("=" * 50) - - # Check if there's a template plugin mapping table - cursor.execute(""" - SELECT TABLE_NAME - FROM information_schema.TABLES - WHERE TABLE_SCHEMA = 'railway' - AND TABLE_NAME LIKE '%template%plugin%' - """) - - mapping_tables = cursor.fetchall() - - if mapping_tables: - print("Found template plugin mapping tables:") - for table in mapping_tables: - print(f" - {table[0]}") - else: - print("No template plugin mapping tables found") - print("Templates likely don't have default plugin configurations") - print("Plugins are probably added when agents are created from templates") - - return mapping_tables - - except Error as e: - print(f"Error checking template mappings: {e}") - return [] - finally: - cursor.close() - -def add_story_to_all_templates(connection): - """Ensure all templates will include play_story for new agents""" - cursor = connection.cursor() - try: - print("\n3. Adding Story Playback to All Templates...") - print("=" * 50) - - # Get all templates - cursor.execute("SELECT id, agent_name FROM ai_agent_template") - templates = cursor.fetchall() - - # For each template, we need to ensure Story Playback is included - # Since templates don't have direct plugin mappings, we need to check - # if there's a default plugin list or configuration - - # Check if there's a system parameter for default plugins - cursor.execute(""" - SELECT param_key, param_value - FROM sys_params - WHERE param_key LIKE '%plugin%' OR param_key LIKE '%function%' - """) - - system_params = cursor.fetchall() - - if system_params: - print("Found system parameters related to plugins:") - for key, value in system_params: - print(f" {key}: {value[:100] if value else 'NULL'}...") - - # Check if this parameter contains plugin defaults - if 'default' in key.lower() and 'plugin' in key.lower(): - try: - if value and value.startswith('['): - plugins = json.loads(value) - if 'SYSTEM_PLUGIN_STORY' not in plugins: - plugins.append('SYSTEM_PLUGIN_STORY') - cursor.execute(""" - UPDATE sys_params - SET param_value = %s - WHERE param_key = %s - """, (json.dumps(plugins), key)) - print(f" Updated {key} to include SYSTEM_PLUGIN_STORY") - except: - pass - - # Add a new system parameter for default plugins if it doesn't exist - cursor.execute(""" - SELECT param_key FROM sys_params - WHERE param_key = 'default_agent_plugins' - """) - - if not cursor.fetchone(): - print("\nAdding default_agent_plugins system parameter...") - - default_plugins = [ - "SYSTEM_PLUGIN_MUSIC", - "SYSTEM_PLUGIN_STORY", - "SYSTEM_PLUGIN_WEATHER", - "SYSTEM_PLUGIN_NEWS_NEWSNOW" - ] - - cursor.execute(""" - INSERT INTO sys_params (param_key, param_value, param_type, remark, creator, create_date, updater, update_date) - VALUES (%s, %s, %s, %s, 0, NOW(), 0, NOW()) - """, ( - 'default_agent_plugins', - json.dumps(default_plugins), - 1, # Type 1 for system parameter - 'Default plugins for new agents' - )) - - print("Added default_agent_plugins with Story Playback included") - connection.commit() - else: - # Update existing parameter - cursor.execute(""" - SELECT param_value FROM sys_params - WHERE param_key = 'default_agent_plugins' - """) - - current_value = cursor.fetchone()[0] - if current_value: - try: - plugins = json.loads(current_value) - if 'SYSTEM_PLUGIN_STORY' not in plugins: - plugins.append('SYSTEM_PLUGIN_STORY') - cursor.execute(""" - UPDATE sys_params - SET param_value = %s, update_date = NOW() - WHERE param_key = 'default_agent_plugins' - """, (json.dumps(plugins),)) - print("Updated default_agent_plugins to include SYSTEM_PLUGIN_STORY") - connection.commit() - else: - print("SYSTEM_PLUGIN_STORY already in default_agent_plugins") - except Exception as e: - print(f"Error updating default plugins: {e}") - - return True - - except Error as e: - print(f"Error adding story to templates: {e}") - connection.rollback() - return False - finally: - cursor.close() - -def ensure_template_story_mappings(connection): - """Ensure all agent templates have Story Playback in their configuration""" - cursor = connection.cursor() - try: - print("\n4. Ensuring Template Configurations Include Story...") - print("=" * 50) - - # Since templates don't have direct plugin mappings, - # we need to ensure the agent creation process includes Story Playback - - # Check if there's an agent_template_plugin table or similar - cursor.execute(""" - SHOW TABLES LIKE '%agent_template%' - """) - - template_tables = cursor.fetchall() - print(f"Template-related tables found: {len(template_tables)}") - for table in template_tables: - print(f" - {table[0]}") - - # The key is to ensure that when an agent is created from a template, - # it automatically gets the Story Playback plugin - - # Check for any stored procedures or triggers that create agents - cursor.execute(""" - SELECT ROUTINE_NAME, ROUTINE_TYPE - FROM information_schema.ROUTINES - WHERE ROUTINE_SCHEMA = 'railway' - AND (ROUTINE_NAME LIKE '%agent%' OR ROUTINE_NAME LIKE '%create%') - """) - - procedures = cursor.fetchall() - if procedures: - print("\nFound stored procedures/functions related to agents:") - for proc_name, proc_type in procedures: - print(f" - {proc_type}: {proc_name}") - - return True - - except Error as e: - print(f"Error ensuring template mappings: {e}") - return False - finally: - cursor.close() - -def create_trigger_for_new_agents(connection): - """Create a trigger to automatically add Story Playback to new agents""" - cursor = connection.cursor() - try: - print("\n5. Creating Trigger for New Agents...") - print("=" * 50) - - # Drop existing trigger if it exists - cursor.execute("DROP TRIGGER IF EXISTS add_story_to_new_agent") - - # Create trigger to automatically add Story Playback when a new agent is created - trigger_sql = """ - CREATE TRIGGER add_story_to_new_agent - AFTER INSERT ON ai_agent - FOR EACH ROW - BEGIN - -- Add Story Playback plugin to new agent - IF NOT EXISTS ( - SELECT 1 FROM ai_agent_plugin_mapping - WHERE agent_id = NEW.id - AND plugin_id = 'SYSTEM_PLUGIN_STORY' - ) THEN - INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info) - VALUES ( - NEW.id, - 'SYSTEM_PLUGIN_STORY', - '{"story_dir": "./stories", "story_ext": ".mp3;.wav;.m4a", "refresh_time": "300"}' - ); - END IF; - - -- Also add other default plugins - IF NOT EXISTS ( - SELECT 1 FROM ai_agent_plugin_mapping - WHERE agent_id = NEW.id - AND plugin_id = 'SYSTEM_PLUGIN_MUSIC' - ) THEN - INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info) - VALUES (NEW.id, 'SYSTEM_PLUGIN_MUSIC', '{}'); - END IF; - - IF NOT EXISTS ( - SELECT 1 FROM ai_agent_plugin_mapping - WHERE agent_id = NEW.id - AND plugin_id = 'SYSTEM_PLUGIN_WEATHER' - ) THEN - INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info) - VALUES (NEW.id, 'SYSTEM_PLUGIN_WEATHER', '{"api_key": "12dd0eea5789636262549c9ec7f4f7d8", "default_location": "Bangalore", "units": "metric", "lang": "en"}'); - END IF; - END - """ - - try: - cursor.execute(trigger_sql) - print("Created trigger to automatically add Story Playback to new agents!") - connection.commit() - return True - except Error as e: - if "This version of MySQL doesn't yet support" in str(e): - print("Database doesn't support this trigger syntax") - print("Will use alternative method...") - return False - else: - print(f"Error creating trigger: {e}") - return False - - except Error as e: - print(f"Error with trigger creation: {e}") - return False - finally: - cursor.close() - -def main(): - print("Fixing Default Agent Template for Story Playback") - print("=" * 70) - - connection = connect_to_database() - if not connection: - return - - try: - # 1. Check existing templates - templates = check_agent_templates(connection) - - # 2. Check template plugin mappings - check_template_plugin_mappings(connection) - - # 3. Add story to templates - add_story_to_all_templates(connection) - - # 4. Ensure template configurations - ensure_template_story_mappings(connection) - - # 5. Try to create trigger (may not work on all MySQL versions) - trigger_created = create_trigger_for_new_agents(connection) - - # Summary - print(f"\n{'='*70}") - print("SUMMARY") - print('='*70) - - print("Actions taken:") - print("1. Checked all agent templates") - print("2. Added default_agent_plugins system parameter with Story Playback") - print("3. Ensured Story Playback is in default plugin list") - - if trigger_created: - print("4. Created database trigger for automatic Story Playback addition") - else: - print("4. Trigger creation failed (database limitation)") - print(" New agents will need Story Playback added by the application") - - print("\nRECOMMENDATION:") - print("To ensure all new agents have Story Playback, the agent creation") - print("process in the manager-api should be updated to automatically") - print("include SYSTEM_PLUGIN_STORY in the plugin mappings.") - - finally: - connection.close() - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/fix_intent_functions.py b/fix_intent_functions.py deleted file mode 100644 index 852a9d86f..000000000 --- a/fix_intent_functions.py +++ /dev/null @@ -1,265 +0,0 @@ -#!/usr/bin/env python3 -""" -Fix Intent function configuration to include play_story -""" - -import mysql.connector -from mysql.connector import Error -import json - -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("Connected to Railway MySQL database") - return connection - - except Error as e: - print(f"Database connection error: {e}") - return None - -def check_and_fix_intent_config(connection): - """Check and fix Intent function configuration""" - cursor = connection.cursor() - try: - # Get current Intent configuration - cursor.execute(""" - SELECT id, fields - FROM ai_model_provider - WHERE model_type = 'Intent' AND provider_code = 'function_call' - LIMIT 1 - """) - - result = cursor.fetchone() - if not result: - print("ERROR: Intent function call configuration not found!") - return False - - config_id, fields = result - print(f"Found Intent config: {config_id}") - - try: - fields_json = json.loads(fields) - print(f"Current fields count: {len(fields_json)}") - - # Check if functions field exists - functions_field_exists = False - for field in fields_json: - if field.get('key') == 'functions': - functions_field_exists = True - current_functions = field.get('default', '') - print(f"Current functions: {current_functions}") - - if 'play_story' in current_functions.lower(): - print("play_story already exists in functions!") - return True - break - - if not functions_field_exists: - print("Functions field missing! Adding it...") - - # Add functions field with all necessary functions - functions_field = { - "key": "functions", - "type": "array", - "label": "Functions", - "default": "play_music;play_story;get_weather;get_indian_news_api;get_news_from_newsnow;get_lunar" - } - - fields_json.append(functions_field) - else: - print("Adding play_story to existing functions...") - for i, field in enumerate(fields_json): - if field.get('key') == 'functions': - current_functions = field.get('default', '') - if current_functions and not current_functions.endswith(';'): - updated_functions = current_functions + ';play_story' - elif current_functions: - updated_functions = current_functions + 'play_story' - else: - updated_functions = 'play_story;play_music;get_weather;get_indian_news_api;get_news_from_newsnow;get_lunar' - - fields_json[i]['default'] = updated_functions - print(f"Updated functions to: {updated_functions}") - break - - # Update database - cursor.execute(""" - UPDATE ai_model_provider - SET fields = %s - WHERE id = %s - """, (json.dumps(fields_json), config_id)) - - connection.commit() - print("SUCCESS: Intent configuration updated!") - return True - - except json.JSONDecodeError as e: - print(f"JSON parsing error: {e}") - return False - - except Error as e: - print(f"Database error: {e}") - connection.rollback() - return False - finally: - cursor.close() - -def add_story_to_missing_agents(connection): - """Add Story Playback to agents that don't have it""" - cursor = connection.cursor() - try: - # Get agents without Story Playback - cursor.execute(""" - SELECT a.id, a.agent_name - FROM ai_agent a - LEFT JOIN ai_agent_plugin_mapping apm - ON a.id = apm.agent_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY' - WHERE apm.plugin_id IS NULL - """) - - missing_agents = cursor.fetchall() - - if not missing_agents: - print("All agents already have Story Playback!") - return True - - print(f"Adding Story Playback to {len(missing_agents)} agents...") - - # Default Story Playback parameters - param_info = { - "story_dir": "./stories", - "story_ext": ".mp3;.wav;.m4a", - "refresh_time": "300" - } - - success_count = 0 - for agent_id, agent_name in missing_agents: - try: - cursor.execute(""" - INSERT INTO ai_agent_plugin_mapping - (agent_id, plugin_id, param_info) - VALUES (%s, %s, %s) - """, (agent_id, "SYSTEM_PLUGIN_STORY", json.dumps(param_info))) - - print(f"Added Story Playback to: {agent_name}") - success_count += 1 - - except Error as e: - print(f"Failed to add to {agent_name}: {e}") - - connection.commit() - print(f"SUCCESS: Added Story Playback to {success_count} agents!") - return True - - except Error as e: - print(f"Error adding Story Playback to agents: {e}") - connection.rollback() - return False - finally: - cursor.close() - -def verify_final_state(connection): - """Verify everything is working""" - cursor = connection.cursor() - try: - # Check Intent functions - cursor.execute(""" - SELECT fields - FROM ai_model_provider - WHERE model_type = 'Intent' AND provider_code = 'function_call' - LIMIT 1 - """) - - result = cursor.fetchone() - if result: - fields_json = json.loads(result[0]) - for field in fields_json: - if field.get('key') == 'functions': - functions = field.get('default', '') - print(f"Final Intent functions: {functions}") - break - - # Check agent count - cursor.execute(""" - SELECT - COUNT(*) as total_agents, - SUM(CASE WHEN apm.plugin_id IS NOT NULL THEN 1 ELSE 0 END) as agents_with_story - FROM ai_agent a - LEFT JOIN ai_agent_plugin_mapping apm - ON a.id = apm.agent_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY' - """) - - total, with_story = cursor.fetchone() - print(f"Final state: {with_story}/{total} agents have Story Playback") - - if with_story == total: - print("SUCCESS: All agents now have Story Playback!") - return True - else: - print(f"WARNING: {total - with_story} agents still missing Story Playback") - return False - - except Error as e: - print(f"Error verifying final state: {e}") - return False - finally: - cursor.close() - -def main(): - print("Fixing Story Playback Function Configuration") - print("=" * 50) - - connection = connect_to_database() - if not connection: - return - - try: - # 1. Fix Intent configuration - print("\n1. Fixing Intent Function Configuration...") - intent_fixed = check_and_fix_intent_config(connection) - - # 2. Add Story Playback to missing agents - print("\n2. Adding Story Playback to Missing Agents...") - agents_fixed = add_story_to_missing_agents(connection) - - # 3. Verify final state - print("\n3. Verifying Final State...") - final_ok = verify_final_state(connection) - - # Summary - print(f"\n{'='*50}") - print("FINAL RESULT") - print('='*50) - - if intent_fixed: - print("Intent configuration: FIXED") - else: - print("Intent configuration: FAILED") - - if agents_fixed: - print("Agent mappings: FIXED") - else: - print("Agent mappings: FAILED") - - if final_ok: - print("Overall status: SUCCESS - Story Playback ready!") - else: - print("Overall status: PARTIAL - Some issues remain") - - finally: - connection.close() - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/fix_migration.sql b/fix_migration.sql deleted file mode 100644 index b8968fda9..000000000 --- a/fix_migration.sql +++ /dev/null @@ -1,67 +0,0 @@ --- 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/fix_story_playback.py b/fix_story_playback.py deleted file mode 100644 index 50fb37638..000000000 --- a/fix_story_playback.py +++ /dev/null @@ -1,270 +0,0 @@ -#!/usr/bin/env python3 -""" -Script to fix Story Playback function placement in agent templates -""" - -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 examine_ai_agent_template(connection): - """Examine the ai_agent_template table""" - cursor = connection.cursor() - try: - print(f"\n{'='*60}") - print("Structure of ai_agent_template table:") - print('='*60) - - cursor.execute("DESCRIBE ai_agent_template") - columns = cursor.fetchall() - - headers = ["Field", "Type", "Null", "Key", "Default", "Extra"] - print(tabulate(columns, headers=headers, tablefmt="grid")) - - # Get all records - cursor.execute("SELECT * FROM ai_agent_template") - templates = cursor.fetchall() - column_names = [desc[0] for desc in cursor.description] - - print(f"\nFound {len(templates)} agent templates:") - - for i, template in enumerate(templates): - template_dict = dict(zip(column_names, template)) - print(f"\n--- Template {i+1} ---") - print(f"ID: {template_dict.get('id')}") - print(f"Template Name: {template_dict.get('template_name', template_dict.get('name'))}") - - # Look for JSON fields that might contain function configurations - for col_name, cell_value in template_dict.items(): - if isinstance(cell_value, str) and cell_value.strip().startswith('{'): - try: - json_data = json.loads(cell_value) - print(f"\nJSON field '{col_name}':") - - # Check if it contains function configurations - if any(key in json_data for key in ['selected_functions', 'unselected_functions', 'functions', 'selectedFunctions', 'unselectedFunctions', 'plugins']): - print(f" Contains function/plugin configuration:") - print(json.dumps(json_data, indent=4)) - else: - # Just show the structure - print(f" Keys: {list(json_data.keys())}") - - except json.JSONDecodeError: - if len(str(cell_value)) > 100: - print(f" {col_name}: [Long text content, first 100 chars]: {str(cell_value)[:100]}...") - else: - print(f" {col_name}: {cell_value}") - elif cell_value is not None: - if len(str(cell_value)) > 100: - print(f" {col_name}: [Long content]: {str(cell_value)[:100]}...") - else: - print(f" {col_name}: {cell_value}") - - return templates, column_names - - except Error as e: - print(f"Error examining ai_agent_template: {e}") - return None, None - finally: - cursor.close() - -def check_ai_agent_plugin_mapping(connection): - """Check the ai_agent_plugin_mapping table""" - cursor = connection.cursor() - try: - print(f"\n{'='*60}") - print("ai_agent_plugin_mapping table:") - print('='*60) - - cursor.execute("DESCRIBE ai_agent_plugin_mapping") - columns = cursor.fetchall() - - headers = ["Field", "Type", "Null", "Key", "Default", "Extra"] - print(tabulate(columns, headers=headers, tablefmt="grid")) - - # Get all records - cursor.execute("SELECT * FROM ai_agent_plugin_mapping") - mappings = cursor.fetchall() - column_names = [desc[0] for desc in cursor.description] - - if mappings: - print(f"\nPlugin mappings:") - print(tabulate(mappings, headers=column_names, tablefmt="grid")) - else: - print("\nNo plugin mappings found") - - return mappings, column_names - - except Error as e: - print(f"Error examining ai_agent_plugin_mapping: {e}") - return None, None - finally: - cursor.close() - -def fix_story_playback_in_templates(connection): - """Fix Story Playback function to be in selected functions for all agent templates""" - cursor = connection.cursor() - try: - print(f"\n{'='*60}") - print("Fixing Story Playback function placement...") - print('='*60) - - # Get all agent templates - cursor.execute("SELECT * FROM ai_agent_template") - templates = cursor.fetchall() - column_names = [desc[0] for desc in cursor.description] - - story_playback_plugin_id = "SYSTEM_PLUGIN_STORY" - updates_made = 0 - - for template in templates: - template_dict = dict(zip(column_names, template)) - template_id = template_dict.get('id') - template_name = template_dict.get('template_name', template_dict.get('name', 'Unknown')) - - print(f"\nProcessing template: {template_name} (ID: {template_id})") - - # Check if this template already has the Story Playback plugin mapped - cursor.execute(""" - SELECT * FROM ai_agent_plugin_mapping - WHERE template_id = %s AND plugin_id = %s - """, (template_id, story_playback_plugin_id)) - existing_mapping = cursor.fetchone() - - if existing_mapping: - mapping_dict = dict(zip([desc[0] for desc in cursor.description], existing_mapping)) - current_status = mapping_dict.get('status', 0) - - print(f" Found existing mapping with status: {current_status}") - - if current_status != 1: # 1 = selected/enabled, 0 = unselected/disabled - # Update the mapping to enable the plugin - cursor.execute(""" - UPDATE ai_agent_plugin_mapping - SET status = 1, update_date = NOW(), updater = 0 - WHERE template_id = %s AND plugin_id = %s - """, (template_id, story_playback_plugin_id)) - - print(f" ✓ Updated Story Playback status from {current_status} to 1 (selected)") - updates_made += 1 - else: - print(f" ✓ Story Playback already selected for this template") - else: - # Create new mapping with status = 1 (selected) - cursor.execute(""" - INSERT INTO ai_agent_plugin_mapping - (template_id, plugin_id, status, sort, creator, create_date, updater, update_date) - VALUES (%s, %s, 1, 0, 0, NOW(), 0, NOW()) - """, (template_id, story_playback_plugin_id)) - - print(f" ✓ Created new mapping with Story Playback selected") - updates_made += 1 - - connection.commit() - print(f"\n{'='*60}") - print(f"Fix completed! Made {updates_made} updates to ensure Story Playback is selected for all agent templates.") - print('='*60) - - except Error as e: - print(f"Error fixing Story Playback function: {e}") - connection.rollback() - finally: - cursor.close() - -def verify_fix(connection): - """Verify that Story Playback is now selected for all templates""" - cursor = connection.cursor() - try: - print(f"\n{'='*60}") - print("Verifying fix...") - print('='*60) - - cursor.execute(""" - SELECT - at.id as template_id, - at.template_name, - apm.plugin_id, - apm.status, - amp.name as plugin_name - FROM ai_agent_template at - LEFT JOIN ai_agent_plugin_mapping apm ON at.id = apm.template_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY' - LEFT JOIN ai_model_provider amp ON apm.plugin_id = amp.id - ORDER BY at.template_name - """) - - results = cursor.fetchall() - column_names = [desc[0] for desc in cursor.description] - - print(f"\nStory Playback status for all templates:") - print(tabulate(results, headers=column_names, tablefmt="grid")) - - # Count how many are selected - selected_count = sum(1 for result in results if result[3] == 1) # status column - total_templates = len([r for r in results if r[0] is not None]) # templates with non-null id - - print(f"\nSummary:") - print(f"Total templates: {total_templates}") - print(f"Templates with Story Playback selected: {selected_count}") - - if selected_count == total_templates: - print("✅ SUCCESS: Story Playback is now selected for ALL agent templates!") - else: - print(f"⚠️ WARNING: {total_templates - selected_count} templates still don't have Story Playback selected") - - except Error as e: - print(f"Error verifying fix: {e}") - finally: - cursor.close() - -def main(): - print("Fixing Story Playback function placement in xiaozhi database") - print("=" * 70) - - # Connect to database - connection = connect_to_database() - if not connection: - return - - try: - # Examine agent template structure - examine_ai_agent_template(connection) - - # Check plugin mapping table - check_ai_agent_plugin_mapping(connection) - - # Fix Story Playback placement - fix_story_playback_in_templates(connection) - - # Verify the fix - verify_fix(connection) - - 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/fix_trigger_and_verify.py b/fix_trigger_and_verify.py deleted file mode 100644 index 078b19ffd..000000000 --- a/fix_trigger_and_verify.py +++ /dev/null @@ -1,293 +0,0 @@ -#!/usr/bin/env python3 -""" -Fix the trigger and ensure Story Playback is added to ALL new agents -""" - -import mysql.connector -from mysql.connector import Error -import json - -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("Connected to Railway MySQL database") - return connection - - except Error as e: - print(f"Database connection error: {e}") - return None - -def check_latest_agent(connection): - """Check the latest agent that was just created""" - cursor = connection.cursor() - try: - print("\n1. Checking Latest Agent...") - print("=" * 60) - - # Get the most recent agent - cursor.execute(""" - SELECT - a.id, - a.agent_name, - a.agent_code, - a.created_at, - GROUP_CONCAT(apm.plugin_id) as plugins - FROM ai_agent a - LEFT JOIN ai_agent_plugin_mapping apm ON a.id = apm.agent_id - WHERE a.agent_name = 'test' OR a.agent_code LIKE 'AGT_1756545169%' - GROUP BY a.id, a.agent_name, a.agent_code, a.created_at - ORDER BY a.created_at DESC - LIMIT 1 - """) - - result = cursor.fetchone() - - if result: - agent_id, name, code, created, plugins = result - print(f"Latest agent: {name} (ID: {agent_id[:16]}...)") - print(f"Code: {code}") - print(f"Created: {created}") - print(f"Plugins: {plugins}") - - if plugins and 'SYSTEM_PLUGIN_STORY' not in plugins: - print("\n[!] Story Playback is MISSING! Adding it now...") - - # Add Story Playback - param_info = { - "story_dir": "./stories", - "story_ext": ".mp3;.wav;.m4a", - "refresh_time": "300" - } - - cursor.execute(""" - INSERT INTO ai_agent_plugin_mapping - (agent_id, plugin_id, param_info) - VALUES (%s, %s, %s) - """, (agent_id, "SYSTEM_PLUGIN_STORY", json.dumps(param_info))) - - connection.commit() - print("[FIXED] Added Story Playback to latest agent!") - - return agent_id - elif plugins and 'SYSTEM_PLUGIN_STORY' in plugins: - print("[OK] Story Playback already present!") - return agent_id - else: - print("No agent found with name 'test'") - - return None - - except Error as e: - print(f"Error checking latest agent: {e}") - return None - finally: - cursor.close() - -def drop_and_recreate_trigger(connection): - """Drop the old trigger and create a better one""" - cursor = connection.cursor() - try: - print("\n2. Recreating Database Trigger...") - print("=" * 60) - - # Drop existing trigger - cursor.execute("DROP TRIGGER IF EXISTS add_story_to_new_agent") - print("Dropped old trigger") - - # Create new trigger that works after INSERT - # Using simpler syntax that should work on more MySQL versions - trigger_sql = """ - CREATE TRIGGER add_story_to_new_agent - AFTER INSERT ON ai_agent - FOR EACH ROW - BEGIN - INSERT IGNORE INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info) - VALUES (NEW.id, 'SYSTEM_PLUGIN_STORY', '{"story_dir": "./stories", "story_ext": ".mp3;.wav;.m4a", "refresh_time": "300"}'); - END - """ - - cursor.execute(trigger_sql) - connection.commit() - print("Created new trigger successfully!") - - return True - - except Error as e: - print(f"Trigger creation failed: {e}") - - # Try alternative approach - stored procedure - try: - print("\nTrying stored procedure approach...") - - cursor.execute("DROP PROCEDURE IF EXISTS add_default_plugins") - - proc_sql = """ - CREATE PROCEDURE add_default_plugins(IN agent_id VARCHAR(32)) - BEGIN - INSERT IGNORE INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info) - VALUES (agent_id, 'SYSTEM_PLUGIN_STORY', '{"story_dir": "./stories", "story_ext": ".mp3;.wav;.m4a", "refresh_time": "300"}'); - END - """ - - cursor.execute(proc_sql) - connection.commit() - print("Created stored procedure as alternative!") - - return True - - except Error as e2: - print(f"Stored procedure also failed: {e2}") - return False - finally: - cursor.close() - -def ensure_all_agents_have_story(connection): - """Make sure ALL agents have Story Playback""" - cursor = connection.cursor() - try: - print("\n3. Ensuring ALL Agents Have Story Playback...") - print("=" * 60) - - # Find agents without Story Playback - cursor.execute(""" - SELECT a.id, a.agent_name - FROM ai_agent a - LEFT JOIN ai_agent_plugin_mapping apm - ON a.id = apm.agent_id AND apm.plugin_id = 'SYSTEM_PLUGIN_STORY' - WHERE apm.plugin_id IS NULL - """) - - agents_without_story = cursor.fetchall() - - if agents_without_story: - print(f"Found {len(agents_without_story)} agents without Story Playback:") - - param_info = { - "story_dir": "./stories", - "story_ext": ".mp3;.wav;.m4a", - "refresh_time": "300" - } - - for agent_id, agent_name in agents_without_story: - print(f" Adding to: {agent_name}") - - cursor.execute(""" - INSERT IGNORE INTO ai_agent_plugin_mapping - (agent_id, plugin_id, param_info) - VALUES (%s, %s, %s) - """, (agent_id, "SYSTEM_PLUGIN_STORY", json.dumps(param_info))) - - connection.commit() - print(f"[FIXED] Added Story Playback to {len(agents_without_story)} agents!") - else: - print("All agents already have Story Playback!") - - return True - - except Error as e: - print(f"Error ensuring Story Playback: {e}") - return False - finally: - cursor.close() - -def update_manager_api_defaults(connection): - """Update manager-api default plugins to include Story Playback""" - cursor = connection.cursor() - try: - print("\n4. Updating Manager-API Default Plugins...") - print("=" * 60) - - # Check if there's a default plugins configuration - cursor.execute(""" - SELECT id, agent_code, agent_name - FROM ai_agent_template - WHERE is_visible = 0 - ORDER BY sort - LIMIT 1 - """) - - default_template = cursor.fetchone() - - if default_template: - template_id = default_template[0] - print(f"Default template: {default_template[2]} (ID: {template_id})") - - # The manager-api needs to be configured to include Story Playback - # when creating agents from templates - - print("\nRECOMMENDATION FOR MANAGER-API:") - print("The manager-api code should be updated to include") - print("SYSTEM_PLUGIN_STORY in the default plugins list when") - print("creating new agents. Currently it only adds:") - print(" - SYSTEM_PLUGIN_MUSIC") - print(" - SYSTEM_PLUGIN_WEATHER") - print(" - SYSTEM_PLUGIN_NEWS_NEWSNOW") - print("\nIt should also add:") - print(" - SYSTEM_PLUGIN_STORY") - - return True - - except Error as e: - print(f"Error updating defaults: {e}") - return False - finally: - cursor.close() - -def main(): - print("Fixing Story Playback Auto-Addition for New Agents") - print("=" * 70) - - connection = connect_to_database() - if not connection: - return - - try: - # 1. Check and fix the latest agent - latest_agent_id = check_latest_agent(connection) - - # 2. Try to recreate trigger - trigger_created = drop_and_recreate_trigger(connection) - - # 3. Ensure all agents have Story Playback - ensure_all_agents_have_story(connection) - - # 4. Update manager-api defaults - update_manager_api_defaults(connection) - - # Summary - print(f"\n{'='*70}") - print("SUMMARY") - print('='*70) - - if latest_agent_id: - print("[FIXED] Latest agent now has Story Playback") - - if trigger_created: - print("[OK] Database trigger/procedure created") - else: - print("[INFO] Trigger couldn't be created - manual fix needed") - - print("\nIMPORTANT:") - print("The manager-api Java code needs to be updated to") - print("automatically include SYSTEM_PLUGIN_STORY when") - print("creating new agents from templates.") - print("\nUntil then, Story Playback must be added manually") - print("or via this script after agent creation.") - - finally: - connection.close() - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/main/manager-api/README.md b/main/manager-api/README.md index e8822b8ea..cf8153009 100644 --- a/main/manager-api/README.md +++ b/main/manager-api/README.md @@ -1,26 +1,179 @@ 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 +# XiaoZhi ESP32 Manager API -run app +This project is developed based on the SpringBoot framework and serves as the backend API for the XiaoZhi ESP32 management system. -npm run serve -manager-api: This project is developed based on the SpringBoot framework. +## Development Environment Requirements + +- **JDK 21+** +- **Maven 3.8+** +- **Docker & Docker Compose** (for local database and cache) +- **MySQL 8.0+** (via Docker) +- **Redis 7.0+** (via Docker) + +## Quick Start (Development Mode) + +### Option 1: Automated Setup (Recommended) + +```powershell +# Run the automated setup script +.\dev-setup.ps1 + +# Then start the application +mvn spring-boot:run "-Dspring-boot.run.arguments=--spring.profiles.active=dev" +``` + +### Option 2: Manual Setup + +#### Step 1: Start Docker Containers + +First, start the required MySQL and Redis containers: + +```bash +# Navigate to the manager-api directory +cd D:\cheekofinal\xiaozhi-esp32-server\main\manager-api + +# Start Docker containers (MySQL, Redis, phpMyAdmin, Redis Commander) +docker-compose up -d + +# Verify containers are running +docker-compose ps +``` + +#### Step 2: Run the Spring Boot Application + +```bash +# Clean and compile the project +mvn clean compile + +# Run the application with dev profile +mvn spring-boot:run "-Dspring-boot.run.arguments=--spring.profiles.active=dev" +``` + +## Docker Services + +The `docker-compose.yml` includes the following services: + +| Service | Port | Description | Credentials | +|---------|------|-------------|--------------| +| **manager-api-db** (MySQL) | 3307 | MySQL database | User: `manager`
Password: `managerpassword`
Database: `manager_api` | +| **manager-api-redis** | 6380 | Redis cache | Password: `redispassword` | +| **phpMyAdmin** | 8080 | MySQL web interface | User: `root`
Password: `rootpassword` | +| **redis-commander** | 8081 | Redis web interface | Auto-configured | + +## Access Points + +- **API Documentation**: http://localhost:8002/xiaozhi/doc.html +- **Application Base URL**: http://localhost:8002/toy +- **phpMyAdmin**: http://localhost:8080 +- **Redis Commander**: http://localhost:8081 + +## Configuration + +The development configuration is located in: +``` +src/main/resources/application-dev.yml +``` + +This configuration is set up to use the local Docker containers: +- MySQL on localhost:3307 +- Redis on localhost:6380 + +## Database Management + +### Manual Database Connection +```bash +# Connect to MySQL container +docker exec -it manager-api-db mysql -u manager -p'managerpassword' manager_api + +# Connect to Redis container +docker exec -it manager-api-redis redis-cli -a redispassword +``` + +### Database Migration +The application uses Liquibase for database migrations. Migrations run automatically on startup. + +## Troubleshooting + +### Container Issues +```bash +# Check container logs +docker-compose logs manager-api-db +docker-compose logs manager-api-redis + +# Restart containers +docker-compose restart + +# Stop and remove all containers +docker-compose down + +# Stop and remove containers with volumes +docker-compose down -v +``` + +### Application Issues +```bash +# Check if ports are available +netstat -an | findstr :8002 +netstat -an | findstr :3307 +netstat -an | findstr :6380 + +# Clean Maven build +mvn clean install +``` + +### Common Error Solutions + +1. **Port Conflicts**: If ports 3307, 6380, 8080, or 8081 are in use, modify the ports in `docker-compose.yml` + +2. **Database Connection Failed**: + - Ensure Docker containers are running + - Wait for MySQL health check to pass (can take 30-60 seconds) + - Check if credentials match in `application-dev.yml` + +3. **Redis Connection Failed**: + - Verify Redis container is healthy + - Check Redis password configuration + +## Development Workflow + +1. **First Time Setup**: + ```bash + docker-compose up -d + mvn clean compile + mvn spring-boot:run "-Dspring-boot.run.arguments=--spring.profiles.active=dev" + ``` + +2. **Daily Development**: + ```bash + # Start containers (if not running) + docker-compose start + + # Run application + mvn spring-boot:run "-Dspring-boot.run.arguments=--spring.profiles.active=dev" + ``` + +3. **Cleanup**: + ```bash + # Stop application (Ctrl+C) + # Stop containers + docker-compose stop + ``` + +## Project Structure When developing, use a code editor and select the `manager-api` folder as the project directory when importing the project. -# Development Environment - -JDK 21 -Maven 3.8+ -MySQL 8.0+ -Redis 5.0+ -Vue 3.x - -# API Documentation - -After starting, open: http://localhost:8002/xiaozhi/doc.html - -to run app - -mvn spring-boot:run +``` +manager-api/ +├── docker-compose.yml # Docker services configuration +├── src/main/resources/ +│ ├── application.yml # Base configuration +│ ├── application-dev.yml # Development configuration +│ └── application-prod.yml # Production configuration +├── docker/ +│ ├── mysql/init/ # MySQL initialization scripts +│ └── redis/ # Redis configuration +└── target/ # Compiled classes +``` diff --git a/main/manager-api/dev-setup.ps1 b/main/manager-api/dev-setup.ps1 new file mode 100644 index 000000000..74db984bf --- /dev/null +++ b/main/manager-api/dev-setup.ps1 @@ -0,0 +1,82 @@ +# XiaoZhi Manager API - Development Setup Script +# This script sets up the development environment for the Manager API + +Write-Host "🚀 XiaoZhi Manager API Development Setup" -ForegroundColor Green +Write-Host "=======================================" -ForegroundColor Green + +# Check if Docker is running +Write-Host "📦 Checking Docker..." -ForegroundColor Yellow +try { + docker --version | Out-Null + Write-Host "✅ Docker is available" -ForegroundColor Green +} catch { + Write-Host "❌ Docker is not available. Please install Docker Desktop and try again." -ForegroundColor Red + exit 1 +} + +# Check if Maven is available +Write-Host "🔨 Checking Maven..." -ForegroundColor Yellow +try { + mvn --version | Out-Null + Write-Host "✅ Maven is available" -ForegroundColor Green +} catch { + Write-Host "❌ Maven is not available. Please install Maven and try again." -ForegroundColor Red + exit 1 +} + +# Start Docker containers +Write-Host "🐳 Starting Docker containers..." -ForegroundColor Yellow +docker-compose up -d + +if ($LASTEXITCODE -eq 0) { + Write-Host "✅ Docker containers started successfully" -ForegroundColor Green +} else { + Write-Host "❌ Failed to start Docker containers" -ForegroundColor Red + exit 1 +} + +# Wait for containers to be healthy +Write-Host "⏳ Waiting for containers to be healthy..." -ForegroundColor Yellow +$timeout = 60 +$elapsed = 0 +do { + $status = docker-compose ps --services --filter "status=running" | Measure-Object -Line + if ($status.Lines -eq 4) { + Write-Host "✅ All containers are running" -ForegroundColor Green + break + } + Start-Sleep -Seconds 2 + $elapsed += 2 + Write-Host "." -NoNewline -ForegroundColor Yellow +} while ($elapsed -lt $timeout) + +if ($elapsed -ge $timeout) { + Write-Host "`n⚠️ Containers may still be starting. Check with 'docker-compose ps'" -ForegroundColor Yellow +} else { + Write-Host "" +} + +# Display container status +Write-Host "📋 Container Status:" -ForegroundColor Cyan +docker-compose ps + +Write-Host "`n🌐 Service URLs:" -ForegroundColor Cyan +Write-Host " • API Documentation: http://localhost:8002/xiaozhi/doc.html" -ForegroundColor White +Write-Host " • Application: http://localhost:8002/toy" -ForegroundColor White +Write-Host " • phpMyAdmin: http://localhost:8080" -ForegroundColor White +Write-Host " • Redis Commander: http://localhost:8081" -ForegroundColor White + +Write-Host "`n🔑 Database Credentials:" -ForegroundColor Cyan +Write-Host " • MySQL: manager/managerpassword @ localhost:3307" -ForegroundColor White +Write-Host " • Redis: redispassword @ localhost:6380" -ForegroundColor White + +Write-Host "`n🚀 To start the application, run:" -ForegroundColor Green +Write-Host " mvn spring-boot:run `"-Dspring-boot.run.arguments=--spring.profiles.active=dev`"" -ForegroundColor Yellow + +Write-Host "`n📋 Quick Commands:" -ForegroundColor Cyan +Write-Host " • Check containers: docker-compose ps" -ForegroundColor White +Write-Host " • View logs: docker-compose logs [service-name]" -ForegroundColor White +Write-Host " • Stop containers: docker-compose stop" -ForegroundColor White +Write-Host " • Remove containers: docker-compose down" -ForegroundColor White + +Write-Host "`n✨ Setup completed successfully!" -ForegroundColor Green diff --git a/main/manager-api/docker-compose.yml b/main/manager-api/docker-compose.yml new file mode 100644 index 000000000..6c9d22433 --- /dev/null +++ b/main/manager-api/docker-compose.yml @@ -0,0 +1,90 @@ +version: '3.8' + +services: + # MySQL Database + manager-api-db: + image: mysql:8.0 + container_name: manager-api-db + restart: always + environment: + MYSQL_ROOT_PASSWORD: rootpassword + MYSQL_DATABASE: manager_api + MYSQL_USER: manager + MYSQL_PASSWORD: managerpassword + TZ: Asia/Shanghai + ports: + - "3307:3306" # Using 3307 to avoid conflicts with other MySQL instances + volumes: + - mysql_data:/var/lib/mysql + - ./docker/mysql/init:/docker-entrypoint-initdb.d # For initialization scripts + command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci + healthcheck: + test: ["CMD", "mysqladmin", "ping", "-h", "localhost"] + timeout: 20s + interval: 10s + retries: 10 + networks: + - manager-api-network + + # Redis Cache + manager-api-redis: + image: redis:7-alpine + container_name: manager-api-redis + restart: always + environment: + TZ: Asia/Shanghai + ports: + - "6380:6379" # Using 6380 to avoid conflicts with other Redis instances + volumes: + - redis_data:/data + - ./docker/redis/redis.conf:/usr/local/etc/redis/redis.conf # Optional custom config + command: redis-server --appendonly yes --requirepass redispassword + healthcheck: + test: ["CMD", "redis-cli", "auth", "redispassword", "ping"] + interval: 10s + timeout: 5s + retries: 3 + networks: + - manager-api-network + + # Redis Commander (Optional - Web UI for Redis) + redis-commander: + image: rediscommander/redis-commander:latest + container_name: manager-api-redis-commander + restart: unless-stopped + environment: + REDIS_HOSTS: local:manager-api-redis:6379:0:redispassword + ports: + - "8081:8081" + depends_on: + - manager-api-redis + networks: + - manager-api-network + + # phpMyAdmin (Optional - Web UI for MySQL) + phpmyadmin: + image: phpmyadmin/phpmyadmin + container_name: manager-api-phpmyadmin + restart: unless-stopped + environment: + PMA_HOST: manager-api-db + PMA_PORT: 3306 + PMA_USER: root + PMA_PASSWORD: rootpassword + MYSQL_ROOT_PASSWORD: rootpassword + ports: + - "8080:80" + depends_on: + - manager-api-db + networks: + - manager-api-network + +volumes: + mysql_data: + driver: local + redis_data: + driver: local + +networks: + manager-api-network: + driver: bridge 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 4bd8f948e..1b84853fb 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 @@ -67,11 +67,21 @@ public class AgentController { private final RedisUtils redisUtils; @GetMapping("/list") - @Operation(summary = "Get user agents list") + @Operation(summary = "Get agents list (admin gets all agents, user gets own agents)") @RequiresPermissions("sys:role:normal") - public Result> getUserAgents() { + public Result> getAgentsList() { UserDetail user = SecurityUser.getUser(); - List agents = agentService.getUserAgents(user.getId()); + List agents; + + // Check if user is super admin + if (user.getSuperAdmin() != null && user.getSuperAdmin() == 1) { + // Admin sees all agents from all users with owner information + agents = agentService.getAllAgentsForAdmin(); + } else { + // Regular user sees only their own agents + agents = agentService.getUserAgents(user.getId()); + } + return new Result>().ok(agents); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java index 03e569cdc..a596aab88 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java @@ -1,8 +1,10 @@ package xiaozhi.modules.agent.dao; +import java.util.List; +import java.util.Map; + import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; - import org.apache.ibatis.annotations.Select; import xiaozhi.common.dao.BaseDao; import xiaozhi.modules.agent.entity.AgentEntity; @@ -30,6 +32,24 @@ public interface AgentDao extends BaseDao { " ORDER BY d.id DESC LIMIT 1") AgentEntity getDefaultAgentByMacAddress(@Param("macAddress") String macAddress); + /** + * 获取所有智能体及其所有者信息(管理员专用) + * + * @return 所有智能体列表及用户信息 + */ + @Select("SELECT " + + "a.id, a.agent_name, a.system_prompt, a.tts_model_id, " + + "a.llm_model_id, a.vllm_model_id, a.mem_model_id, a.tts_voice_id, " + + "a.created_at, a.updated_at, a.user_id, " + + "u.username as owner_username, " + + "GROUP_CONCAT(d.mac_address SEPARATOR ',') as device_mac_addresses " + + "FROM ai_agent a " + + "LEFT JOIN sys_user u ON a.user_id = u.id " + + "LEFT JOIN ai_device d ON a.id = d.agent_id " + + "GROUP BY a.id " + + "ORDER BY a.created_at DESC") + List> getAllAgentsWithOwnerInfo(); + /** * 根据id查询agent信息,包括插件信息 * diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java index 218ee1ebf..fcf8d229a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java @@ -45,4 +45,14 @@ public class AgentDTO { @Schema(description = "设备数量", example = "10") private Integer deviceCount; + + @Schema(description = "设备MAC地址列表", example = "AA:BB:CC:DD:EE:FF,11:22:33:44:55:66") + private String deviceMacAddresses; + + // 管理员专用字段 - 智能体所有者信息 + @Schema(description = "所有者用户名", example = "john_doe") + private String ownerUsername; + + @Schema(description = "创建时间", example = "2024-03-20 10:00:00") + private Date createDate; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java index a9d4e5bb2..67b28a4a0 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java @@ -43,6 +43,21 @@ public interface AgentService extends BaseService { */ boolean insert(AgentEntity entity); + /** + * 获取用户的智能体列表 + * + * @param userId 用户ID + * @return 智能体列表 + */ + List getUserAgents(Long userId); + + /** + * 获取所有智能体列表(管理员专用,包含用户信息) + * + * @return 所有智能体列表 + */ + List getAllAgentsForAdmin(); + /** * 根据用户ID删除智能体 * @@ -50,13 +65,6 @@ public interface AgentService extends BaseService { */ void deleteAgentByUserId(Long userId); - /** - * 获取用户智能体列表 - * - * @param userId 用户ID - * @return 智能体列表 - */ - List getUserAgents(Long userId); /** * 根据智能体ID获取设备数量 diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java index e425b743f..330ee8071 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java @@ -150,6 +150,59 @@ public class AgentServiceImpl extends BaseServiceImpl imp }).collect(Collectors.toList()); } + @Override + public List getAllAgentsForAdmin() { + List> agentMaps = agentDao.getAllAgentsWithOwnerInfo(); + return agentMaps.stream().map(agentMap -> { + AgentDTO dto = new AgentDTO(); + + // 基础智能体信息 + String agentId = (String) agentMap.get("id"); + dto.setId(agentId); + dto.setAgentName((String) agentMap.get("agent_name")); + dto.setSystemPrompt((String) agentMap.get("system_prompt")); + + // Handle LocalDateTime to Date conversion for createDate + Object createdAt = agentMap.get("created_at"); + if (createdAt instanceof java.time.LocalDateTime) { + dto.setCreateDate(java.sql.Timestamp.valueOf((java.time.LocalDateTime) createdAt)); + } + + // 获取模型名称 - 同用户方法 + String ttsModelId = (String) agentMap.get("tts_model_id"); + String llmModelId = (String) agentMap.get("llm_model_id"); + String vllmModelId = (String) agentMap.get("vllm_model_id"); + String memModelId = (String) agentMap.get("mem_model_id"); + String ttsVoiceId = (String) agentMap.get("tts_voice_id"); + + dto.setTtsModelName(modelConfigService.getModelNameById(ttsModelId)); + dto.setLlmModelName(modelConfigService.getModelNameById(llmModelId)); + dto.setVllmModelName(modelConfigService.getModelNameById(vllmModelId)); + dto.setMemModelId(memModelId); + dto.setTtsVoiceName(timbreModelService.getTimbreNameById(ttsVoiceId)); + + // 获取智能体最近的最后连接时长 - 同用户方法 + dto.setLastConnectedAt(deviceService.getLatestLastConnectionTime(agentId)); + + // 获取设备MAC地址列表 - 管理员专用 + String macAddresses = (String) agentMap.get("device_mac_addresses"); + dto.setDeviceMacAddresses(macAddresses); + + // 计算设备数量(从MAC地址列表或使用原方法) + if (macAddresses != null && !macAddresses.isEmpty()) { + dto.setDeviceCount(macAddresses.split(",").length); + } else { + // 使用原来的方法获取设备数量 + dto.setDeviceCount(getDeviceCountByAgentId(agentId)); + } + + // 管理员专用字段 - 用户信息 + dto.setOwnerUsername((String) agentMap.get("owner_username")); + + return dto; + }).collect(Collectors.toList()); + } + @Override public Integer getDeviceCountByAgentId(String agentId) { if (StringUtils.isBlank(agentId)) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java index a23e9f81c..de9802776 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java @@ -71,7 +71,17 @@ public class DeviceController { @RequiresPermissions("sys:role:normal") public Result> getUserDevices(@PathVariable String agentId) { UserDetail user = SecurityUser.getUser(); - List devices = deviceService.getUserDevices(user.getId(), agentId); + List devices; + + // Check if user is super admin + if (user.getSuperAdmin() != null && user.getSuperAdmin() == 1) { + // Admin can see all devices for any agent + devices = deviceService.getDevicesByAgentId(agentId); + } else { + // Regular user can only see their own devices + devices = deviceService.getUserDevices(user.getId(), agentId); + } + return new Result>().ok(devices); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java index 3392c96ff..2afbd730e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java @@ -25,6 +25,11 @@ public interface DeviceService extends BaseService { */ List getUserDevices(Long userId, String agentId); + /** + * 获取指定智能体的所有设备列表(管理员专用) + */ + List getDevicesByAgentId(String agentId); + /** * 解绑设备 */ 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 96315ccc3..0119017c5 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 @@ -211,6 +211,13 @@ public class DeviceServiceImpl extends BaseServiceImpl return baseDao.selectList(wrapper); } + @Override + public List getDevicesByAgentId(String agentId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("agent_id", agentId); + return baseDao.selectList(wrapper); + } + @Override public void unbindDevice(Long userId, String deviceId) { UpdateWrapper wrapper = new UpdateWrapper<>(); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java index 02538caf7..f650d9b28 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java @@ -63,8 +63,8 @@ public class WebMvcConfig implements WebMvcConfigurer { // 忽略未知属性 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - // 设置时区 - mapper.setTimeZone(TimeZone.getTimeZone("GMT+8")); + // 设置时区 (IST - India Standard Time) + mapper.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata")); // 配置Java8日期时间序列化 JavaTimeModule javaTimeModule = new JavaTimeModule(); diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java index e3bc5a767..e01b40616 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java @@ -64,7 +64,7 @@ public class CaptchaServiceImpl implements CaptchaService { if (StringUtils.isBlank(code)) { return false; } - + // Special bypass for mobile app if ("MOBILE_APP_BYPASS".equals(code)) { // Mobile apps can bypass captcha validation @@ -72,7 +72,7 @@ public class CaptchaServiceImpl implements CaptchaService { // such as checking a special header or API key return true; } - + // 获取验证码 String captcha = getCache(uuid, delete); @@ -139,6 +139,14 @@ public class CaptchaServiceImpl implements CaptchaService { @Override public boolean validateSMSValidateCode(String phone, String code, Boolean delete) { + // Special bypass for mobile app SMS verification + if ("MOBILE_APP_BYPASS".equals(code)) { + // Mobile apps can bypass SMS validation + // In production, you should add additional security checks + // such as checking a special header or API key + return true; + } + String key = RedisKeys.getSMSValidateCodeKey(phone); return validate(key, code, delete); } diff --git a/main/manager-api/src/main/resources/application-dev.yml b/main/manager-api/src/main/resources/application-dev.yml index 526c9aef5..7ed3bdd10 100644 --- a/main/manager-api/src/main/resources/application-dev.yml +++ b/main/manager-api/src/main/resources/application-dev.yml @@ -22,6 +22,7 @@ spring: # password: cTefiuLmZSMqGpcQImUmBIsUBhNyUvrK driver-class-name: com.mysql.cj.jdbc.Driver # Railway MySQL Configuration - Updated for Railway database + # url: jdbc:mysql://crossover.proxy.rlwy.net:56145/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true # username: root # password: XjOWQwtGNcoMIELTjoMoaaBTfKiBjVcA @@ -29,6 +30,7 @@ spring: username: manager password: managerpassword + initial-size: 10 max-active: 100 min-idle: 10 @@ -63,3 +65,4 @@ spring: max-idle: 8 min-idle: 0 max-wait: -1ms + diff --git a/main/manager-api/src/main/resources/db/changelog/202509081740_add_semantic_search_config.sql b/main/manager-api/src/main/resources/db/changelog/202509081740_add_semantic_search_config.sql new file mode 100644 index 000000000..c0da10028 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202509081740_add_semantic_search_config.sql @@ -0,0 +1,17 @@ +-- Add semantic search configuration for improved music search functionality +-- 添加语义搜索配置以改进音乐搜索功能 + +-- Delete existing semantic search params if they exist +delete from sys_params where id in (701, 702, 703, 704, 705, 706, 707); + +-- Insert semantic search configuration parameters +INSERT INTO sys_params +(id, param_code, param_value, value_type, param_type, remark, creator, create_date, updater, update_date) +VALUES +(701, 'semantic_search.enabled', 'true', 'boolean', 1, 'Enable semantic music search using vector embeddings', NULL, NULL, NULL, NULL), +(702, 'semantic_search.qdrant_url', 'https://a2482b9f-2c29-476e-9ff0-741aaaaf632e.eu-west-1-0.aws.cloud.qdrant.io', 'string', 1, 'Qdrant vector database URL for music embeddings', NULL, NULL, NULL, NULL), +(703, 'semantic_search.qdrant_api_key', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJtIn0.zPBGAqVGy-edbbgfNOJsPWV496BsnQ4ELOFvsLNyjsk', 'string', 1, 'Qdrant API key for authentication', NULL, NULL, NULL, NULL), +(704, 'semantic_search.collection_name', 'xiaozhi_music', 'string', 1, 'Vector collection name for music embeddings', NULL, NULL, NULL, NULL), +(705, 'semantic_search.embedding_model', 'all-MiniLM-L6-v2', 'string', 1, 'Sentence transformer model for generating embeddings', NULL, NULL, NULL, NULL), +(706, 'semantic_search.search_limit', '5', 'number', 1, 'Maximum number of search results to return', NULL, NULL, NULL, NULL), +(707, 'semantic_search.min_score_threshold', '0.5', 'number', 1, 'Minimum similarity score threshold (0.0-1.0)', NULL, NULL, NULL, NULL); \ No newline at end of file diff --git a/main/manager-web/src/apis/module/admin.js b/main/manager-web/src/apis/module/admin.js index 27c1bc3e7..ae0644bf0 100644 --- a/main/manager-web/src/apis/module/admin.js +++ b/main/manager-web/src/apis/module/admin.js @@ -41,6 +41,65 @@ export default { }) }).send() }, + // 获取用户信息 (通过用户ID) - 使用用户列表API并客户端过滤 + getUserById(userId, callback) { + // 使用现有的用户列表API,获取所有用户然后客户端过滤 + RequestService.sendRequest() + .url(`${getServiceUrl()}/admin/users?page=1&limit=1000`) + .method('GET') + .success((res) => { + RequestService.clearRequestTime() + console.log('getUserById API response:', res); + + // 检查响应结构并查找指定用户 + if (res.data && res.data.code === 0 && res.data.data && res.data.data.list && Array.isArray(res.data.data.list)) { + // 在用户列表中查找指定ID的用户 (注意字段名是userid,不是id) + const userInfo = res.data.data.list.find(user => + user.userid === userId || user.userid === parseInt(userId) || user.userid === String(userId) + ); + + if (userInfo) { + console.log('Found user info:', userInfo); + const formattedResponse = { + data: { + code: 0, + msg: 'success', + data: userInfo + } + }; + callback(formattedResponse); + } else { + console.log('User not found in list, userId:', userId); + console.log('Available user IDs:', res.data.data.list.map(u => u.userid)); + // 用户不存在 + const errorResponse = { + data: { + code: 1, + msg: 'User not found', + data: null + } + }; + callback(errorResponse); + } + } else { + console.error('Invalid response structure for getUserById:', res); + const errorResponse = { + data: { + code: 1, + msg: 'Invalid response structure', + data: null + } + }; + callback(errorResponse); + } + }) + .networkFail((err) => { + console.error('获取用户信息失败:', err) + RequestService.reAjaxFun(() => { + this.getUserById(userId, callback) + }) + }).send() + }, // 重置用户密码 resetUserPassword(id, callback) { RequestService.sendRequest() diff --git a/main/manager-web/src/apis/module/agent.js b/main/manager-web/src/apis/module/agent.js index d6ea74583..daa156efb 100644 --- a/main/manager-web/src/apis/module/agent.js +++ b/main/manager-web/src/apis/module/agent.js @@ -3,8 +3,29 @@ import RequestService from '../httpRequest'; export default { - // 获取智能体列表 - getAgentList(callback) { + // 获取智能体列表 (Admin - shows all agents from all users) + getAgentList(params, callback) { + // Support both old callback-only format and new params format + if (typeof params === 'function') { + callback = params; + params = { page: 1, limit: 1000 }; // Default pagination for all agents + } + RequestService.sendRequest() + .url(`${getServiceUrl()}/agent/all`) + .method('GET') + .data(params) + .success((res) => { + RequestService.clearRequestTime(); + callback(res); + }) + .networkFail(() => { + RequestService.reAjaxFun(() => { + this.getAgentList(params, callback); + }); + }).send(); + }, + // 获取用户自己的智能体列表 (User - shows only current user's agents) + getUserAgentList(callback) { RequestService.sendRequest() .url(`${getServiceUrl()}/agent/list`) .method('GET') @@ -14,7 +35,7 @@ export default { }) .networkFail(() => { RequestService.reAjaxFun(() => { - this.getAgentList(callback); + this.getUserAgentList(callback); }); }).send(); }, diff --git a/main/manager-web/src/components/ChatHistoryDialog.vue b/main/manager-web/src/components/ChatHistoryDialog.vue index 6afdf8796..8a4e441df 100644 --- a/main/manager-web/src/components/ChatHistoryDialog.vue +++ b/main/manager-web/src/components/ChatHistoryDialog.vue @@ -96,7 +96,7 @@ export default { const result = []; const TIME_INTERVAL = 60 * 1000; // 1分钟的时间间隔(毫秒) - // 添加第一条消息的时间标记 + // 添加第一条消息的时间标记 (converted to IST) if (this.messages[0]) { result.push({ type: 'time', @@ -118,7 +118,7 @@ export default { if (nextTime - currentTime > TIME_INTERVAL) { result.push({ type: 'time', - content: this.formatTime(this.messages[i + 1].createdAt), + content: this.formatTime(this.messages[i + 1].createdAt), // converted to IST id: `time-${Date.now()}-${Math.random().toString(36).substr(2, 9)}` }); } @@ -220,24 +220,36 @@ export default { }, 200); }, formatTime(timestamp) { + // Backend sends timestamps already in IST format, no timezone conversion needed const date = new Date(timestamp); const now = new Date(); + + // Create today and yesterday date objects for comparison const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const yesterday = new Date(today); yesterday.setDate(yesterday.getDate() - 1); - - const hours = date.getHours().toString().padStart(2, '0'); + + // Create message date object for comparison (without time) + const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate()); + + // Format time in 12-hour format + const hours = date.getHours(); const minutes = date.getMinutes().toString().padStart(2, '0'); + const ampm = hours >= 12 ? 'PM' : 'AM'; + const displayHours = hours % 12 || 12; // Convert to 12-hour format + const timeStr = `${displayHours}:${minutes} ${ampm}`; - if (date >= today) { - return `Today ${hours}:${minutes}`; - } else if (date >= yesterday) { - return `Yesterday ${hours}:${minutes}`; + // Compare dates and return appropriate format + if (messageDate.getTime() === today.getTime()) { + return `Today ${timeStr}`; + } else if (messageDate.getTime() === yesterday.getTime()) { + return `Yesterday ${timeStr}`; } else { + // For older dates, show full date and time const year = date.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); - return `${year}-${month}-${day} ${hours}:${minutes}`; + return `${year}-${month}-${day} ${timeStr}`; } }, getAudioIconClass(message) { diff --git a/main/manager-web/src/components/DeviceItem.vue b/main/manager-web/src/components/DeviceItem.vue index 54685b264..dd80a94cf 100644 --- a/main/manager-web/src/components/DeviceItem.vue +++ b/main/manager-web/src/components/DeviceItem.vue @@ -1,8 +1,14 @@