From c1cf912446796a35ac62632f1cdd4acd83251d70 Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Sat, 30 Aug 2025 14:56:39 +0530 Subject: [PATCH] updated story plugin add to default template --- check_story_function_mapping.py | 379 ++++++++++++++++++ check_sys_params_structure.py | 271 +++++++++++++ fix_default_agent_template.py | 366 +++++++++++++++++ fix_intent_functions.py | 265 ++++++++++++ fix_trigger_and_verify.py | 293 ++++++++++++++ .../agent/service/impl/AgentServiceImpl.java | 6 +- .../plugins_func/functions/play_story.py | 14 +- rebuild_manager_api.sh | 50 +++ simple_story_check.py | 243 +++++++++++ verify_all_agents_story.py | 327 +++++++++++++++ 10 files changed, 2206 insertions(+), 8 deletions(-) create mode 100644 check_story_function_mapping.py create mode 100644 check_sys_params_structure.py create mode 100644 fix_default_agent_template.py create mode 100644 fix_intent_functions.py create mode 100644 fix_trigger_and_verify.py create mode 100644 rebuild_manager_api.sh create mode 100644 simple_story_check.py create mode 100644 verify_all_agents_story.py diff --git a/check_story_function_mapping.py b/check_story_function_mapping.py new file mode 100644 index 000000000..f3b634ca7 --- /dev/null +++ b/check_story_function_mapping.py @@ -0,0 +1,379 @@ +#!/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 new file mode 100644 index 000000000..6a777bf47 --- /dev/null +++ b/check_sys_params_structure.py @@ -0,0 +1,271 @@ +#!/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/fix_default_agent_template.py b/fix_default_agent_template.py new file mode 100644 index 000000000..f05ef544d --- /dev/null +++ b/fix_default_agent_template.py @@ -0,0 +1,366 @@ +#!/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 new file mode 100644 index 000000000..852a9d86f --- /dev/null +++ b/fix_intent_functions.py @@ -0,0 +1,265 @@ +#!/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_trigger_and_verify.py b/fix_trigger_and_verify.py new file mode 100644 index 000000000..078b19ffd --- /dev/null +++ b/fix_trigger_and_verify.py @@ -0,0 +1,293 @@ +#!/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/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 4f5681e28..fdda81834 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 @@ -390,9 +390,9 @@ public class AgentServiceImpl extends BaseServiceImpl imp // 设置默认插件 List toInsert = new ArrayList<>(); - // 播放音乐、查天气、查新闻 - String[] pluginIds = new String[] { "SYSTEM_PLUGIN_MUSIC", "SYSTEM_PLUGIN_WEATHER", - "SYSTEM_PLUGIN_NEWS_NEWSNOW" }; + // 播放音乐、播放故事、查天气、查新闻 + String[] pluginIds = new String[] { "SYSTEM_PLUGIN_MUSIC", "SYSTEM_PLUGIN_STORY", + "SYSTEM_PLUGIN_WEATHER", "SYSTEM_PLUGIN_NEWS_NEWSNOW" }; for (String pluginId : pluginIds) { ModelProviderDTO provider = modelProviderService.getById(pluginId); if (provider == null) { diff --git a/main/xiaozhi-server/plugins_func/functions/play_story.py b/main/xiaozhi-server/plugins_func/functions/play_story.py index 87266139a..ea726a5be 100644 --- a/main/xiaozhi-server/plugins_func/functions/play_story.py +++ b/main/xiaozhi-server/plugins_func/functions/play_story.py @@ -1155,16 +1155,20 @@ def initialize_story_handler(conn): STORY_CACHE["story_dir"] = os.path.abspath( STORY_CACHE["story_config"].get("story_dir", "./stories") ) - STORY_CACHE["story_ext"] = STORY_CACHE["story_config"].get( - "story_ext", (".mp3", ".wav", ".p3") + story_ext_config = STORY_CACHE["story_config"].get( + "story_ext", ".mp3;.wav;.p3" ) - STORY_CACHE["refresh_time"] = STORY_CACHE["story_config"].get( + if isinstance(story_ext_config, str): + STORY_CACHE["story_ext"] = tuple(ext.strip() for ext in story_ext_config.split(';')) + else: + STORY_CACHE["story_ext"] = story_ext_config + STORY_CACHE["refresh_time"] = float(STORY_CACHE["story_config"].get( "refresh_time", 300 # Refresh every 5 minutes - ) + )) else: STORY_CACHE["story_dir"] = os.path.abspath("./stories") STORY_CACHE["story_ext"] = (".mp3", ".wav", ".p3") - STORY_CACHE["refresh_time"] = 300 + STORY_CACHE["refresh_time"] = 300.0 # Get story files organized by category STORY_CACHE["story_files_by_category"], STORY_CACHE["all_story_files"] = get_story_files( diff --git a/rebuild_manager_api.sh b/rebuild_manager_api.sh new file mode 100644 index 000000000..675bd3ac2 --- /dev/null +++ b/rebuild_manager_api.sh @@ -0,0 +1,50 @@ +#!/bin/bash + +echo "================================================" +echo "Rebuilding and Restarting Manager-API" +echo "================================================" + +# Navigate to manager-api directory +cd main/manager-api + +# Check if Maven is installed +if ! command -v mvn &> /dev/null; then + echo "Maven is not installed. Please install Maven first." + exit 1 +fi + +# Clean and build the project +echo "Building manager-api with Maven..." +mvn clean package -DskipTests + +if [ $? -ne 0 ]; then + echo "Build failed!" + exit 1 +fi + +echo "Build successful!" + +# Check if PM2 is available +if command -v pm2 &> /dev/null; then + echo "Restarting manager-api with PM2..." + pm2 restart manager-api + + # Show the status + pm2 status manager-api + + # Show recent logs + echo "" + echo "Recent logs:" + pm2 logs manager-api --lines 20 --nostream +else + echo "PM2 not found. You'll need to restart manager-api manually." + echo "" + echo "If running with Java directly, use:" + echo " java -jar target/manager-api-*.jar" +fi + +echo "" +echo "================================================" +echo "Manager-API rebuild complete!" +echo "SYSTEM_PLUGIN_STORY is now included in default plugins" +echo "================================================" \ No newline at end of file diff --git a/simple_story_check.py b/simple_story_check.py new file mode 100644 index 000000000..e1be2bb10 --- /dev/null +++ b/simple_story_check.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +""" +Simple script to check and fix Story Playback function mapping +""" + +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_story_plugin_exists(connection): + """Check if Story Playback plugin exists""" + cursor = connection.cursor() + try: + cursor.execute(""" + SELECT id, provider_code, name + FROM ai_model_provider + WHERE id = 'SYSTEM_PLUGIN_STORY' + """) + + result = cursor.fetchone() + if result: + plugin_id, provider_code, name = result + print(f"[OK] Story Playback plugin exists: {plugin_id}") + print(f" Provider code: {provider_code}") + return True + else: + print(f"[ERROR] Story Playback plugin not found!") + return False + + except Error as e: + print(f"Error checking story plugin: {e}") + return False + finally: + cursor.close() + +def check_intent_function_configuration(connection): + """Check Intent function call configuration""" + cursor = connection.cursor() + try: + 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"[OK] Intent function call config found: {config_id}") + + try: + fields_json = json.loads(fields) + + # Find functions field + functions_value = None + for field in fields_json: + if field.get('key') == 'functions': + functions_value = field.get('default', '') + break + + if functions_value: + print(f"Current functions: {functions_value}") + + if 'play_story' in functions_value.lower(): + print("[OK] play_story found in Intent functions!") + return True, config_id, fields_json + else: + print("[MISSING] play_story NOT found in Intent functions!") + return False, config_id, fields_json + else: + print("[ERROR] No functions field found in Intent config!") + return False, config_id, None + + except json.JSONDecodeError: + print("[ERROR] Could not parse Intent configuration JSON") + return False, config_id, None + + else: + print("[ERROR] Intent function call configuration not found!") + return False, None, None + + except Error as e: + print(f"Error checking Intent config: {e}") + return False, None, None + finally: + cursor.close() + +def fix_intent_functions(connection, config_id, fields_json): + """Add play_story to Intent functions if missing""" + cursor = connection.cursor() + try: + # Find and update the functions field + for i, field in enumerate(fields_json): + if field.get('key') == 'functions': + current_functions = field.get('default', '') + + # Add play_story if not present + 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' + + fields_json[i]['default'] = 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(f"[FIXED] Added play_story to Intent functions!") + print(f"Updated functions: {updated_functions}") + return True + + except Error as e: + print(f"Error fixing Intent functions: {e}") + connection.rollback() + return False + finally: + cursor.close() + +def check_agent_story_mappings(connection): + """Check which agents have Story Playback""" + cursor = connection.cursor() + try: + cursor.execute(""" + SELECT + a.id, + a.agent_name, + CASE WHEN apm.plugin_id IS NOT NULL THEN 'YES' ELSE 'NO' END as has_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' + ORDER BY a.agent_name + """) + + results = cursor.fetchall() + + total = len(results) + with_story = len([r for r in results if r[2] == 'YES']) + + print(f"\nAgent Story Playback Status:") + print(f"Total agents: {total}") + print(f"With Story Playback: {with_story}") + + if with_story < total: + print(f"Missing Story Playback:") + for agent_id, agent_name, has_story in results: + if has_story == 'NO': + print(f" - {agent_name} (ID: {agent_id})") + else: + print("[OK] All agents have Story Playback!") + + return with_story == total + + except Error as e: + print(f"Error checking agent mappings: {e}") + return False + finally: + cursor.close() + +def main(): + print("Story Playback Function Check") + print("=" * 50) + + connection = connect_to_database() + if not connection: + return + + try: + # 1. Check if Story plugin exists + print("\n1. Checking Story Playback Plugin...") + story_exists = check_story_plugin_exists(connection) + + # 2. Check Intent function configuration + print("\n2. Checking Intent Function Configuration...") + has_play_story, config_id, fields_json = check_intent_function_configuration(connection) + + # 3. Fix Intent functions if needed + if not has_play_story and config_id and fields_json: + print("\n3. Fixing Intent Function Configuration...") + fix_intent_functions(connection, config_id, fields_json) + elif has_play_story: + print("\n3. Intent Configuration - OK, no fix needed") + + # 4. Check agent mappings + print("\n4. Checking Agent Story Playback Mappings...") + all_agents_have_story = check_agent_story_mappings(connection) + + # Summary + print(f"\n{'='*50}") + print("SUMMARY") + print('='*50) + + if story_exists: + print("[✓] Story Playback plugin exists in database") + else: + print("[✗] Story Playback plugin missing") + + if has_play_story: + print("[✓] play_story configured in Intent functions") + else: + print("[✗] play_story missing from Intent functions") + + if all_agents_have_story: + print("[✓] All agents have Story Playback mapped") + else: + print("[✗] Some agents missing Story Playback") + + finally: + connection.close() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/verify_all_agents_story.py b/verify_all_agents_story.py new file mode 100644 index 000000000..00dc9f908 --- /dev/null +++ b/verify_all_agents_story.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python3 +""" +Verify all existing agents have Story Playback and check for issues +""" + +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_all_agents_story_status(connection): + """Check if all agents have Story Playback""" + cursor = connection.cursor() + try: + print("\n1. Checking ALL Agents for Story Playback...") + print("=" * 60) + + # Get all agents with their Story Playback status + cursor.execute(""" + SELECT + a.id, + a.agent_name, + a.agent_code, + a.created_at, + CASE + WHEN apm_story.plugin_id IS NOT NULL THEN 'YES' + ELSE 'NO' + END as has_story_playback, + apm_story.param_info as story_params + FROM ai_agent a + LEFT JOIN ai_agent_plugin_mapping apm_story + ON a.id = apm_story.agent_id + AND apm_story.plugin_id = 'SYSTEM_PLUGIN_STORY' + ORDER BY a.created_at DESC + """) + + agents = cursor.fetchall() + + print(f"Total agents in database: {len(agents)}\n") + + agents_with_story = 0 + agents_without_story = [] + + for agent in agents: + agent_id, agent_name, agent_code, created_at, has_story, story_params = agent + + if has_story == 'YES': + agents_with_story += 1 + status = "[OK]" + else: + agents_without_story.append((agent_id, agent_name)) + status = "[MISSING]" + + print(f"{status} {agent_name or agent_code} (ID: {agent_id[:8]}...)") + print(f" Created: {created_at}") + print(f" Story Playback: {has_story}") + if story_params: + try: + params = json.loads(story_params) + print(f" Params: {params}") + except: + print(f" Params: {story_params[:50]}...") + print() + + print(f"\nSUMMARY:") + print(f"Agents WITH Story Playback: {agents_with_story}") + print(f"Agents WITHOUT Story Playback: {len(agents_without_story)}") + + return agents_without_story + + except Error as e: + print(f"Error checking agents: {e}") + return [] + finally: + cursor.close() + +def fix_agents_without_story(connection, agents_without_story): + """Add Story Playback to agents that don't have it""" + if not agents_without_story: + print("\nAll agents already have Story Playback!") + return True + + cursor = connection.cursor() + try: + print(f"\n2. Fixing {len(agents_without_story)} agents without Story Playback...") + print("=" * 60) + + param_info = { + "story_dir": "./stories", + "story_ext": ".mp3;.wav;.m4a", + "refresh_time": "300" + } + + fixed_count = 0 + for agent_id, agent_name in agents_without_story: + try: + # Check if mapping already exists (shouldn't, but double-check) + cursor.execute(""" + SELECT id FROM ai_agent_plugin_mapping + WHERE agent_id = %s AND plugin_id = 'SYSTEM_PLUGIN_STORY' + """, (agent_id,)) + + if cursor.fetchone(): + print(f"Mapping already exists for {agent_name}, skipping...") + continue + + # Add Story Playback + 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"[FIXED] Added Story Playback to: {agent_name}") + fixed_count += 1 + + except Error as e: + print(f"[ERROR] Failed to fix {agent_name}: {e}") + + connection.commit() + print(f"\nFixed {fixed_count} agents!") + return True + + except Error as e: + print(f"Error fixing agents: {e}") + connection.rollback() + return False + finally: + cursor.close() + +def check_duplicate_agent_issues(connection): + """Check for duplicate agent names or codes that might cause the error""" + cursor = connection.cursor() + try: + print("\n3. Checking for Duplicate Agent Issues...") + print("=" * 60) + + print("\nThe error message suggests: 'Record already exists in database'") + print("This usually means duplicate agent_name or agent_code\n") + + # Check for duplicate agent names + cursor.execute(""" + SELECT agent_name, COUNT(*) as count + FROM ai_agent + WHERE agent_name IS NOT NULL + GROUP BY agent_name + HAVING COUNT(*) > 1 + """) + + duplicate_names = cursor.fetchall() + + if duplicate_names: + print("Found duplicate agent names:") + for name, count in duplicate_names: + print(f" - '{name}' appears {count} times") + else: + print("No duplicate agent names found") + + # Check for duplicate agent codes + cursor.execute(""" + SELECT agent_code, COUNT(*) as count + FROM ai_agent + WHERE agent_code IS NOT NULL + GROUP BY agent_code + HAVING COUNT(*) > 1 + """) + + duplicate_codes = cursor.fetchall() + + if duplicate_codes: + print("\nFound duplicate agent codes:") + for code, count in duplicate_codes: + print(f" - '{code}' appears {count} times") + else: + print("No duplicate agent codes found") + + # Check unique constraints + cursor.execute(""" + SELECT + CONSTRAINT_NAME, + COLUMN_NAME + FROM information_schema.KEY_COLUMN_USAGE + WHERE TABLE_SCHEMA = 'railway' + AND TABLE_NAME = 'ai_agent' + AND CONSTRAINT_NAME != 'PRIMARY' + """) + + constraints = cursor.fetchall() + + if constraints: + print("\nUnique constraints on ai_agent table:") + for constraint_name, column_name in constraints: + print(f" - {constraint_name} on column: {column_name}") + + # Get recent agents to see naming pattern + cursor.execute(""" + SELECT agent_name, agent_code, created_at + FROM ai_agent + ORDER BY created_at DESC + LIMIT 5 + """) + + recent_agents = cursor.fetchall() + + print("\nMost recent agents (to check naming pattern):") + for name, code, created in recent_agents: + print(f" - Name: '{name}', Code: '{code}', Created: {created}") + + print("\nRECOMMENDATION:") + print("When creating a new agent, ensure:") + print("1. The agent_name is unique") + print("2. The agent_code is unique") + print("3. Try adding a timestamp or random suffix to make it unique") + + except Error as e: + print(f"Error checking duplicates: {e}") + finally: + cursor.close() + +def check_all_plugins_for_agents(connection): + """Check what plugins each agent has""" + cursor = connection.cursor() + try: + print("\n4. Checking All Plugins for Each Agent...") + print("=" * 60) + + cursor.execute(""" + SELECT + a.agent_name, + GROUP_CONCAT( + CASE + WHEN apm.plugin_id = 'SYSTEM_PLUGIN_STORY' THEN 'Story' + WHEN apm.plugin_id = 'SYSTEM_PLUGIN_MUSIC' THEN 'Music' + WHEN apm.plugin_id = 'SYSTEM_PLUGIN_WEATHER' THEN 'Weather' + WHEN apm.plugin_id LIKE '%NEWS%' THEN 'News' + ELSE SUBSTRING(apm.plugin_id, 15) + END + ORDER BY apm.plugin_id + SEPARATOR ', ' + ) as plugins + FROM ai_agent a + LEFT JOIN ai_agent_plugin_mapping apm ON a.id = apm.agent_id + GROUP BY a.id, a.agent_name + ORDER BY a.created_at DESC + """) + + results = cursor.fetchall() + + print("Agent Plugin Summary:") + for agent_name, plugins in results: + if plugins: + if 'Story' in plugins: + story_status = "[Has Story]" + else: + story_status = "[NO STORY!]" + print(f"{story_status} {agent_name}: {plugins}") + else: + print(f"[NO PLUGINS] {agent_name}: No plugins configured") + + except Error as e: + print(f"Error checking plugins: {e}") + finally: + cursor.close() + +def main(): + print("Comprehensive Agent Story Playback Verification") + print("=" * 70) + + connection = connect_to_database() + if not connection: + return + + try: + # 1. Check all agents for Story Playback + agents_without_story = check_all_agents_story_status(connection) + + # 2. Fix agents without Story Playback + if agents_without_story: + fix_agents_without_story(connection, agents_without_story) + + # 3. Check for duplicate issues + check_duplicate_agent_issues(connection) + + # 4. Check all plugins + check_all_plugins_for_agents(connection) + + # Final verification + print(f"\n{'='*70}") + print("FINAL STATUS") + print('='*70) + + if not agents_without_story: + print("[SUCCESS] All agents have Story Playback!") + else: + print(f"[FIXED] Added Story Playback to {len(agents_without_story)} agents") + + print("\nRegarding the error when creating new agents:") + print("Error: 'Record already exists in database'") + print("This means you're trying to create an agent with a name or code") + print("that already exists. Use a unique name/code for new agents.") + + finally: + connection.close() + +if __name__ == "__main__": + main() \ No newline at end of file