diff --git a/main/manager-api/src/main/resources/db/changelog/202508291545_add_groq_llm.sql b/main/manager-api/src/main/resources/db/changelog/202508291545_add_groq_llm.sql new file mode 100644 index 000000000..f3d10bd0a --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202508291545_add_groq_llm.sql @@ -0,0 +1,34 @@ +-- Add GroqLLM Provider +DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_LLM_GroqLLM'; +INSERT INTO `ai_model_provider` (`id`, `model_type`, `provider_code`, `name`, `fields`, `sort`, `creator`, `create_date`, `updater`, `update_date`) VALUES +('SYSTEM_LLM_GroqLLM', 'LLM', 'groq', 'Groq LLM', '[{"key":"api_key","label":"API Key","type":"string"},{"key":"model_name","label":"Model Name","type":"string"},{"key":"base_url","label":"Base URL","type":"string"},{"key":"temperature","label":"Temperature","type":"number"},{"key":"max_tokens","label":"Max Tokens","type":"number"},{"key":"top_p","label":"Top P","type":"number"},{"key":"frequency_penalty","label":"Frequency Penalty","type":"number"},{"key":"timeout","label":"Timeout (seconds)","type":"number"},{"key":"max_retries","label":"Max Retries","type":"number"},{"key":"retry_delay","label":"Retry Delay (seconds)","type":"number"}]', 15, 1, NOW(), 1, NOW()); + +-- Add GroqLLM Model Configuration +DELETE FROM `ai_model_config` WHERE id = 'LLM_GroqLLM'; +INSERT INTO `ai_model_config` VALUES ('LLM_GroqLLM', 'LLM', 'GroqLLM', 'Groq LLM', 0, 1, '{"type": "openai", "api_key": "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", "model_name": "openai/gpt-oss-20b", "base_url": "https://api.groq.com/openai/v1", "temperature": 0.7, "max_tokens": 2048, "top_p": 1.0, "frequency_penalty": 0, "timeout": 15, "max_retries": 2, "retry_delay": 1}', NULL, NULL, 16, NULL, NULL, NULL, NULL); + +-- Update GroqLLM Configuration Documentation +UPDATE `ai_model_config` SET +`doc_link` = 'https://console.groq.com/', +`remark` = 'Groq LLM Configuration Guide: +1. Groq is an AI chip company focused on high-performance inference, providing fast LLM inference services +2. Supports various open-source large language models like Llama, Mixtral, etc. +3. Features ultra-low latency inference performance, suitable for real-time conversation scenarios +4. Uses OpenAI-compatible API interface for easy integration +5. Requires API key from Groq official website + +Configuration Parameters: +- api_key: API key obtained from Groq console +- model_name: Model name, e.g., llama3-8b-8192, mixtral-8x7b-32768, etc. +- base_url: Groq API endpoint, typically https://api.groq.com/openai/v1 +- temperature: Controls output randomness (0-2), lower values are more deterministic +- max_tokens: Maximum tokens to generate per request +- top_p: Nucleus sampling parameter controlling output diversity +- frequency_penalty: Frequency penalty to reduce repetitive content +- timeout: Request timeout in seconds, recommended 15s (Groq is fast) +- max_retries: Maximum retry attempts, recommended 2 +- retry_delay: Retry interval in seconds, recommended 1s + +Get API Key: https://console.groq.com/keys +Model List: https://console.groq.com/docs/models +' WHERE `id` = 'LLM_GroqLLM'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/202508291600_add_play_story.sql b/main/manager-api/src/main/resources/db/changelog/202508291600_add_play_story.sql new file mode 100644 index 000000000..d8cde5d1c --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202508291600_add_play_story.sql @@ -0,0 +1,28 @@ +-- Add play_story plugin support +-- This adds play_story to all agents that currently have play_music + +-- 1. Add play_story plugin provider +DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_PLUGIN_STORY'; +INSERT INTO ai_model_provider (id, model_type, provider_code, name, fields, sort, creator, create_date, updater, update_date) +VALUES ('SYSTEM_PLUGIN_STORY', 'Plugin', 'play_story', 'Story Playback', JSON_ARRAY(), 25, 0, NOW(), 0, NOW()); + +-- 2. Add play_story to all agents that have play_music +INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info) +SELECT DISTINCT m.agent_id, 'SYSTEM_PLUGIN_STORY', '{}' +FROM ai_agent_plugin_mapping m +JOIN ai_model_provider p ON p.id = m.plugin_id +WHERE p.provider_code = 'play_music' + AND NOT EXISTS ( + SELECT 1 FROM ai_agent_plugin_mapping m2 + JOIN ai_model_provider p2 ON p2.id = m2.plugin_id + WHERE m2.agent_id = m.agent_id AND p2.provider_code = 'play_story' + ); + +-- 3. Add optional configuration fields for play_story +UPDATE `ai_model_provider` SET +fields = JSON_ARRAY( + JSON_OBJECT('key', 'story_dir', 'type', 'string', 'label', 'Story Directory', 'default', './stories'), + JSON_OBJECT('key', 'story_ext', 'type', 'array', 'label', 'Story File Extensions', 'default', '.mp3;.wav;.p3'), + JSON_OBJECT('key', 'refresh_time', 'type', 'number', 'label', 'Refresh Time (seconds)', 'default', '300') +) +WHERE id = 'SYSTEM_PLUGIN_STORY'; diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index 6142d8901..4d130661d 100755 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -331,3 +331,17 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202508291530_add_amazon_transcribe_streaming.sql + - changeSet: + id: 202508291545 + author: claude + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202508291545_add_groq_llm.sql + - changeSet: + id: 202508291600 + author: claude + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202508291600_add_play_story.sql diff --git a/main/xiaozhi-server/add_indian_news_provider.py b/main/xiaozhi-server/add_indian_news_provider.py new file mode 100644 index 000000000..e922f5a79 --- /dev/null +++ b/main/xiaozhi-server/add_indian_news_provider.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +""" +Add get_indian_news_api provider and map it to agents +""" +import mysql.connector +from mysql.connector import Error + +# Database configuration +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'database': 'railway', + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'ssl_disabled': True, + 'use_unicode': True, + 'charset': 'utf8mb4' +} + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect(**DB_CONFIG) + if connection.is_connected(): + print("Connected to database") + return connection + except Error as e: + print(f"Connection error: {e}") + return None + +def check_existing_news_providers(connection): + """Check what news providers exist""" + cursor = connection.cursor() + + print("=== EXISTING NEWS PROVIDERS ===") + cursor.execute(""" + SELECT id, provider_code, name + FROM ai_model_provider + WHERE provider_code LIKE '%news%' OR name LIKE '%news%' OR name LIKE '%News%' + ORDER BY provider_code + """) + + providers = cursor.fetchall() + + if providers: + for provider in providers: + print(f" {provider[0]} -> {provider[1]} ({provider[2]})") + else: + print(" No news providers found") + + cursor.close() + return providers + +def add_indian_news_provider(connection): + """Add the get_indian_news_api provider""" + cursor = connection.cursor() + + print("\n=== ADDING get_indian_news_api PROVIDER ===") + + # Check if it already exists + cursor.execute(""" + SELECT id FROM ai_model_provider WHERE provider_code = 'get_indian_news_api' + """) + + if cursor.fetchone(): + print("[INFO] get_indian_news_api provider already exists!") + cursor.close() + return True + + try: + # Add the provider + cursor.execute(""" + INSERT INTO ai_model_provider (id, model_type, provider_code, name, fields, sort, creator, create_date, updater, update_date) + VALUES ('SYSTEM_PLUGIN_INDIAN_NEWS', 'Plugin', 'get_indian_news_api', 'Indian News API', JSON_ARRAY(), 35, 0, NOW(), 0, NOW()) + """) + + connection.commit() + print("[SUCCESS] Added get_indian_news_api provider!") + cursor.close() + return True + + except Error as e: + print(f"[ERROR] Failed to add provider: {e}") + connection.rollback() + cursor.close() + return False + +def add_to_agents_with_news(connection): + """Add get_indian_news_api to all agents that have other news plugins""" + cursor = connection.cursor() + + print("\n=== ADDING TO AGENTS ===") + + # Find agents that have news plugins but not indian news + cursor.execute(""" + SELECT DISTINCT a.id, a.agent_name + FROM ai_agent a + JOIN ai_agent_plugin_mapping m ON a.id = m.agent_id + JOIN ai_model_provider p ON p.id = m.plugin_id + WHERE p.provider_code = 'get_news_from_newsnow' + AND NOT EXISTS ( + SELECT 1 FROM ai_agent_plugin_mapping m2 + JOIN ai_model_provider p2 ON p2.id = m2.plugin_id + WHERE m2.agent_id = a.id AND p2.provider_code = 'get_indian_news_api' + ) + """) + + agents = cursor.fetchall() + + if not agents: + print("[INFO] No agents need get_indian_news_api added") + cursor.close() + return + + print(f"Adding get_indian_news_api to {len(agents)} agents:") + + added_count = 0 + for agent_id, agent_name in agents: + try: + cursor.execute(""" + INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info) + VALUES (%s, 'SYSTEM_PLUGIN_INDIAN_NEWS', '{}') + """, (agent_id,)) + + print(f" - {agent_name} ({agent_id})") + added_count += 1 + + except Error as e: + print(f" - ERROR adding to {agent_name}: {e}") + + if added_count > 0: + try: + connection.commit() + print(f"\n[SUCCESS] Added get_indian_news_api to {added_count} agents!") + except Error as e: + connection.rollback() + print(f"\n[ERROR] Failed to commit: {e}") + return False + + cursor.close() + return True + +def verify_complete_setup(connection): + """Verify that all expected functions are now available""" + cursor = connection.cursor() + + print("\n=== FINAL VERIFICATION ===") + + # Check a Cheeko agent + cursor.execute("SELECT id, agent_name FROM ai_agent WHERE agent_name LIKE '%Cheeko%' LIMIT 1") + agent = cursor.fetchone() + + if agent: + agent_id, agent_name = agent + print(f"Checking agent: {agent_name}") + + cursor.execute(""" + SELECT p.provider_code + FROM ai_agent_plugin_mapping m + JOIN ai_model_provider p ON p.id = m.plugin_id + WHERE m.agent_id = %s AND p.model_type = 'Plugin' + ORDER BY p.provider_code + """, (agent_id,)) + + plugins = cursor.fetchall() + available_functions = [plugin[0] for plugin in plugins] + + expected = ['play_music', 'play_story', 'get_weather', 'get_indian_news_api', 'get_news_from_newsnow'] + + print(f"Available functions: {available_functions}") + print(f"\nFunction Status:") + all_present = True + for func in expected: + status = "[OK]" if func in available_functions else "[MISSING]" + print(f" {func}: {status}") + if func not in available_functions: + all_present = False + + if all_present: + print(f"\n[COMPLETE] All expected functions are now available!") + print("The agent should now work with manager-api config just like local config") + else: + print(f"\n[WARNING] Some functions are still missing") + + cursor.close() + +def main(): + connection = connect_to_database() + if not connection: + return + + try: + # 1. Check existing news providers + existing = check_existing_news_providers(connection) + + # 2. Add the missing provider + if add_indian_news_provider(connection): + # 3. Add to agents + add_to_agents_with_news(connection) + + # 4. Final verification + verify_complete_setup(connection) + + print(f"\n[FINAL RESULT]") + print("✅ get_indian_news_api provider added") + print("✅ Plugin mapped to agents with news functionality") + print("✅ All expected functions should now work with manager-api") + print("\nNext steps:") + print("1. Restart manager-api") + print("2. Test both play_story and get_indian_news_api functionality") + + finally: + if connection.is_connected(): + connection.close() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/main/xiaozhi-server/add_missing_indian_news.py b/main/xiaozhi-server/add_missing_indian_news.py new file mode 100644 index 000000000..301063ff2 --- /dev/null +++ b/main/xiaozhi-server/add_missing_indian_news.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +""" +Add missing get_indian_news_api plugin to all agents that have other news/weather plugins +""" +import mysql.connector +from mysql.connector import Error + +# Database configuration +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'database': 'railway', + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'ssl_disabled': True, + 'use_unicode': True, + 'charset': 'utf8mb4' +} + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect(**DB_CONFIG) + if connection.is_connected(): + print("Connected to database") + return connection + except Error as e: + print(f"Connection error: {e}") + return None + +def check_indian_news_provider(connection): + """Check if get_indian_news_api provider exists""" + cursor = connection.cursor() + + cursor.execute(""" + SELECT id, provider_code, name + FROM ai_model_provider + WHERE provider_code = 'get_indian_news_api' OR provider_code LIKE '%indian_news%' + """) + + providers = cursor.fetchall() + cursor.close() + + if providers: + print(f"Found Indian news providers:") + for provider in providers: + print(f" {provider[0]} -> {provider[1]} ({provider[2]})") + return providers[0][0] # Return the ID of the first matching provider + else: + print("No get_indian_news_api provider found!") + return None + +def find_agents_needing_indian_news(connection): + """Find agents that have other news plugins but missing indian news""" + cursor = connection.cursor() + + # Find agents that have get_news_from_newsnow (other news plugin) + cursor.execute(""" + SELECT DISTINCT a.id, a.agent_name + FROM ai_agent a + JOIN ai_agent_plugin_mapping m ON a.id = m.agent_id + JOIN ai_model_provider p ON p.id = m.plugin_id + WHERE p.provider_code = 'get_news_from_newsnow' + """) + + news_agents = cursor.fetchall() + + # Filter out agents that already have indian news + agents_needing_indian_news = [] + + for agent_id, agent_name in news_agents: + cursor.execute(""" + SELECT COUNT(*) + FROM ai_agent_plugin_mapping m + JOIN ai_model_provider p ON p.id = m.plugin_id + WHERE m.agent_id = %s AND p.provider_code = 'get_indian_news_api' + """, (agent_id,)) + + count = cursor.fetchone()[0] + if count == 0: + agents_needing_indian_news.append((agent_id, agent_name)) + + cursor.close() + return agents_needing_indian_news + +def add_indian_news_to_agents(connection, provider_id, agents): + """Add indian news plugin to specified agents""" + cursor = connection.cursor() + + added_count = 0 + + for agent_id, agent_name in agents: + try: + cursor.execute(""" + INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info) + VALUES (%s, %s, '{}') + """, (agent_id, provider_id)) + + print(f"Added get_indian_news_api to {agent_name} ({agent_id})") + added_count += 1 + + except Error as e: + print(f"Error adding to {agent_name}: {e}") + + if added_count > 0: + try: + connection.commit() + print(f"\n[SUCCESS] Added get_indian_news_api to {added_count} agents!") + except Error as e: + connection.rollback() + print(f"\n[ERROR] Failed to commit changes: {e}") + return False + + cursor.close() + return True + +def verify_additions(connection): + """Verify that the additions were successful""" + cursor = connection.cursor() + + print("\n=== VERIFICATION ===") + + # Check agents that now have indian news + cursor.execute(""" + SELECT a.agent_name, COUNT(*) as plugin_count + FROM ai_agent a + JOIN ai_agent_plugin_mapping m ON a.id = m.agent_id + JOIN ai_model_provider p ON p.id = m.plugin_id + WHERE p.provider_code = 'get_indian_news_api' + GROUP BY a.id, a.agent_name + ORDER BY a.agent_name + """) + + agents_with_indian_news = cursor.fetchall() + + if agents_with_indian_news: + print(f"Agents with get_indian_news_api:") + for agent_name, count in agents_with_indian_news: + print(f" - {agent_name}") + else: + print("No agents have get_indian_news_api plugin!") + + cursor.close() + +def main(): + connection = connect_to_database() + if not connection: + return + + try: + print("=== ADDING MISSING get_indian_news_api ===\n") + + # 1. Check if provider exists + provider_id = check_indian_news_provider(connection) + if not provider_id: + print("[ERROR] get_indian_news_api provider not found in database!") + print("You may need to add it first to ai_model_provider table") + return + + # 2. Find agents that need it + agents_needing = find_agents_needing_indian_news(connection) + + if not agents_needing: + print("[INFO] All agents already have get_indian_news_api or no agents have news plugins") + return + + print(f"Found {len(agents_needing)} agents that need get_indian_news_api:") + for agent_id, agent_name in agents_needing: + print(f" - {agent_name} ({agent_id})") + + # 3. Ask for confirmation + response = input(f"\nAdd get_indian_news_api to these {len(agents_needing)} agents? (y/N): ").strip().lower() + + if response == 'y' or response == 'yes': + # 4. Add the mappings + success = add_indian_news_to_agents(connection, provider_id, agents_needing) + + if success: + # 5. Verify + verify_additions(connection) + print(f"\n[COMPLETE] get_indian_news_api has been added to agents!") + print("\nNext steps:") + print("1. Restart manager-api to reload configurations") + print("2. Test get_indian_news_api functionality") + else: + print(f"\n[FAILED] Could not add get_indian_news_api to agents") + else: + print("No changes made.") + + finally: + if connection.is_connected(): + connection.close() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/main/xiaozhi-server/check_database.py b/main/xiaozhi-server/check_database.py new file mode 100644 index 000000000..0be44b18d --- /dev/null +++ b/main/xiaozhi-server/check_database.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +""" +Script to check what's in the Railway MySQL database +""" +import mysql.connector +import json +from mysql.connector import Error + +# Database configuration from application-dev.yml +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'database': 'railway', + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'ssl_disabled': True, + 'use_unicode': True, + 'charset': 'utf8mb4' +} + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect(**DB_CONFIG) + if connection.is_connected(): + print("Successfully connected to Railway MySQL database") + return connection + except Error as e: + print(f"Error connecting to MySQL database: {e}") + return None + +def check_tables(connection): + """Check what tables exist in the database""" + cursor = connection.cursor() + cursor.execute("SHOW TABLES") + tables = cursor.fetchall() + print(f"\nFound {len(tables)} tables:") + for table in tables: + print(f" - {table[0]}") + cursor.close() + return [table[0] for table in tables] + +def check_config_tables(connection): + """Check configuration-related tables""" + cursor = connection.cursor() + + # Check system parameters table + print("\n=== System Parameters ===") + try: + cursor.execute("SELECT param_key, param_value FROM sys_params WHERE param_key LIKE '%log%' OR param_key LIKE '%config%'") + params = cursor.fetchall() + for param in params: + print(f" {param[0]}: {param[1]}") + except Error as e: + print(f"Error querying sys_params: {e}") + + # Check AI model configurations + print("\n=== AI Model Configurations ===") + try: + cursor.execute("SELECT id, model_type, name, config_json FROM ai_model_config WHERE model_type = 'LLM' LIMIT 5") + models = cursor.fetchall() + for model in models: + print(f" ID: {model[0]}") + print(f" Type: {model[1]}") + print(f" Name: {model[2]}") + try: + config = json.loads(model[3]) if model[3] else {} + print(f" Config: {json.dumps(config, indent=4)}") + except: + print(f" Config: {model[3]}") + print(" ---") + except Error as e: + print(f"Error querying ai_model_config: {e}") + + # Check server configurations + print("\n=== Server Configurations ===") + try: + cursor.execute("SELECT * FROM server_config LIMIT 5") + servers = cursor.fetchall() + columns = [desc[0] for desc in cursor.description] + for server in servers: + server_dict = dict(zip(columns, server)) + print(f" Server: {json.dumps(server_dict, indent=2, default=str)}") + except Error as e: + print(f"Error querying server_config: {e}") + + cursor.close() + +def main(): + """Main function to check the database""" + print("Connecting to Railway MySQL database...") + + connection = connect_to_database() + if not connection: + return + + try: + tables = check_tables(connection) + check_config_tables(connection) + + except Error as e: + print(f"Error during database operations: {e}") + + finally: + if connection.is_connected(): + connection.close() + print("\nDatabase connection closed.") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/main/xiaozhi-server/check_database_structure.py b/main/xiaozhi-server/check_database_structure.py new file mode 100644 index 000000000..f89d0ee24 --- /dev/null +++ b/main/xiaozhi-server/check_database_structure.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +""" +Script to check the actual database table structures +""" +import mysql.connector +import json +from mysql.connector import Error + +# Database configuration from application-dev.yml +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'database': 'railway', + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'ssl_disabled': True, + 'use_unicode': True, + 'charset': 'utf8mb4' +} + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect(**DB_CONFIG) + if connection.is_connected(): + print("Successfully connected to Railway MySQL database") + return connection + except Error as e: + print(f"Error connecting to MySQL database: {e}") + return None + +def describe_table(connection, table_name): + """Describe the structure of a table""" + cursor = connection.cursor() + try: + cursor.execute(f"DESCRIBE {table_name}") + columns = cursor.fetchall() + print(f"\n=== Table: {table_name} ===") + for col in columns: + print(f" {col[0]} | {col[1]} | {col[2]} | {col[3]} | {col[4]} | {col[5]}") + return [col[0] for col in columns] + except Error as e: + print(f"Error describing table {table_name}: {e}") + return [] + finally: + cursor.close() + +def check_sys_params(connection): + """Check sys_params table structure and content""" + cursor = connection.cursor() + columns = describe_table(connection, 'sys_params') + + try: + # Get a few sample records + cursor.execute("SELECT * FROM sys_params LIMIT 10") + rows = cursor.fetchall() + print(f"\nSample data from sys_params:") + for row in rows: + row_dict = dict(zip(columns, row)) + print(f" {json.dumps(row_dict, indent=2, default=str)}") + except Error as e: + print(f"Error querying sys_params: {e}") + finally: + cursor.close() + +def check_ai_model_config(connection): + """Check ai_model_config table structure and content""" + cursor = connection.cursor() + columns = describe_table(connection, 'ai_model_config') + + try: + # Get LLM configs + cursor.execute("SELECT * FROM ai_model_config WHERE model_type = 'LLM' LIMIT 5") + rows = cursor.fetchall() + print(f"\nLLM configurations from ai_model_config:") + for row in rows: + row_dict = dict(zip(columns, row)) + print(f" {json.dumps(row_dict, indent=2, default=str)}") + except Error as e: + print(f"Error querying ai_model_config: {e}") + finally: + cursor.close() + +def main(): + """Main function""" + connection = connect_to_database() + if not connection: + return + + try: + # Check key tables + check_sys_params(connection) + check_ai_model_config(connection) + + except Error as e: + print(f"Error during database operations: {e}") + + finally: + if connection.is_connected(): + connection.close() + print("\nDatabase connection closed.") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/main/xiaozhi-server/check_intent_functions.py b/main/xiaozhi-server/check_intent_functions.py new file mode 100644 index 000000000..a0f0f6cee --- /dev/null +++ b/main/xiaozhi-server/check_intent_functions.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +""" +Check how Intent function_call gets its functions list from manager-api +""" +import mysql.connector +import json +from mysql.connector import Error + +# Database configuration +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'database': 'railway', + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'ssl_disabled': True, + 'use_unicode': True, + 'charset': 'utf8mb4' +} + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect(**DB_CONFIG) + if connection.is_connected(): + print("Connected to database") + return connection + except Error as e: + print(f"Connection error: {e}") + return None + +def check_intent_function_call_config(connection): + """Check the Intent function_call configuration""" + cursor = connection.cursor() + + print("=== INTENT FUNCTION_CALL CONFIGURATION ===\n") + + # Check the Intent_function_call config + cursor.execute(""" + SELECT id, model_name, config_json, remark + FROM ai_model_config + WHERE id = 'Intent_function_call' + """) + result = cursor.fetchone() + + if result: + config_id, model_name, config_json, remark = result + print(f"Configuration ID: {config_id}") + print(f"Model Name: {model_name}") + + try: + config = json.loads(config_json) if config_json else {} + print(f"Current Config:") + print(json.dumps(config, indent=2)) + + # Check if functions are defined in config + if 'functions' in config: + functions = config['functions'] + print(f"\nFunctions in config: {functions}") + else: + print("\nNo 'functions' key found in Intent config - uses plugin mappings instead") + + except json.JSONDecodeError as e: + print(f"Error parsing config JSON: {e}") + print(f"Raw config: {config_json}") + + if remark: + print(f"\nRemark: {remark}") + else: + print("Intent_function_call configuration not found!") + return False + + cursor.close() + return True + +def check_how_functions_are_loaded(connection): + """Check how functions are loaded for agents""" + cursor = connection.cursor() + + print("\n=== HOW FUNCTIONS ARE LOADED FOR AGENTS ===\n") + + # Check a specific agent and its plugin mappings + cursor.execute(""" + SELECT a.id, a.agent_name, a.intent_model_id + FROM ai_agent a + WHERE a.agent_name LIKE '%Cheeko%' + LIMIT 1 + """) + agent_result = cursor.fetchone() + + if not agent_result: + print("No Cheeko agent found") + return + + agent_id, agent_name, intent_model = agent_result + print(f"Checking agent: {agent_name} ({agent_id})") + print(f"Intent model: {intent_model}") + + # Get plugins for this agent + print(f"\nPlugins mapped to this agent:") + cursor.execute(""" + SELECT p.id, p.provider_code, p.name, m.param_info + FROM ai_agent_plugin_mapping m + JOIN ai_model_provider p ON p.id = m.plugin_id + WHERE m.agent_id = %s AND p.model_type = 'Plugin' + ORDER BY p.provider_code + """, (agent_id,)) + + plugins = cursor.fetchall() + + if plugins: + available_functions = [] + for plugin in plugins: + provider_id, provider_code, provider_name, param_info = plugin + available_functions.append(provider_code) + print(f" - {provider_code} ({provider_name})") + + print(f"\nAvailable functions for this agent: {available_functions}") + + # Check specifically for our functions + expected_functions = ['play_music', 'play_story', 'get_weather', 'get_indian_news_api', 'get_news_from_newsnow'] + missing_functions = [] + present_functions = [] + + for func in expected_functions: + if func in available_functions: + present_functions.append(func) + else: + missing_functions.append(func) + + print(f"\nFunction Status:") + print(f" Present: {present_functions}") + print(f" Missing: {missing_functions}") + + if missing_functions: + print(f"\n[WARNING] Missing functions: {missing_functions}") + print("These functions won't be available when using manager-api config") + else: + print(f"\n[OK] All expected functions are available!") + + else: + print("No plugin mappings found for this agent") + + cursor.close() + +def check_server_config_generation(connection): + """Check how server config is generated""" + cursor = connection.cursor() + + print("\n=== SERVER CONFIG GENERATION LOGIC ===\n") + + # This is what the server likely does when generating config + print("The server config generation likely works as follows:") + print("1. Gets basic Intent configuration from ai_model_config") + print("2. For each agent request, gets plugins from ai_agent_plugin_mapping") + print("3. Dynamically builds the functions list based on agent's plugins") + print("") + print("This means the 'functions' are not in the Intent config itself,") + print("but are loaded per-agent from the plugin mappings.") + + cursor.close() + +def main(): + connection = connect_to_database() + if not connection: + return + + try: + # Check Intent configuration + if check_intent_function_call_config(connection): + # Check how functions are loaded for agents + check_how_functions_are_loaded(connection) + # Explain server config generation + check_server_config_generation(connection) + + finally: + if connection.is_connected(): + connection.close() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/main/xiaozhi-server/check_log_config.py b/main/xiaozhi-server/check_log_config.py new file mode 100644 index 000000000..69ccedb1f --- /dev/null +++ b/main/xiaozhi-server/check_log_config.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +""" +Script to check and fix log configuration in database +""" +import mysql.connector +import json +from mysql.connector import Error + +# Database configuration +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'database': 'railway', + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'ssl_disabled': True, + 'use_unicode': True, + 'charset': 'utf8mb4' +} + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect(**DB_CONFIG) + if connection.is_connected(): + print("Successfully connected to Railway MySQL database") + return connection + except Error as e: + print(f"Error connecting to MySQL database: {e}") + return None + +def check_log_parameters(connection): + """Check log-related parameters""" + cursor = connection.cursor() + + try: + # Check for log-related parameters + cursor.execute("SELECT id, param_code, param_value FROM sys_params WHERE param_code LIKE '%log%'") + rows = cursor.fetchall() + + print("=== Log-related Parameters ===") + for row in rows: + print(f"ID: {row[0]} | Code: {row[1]} | Value: {row[2]}") + + return rows + except Error as e: + print(f"Error querying log parameters: {e}") + return [] + finally: + cursor.close() + +def fix_log_level_if_needed(connection): + """Fix log level if it's corrupted""" + cursor = connection.cursor() + + try: + # Check if there's a corrupted log_level parameter + cursor.execute("SELECT id, param_code, param_value FROM sys_params WHERE param_value LIKE '%http%' AND param_value LIKE '%ota%'") + corrupted_rows = cursor.fetchall() + + if corrupted_rows: + print(f"\nFound {len(corrupted_rows)} corrupted parameters:") + for row in corrupted_rows: + print(f" ID: {row[0]} | Code: {row[1]} | Value: {row[2]}") + + # Fix the corrupted log level + for row in corrupted_rows: + if 'log' in row[1].lower(): # If it's a log-related parameter + print(f"\nFixing parameter {row[1]} (ID: {row[0]})") + cursor.execute( + "UPDATE sys_params SET param_value = %s, update_date = NOW() WHERE id = %s", + ("INFO", row[0]) + ) + connection.commit() + print(f"✅ Fixed: {row[1]} set to 'INFO'") + else: + print("\nNo corrupted log parameters found.") + + except Error as e: + print(f"Error fixing log parameters: {e}") + connection.rollback() + finally: + cursor.close() + +def check_all_params_with_urls(connection): + """Check all parameters that might have URLs incorrectly""" + cursor = connection.cursor() + + try: + cursor.execute("SELECT id, param_code, param_value FROM sys_params WHERE param_value LIKE '%http%'") + rows = cursor.fetchall() + + print(f"\n=== All Parameters with HTTP URLs ===") + for row in rows: + print(f"ID: {row[0]} | Code: {row[1]} | Value: {row[2]}") + + except Error as e: + print(f"Error querying URL parameters: {e}") + finally: + cursor.close() + +def main(): + """Main function""" + connection = connect_to_database() + if not connection: + return + + try: + check_log_parameters(connection) + check_all_params_with_urls(connection) + fix_log_level_if_needed(connection) + + # Check again after fix + print("\n" + "="*50) + print("After fix:") + check_log_parameters(connection) + + except Error as e: + print(f"Error during database operations: {e}") + + finally: + if connection.is_connected(): + connection.close() + print("\nDatabase connection closed.") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/main/xiaozhi-server/check_plugin_mappings.py b/main/xiaozhi-server/check_plugin_mappings.py new file mode 100644 index 000000000..22b20bb6a --- /dev/null +++ b/main/xiaozhi-server/check_plugin_mappings.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Script to check plugin mappings and agent configurations in the database +This will help us understand how play_music is configured and what's needed for play_story +""" +import mysql.connector +import json +import sys +from mysql.connector import Error + +# Set UTF-8 encoding for Windows console +if sys.platform == "win32": + import os + os.system("chcp 65001 >nul 2>&1") + +def safe_print(text): + """Safely print text with UTF-8 encoding""" + try: + print(text) + except UnicodeEncodeError: + print(text.encode('utf-8', errors='replace').decode('utf-8')) + +# Database configuration from application-dev.yml +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'database': 'railway', + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'ssl_disabled': True, + 'use_unicode': True, + 'charset': 'utf8mb4' +} + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect(**DB_CONFIG) + if connection.is_connected(): + print("Successfully connected to Railway MySQL database") + return connection + except Error as e: + print(f"Error connecting to MySQL database: {e}") + return None + +def check_plugin_providers(connection): + """Check available plugin providers""" + cursor = connection.cursor() + print("\n=== Plugin Providers ===") + try: + cursor.execute(""" + SELECT id, provider_code, name, fields, sort + FROM ai_model_provider + WHERE model_type = 'Plugin' + ORDER BY sort + """) + providers = cursor.fetchall() + + print(f"Found {len(providers)} plugin providers:") + for provider in providers: + safe_print(f" ID: {provider[0]}") + safe_print(f" Code: {provider[1]}") + safe_print(f" Name: {provider[2]}") + safe_print(f" Sort: {provider[4]}") + try: + fields = json.loads(provider[3]) if provider[3] else [] + if fields: + safe_print(f" Fields: {json.dumps(fields, indent=4)}") + else: + safe_print(" Fields: (none)") + except: + safe_print(f" Fields: {provider[3]}") + safe_print(" ---") + except Error as e: + print(f"Error querying plugin providers: {e}") + cursor.close() + +def check_function_call_config(connection): + """Check function_call intent configuration""" + cursor = connection.cursor() + print("\n=== Function Call Configuration ===") + try: + cursor.execute(""" + SELECT id, name, config_json, remark + FROM ai_model_config + WHERE id = 'Intent_function_call' + """) + result = cursor.fetchone() + + if result: + print(f"ID: {result[0]}") + print(f"Name: {result[1]}") + try: + config = json.loads(result[2]) if result[2] else {} + print(f"Config: {json.dumps(config, indent=2)}") + except: + print(f"Config: {result[2]}") + print(f"Remark: {result[3]}") + else: + print("No function_call configuration found!") + except Error as e: + print(f"Error querying function_call config: {e}") + cursor.close() + +def check_agents(connection): + """Check available agents""" + cursor = connection.cursor() + print("\n=== Available Agents ===") + try: + cursor.execute(""" + SELECT id, name, intent_provider, creator, create_date + FROM ai_agent + ORDER BY create_date DESC + LIMIT 10 + """) + agents = cursor.fetchall() + + print(f"Found {len(agents)} recent agents:") + for agent in agents: + print(f" ID: {agent[0]}") + print(f" Name: {agent[1]}") + print(f" Intent Provider: {agent[2]}") + print(f" Creator: {agent[3]}") + print(f" Created: {agent[4]}") + print(" ---") + except Error as e: + print(f"Error querying agents: {e}") + cursor.close() + return agents + +def check_plugin_mappings(connection, agents): + """Check plugin mappings for agents""" + cursor = connection.cursor() + print("\n=== Agent Plugin Mappings ===") + + for agent in agents: + agent_id = agent[0] + agent_name = agent[1] + + print(f"\nAgent: {agent_name} ({agent_id})") + try: + cursor.execute(""" + SELECT m.plugin_id, p.provider_code, p.name, m.param_info + FROM ai_agent_plugin_mapping m + JOIN ai_model_provider p ON p.id = m.plugin_id + WHERE m.agent_id = %s + ORDER BY p.sort + """, (agent_id,)) + mappings = cursor.fetchall() + + if mappings: + print(f" Plugins ({len(mappings)}):") + for mapping in mappings: + print(f" - {mapping[1]} ({mapping[2]})") + if mapping[3]: + try: + params = json.loads(mapping[3]) + if params: + print(f" Params: {json.dumps(params, indent=6)}") + except: + print(f" Params: {mapping[3]}") + else: + print(" No plugin mappings found") + except Error as e: + print(f" Error querying plugin mappings for {agent_name}: {e}") + + cursor.close() + +def check_play_story_status(connection): + """Check if play_story plugin exists""" + cursor = connection.cursor() + print("\n=== Play Story Status Check ===") + + # Check if play_story provider exists + try: + cursor.execute(""" + SELECT id, provider_code, name + FROM ai_model_provider + WHERE provider_code = 'play_story' OR id LIKE '%STORY%' + """) + story_providers = cursor.fetchall() + + if story_providers: + print("✓ Play Story provider found:") + for provider in story_providers: + print(f" - {provider[0]}: {provider[1]} ({provider[2]})") + else: + print("✗ Play Story provider NOT found") + except Error as e: + print(f"Error checking play_story provider: {e}") + + # Check if any agents have play_story mapped + try: + cursor.execute(""" + SELECT a.name, a.id, m.plugin_id + FROM ai_agent a + JOIN ai_agent_plugin_mapping m ON a.id = m.agent_id + JOIN ai_model_provider p ON p.id = m.plugin_id + WHERE p.provider_code = 'play_story' + """) + story_mappings = cursor.fetchall() + + if story_mappings: + print("✓ Agents with play_story mapping:") + for mapping in story_mappings: + print(f" - {mapping[0]} ({mapping[1]})") + else: + print("✗ No agents have play_story mapping") + except Error as e: + print(f"Error checking play_story mappings: {e}") + + cursor.close() + +def generate_sql_script(): + """Generate the SQL script to add play_story support""" + timestamp = "202508291600" # Current timestamp + + sql_content = f"""-- Add play_story plugin support to all agents +-- Generated automatically to match the pattern of existing plugins like play_music + +-- 1. Add play_story plugin provider (if not exists) +DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_PLUGIN_STORY'; +INSERT INTO ai_model_provider (id, model_type, provider_code, name, fields, sort, creator, create_date, updater, update_date) +VALUES ('SYSTEM_PLUGIN_STORY', 'Plugin', 'play_story', '服务器故事播放', JSON_ARRAY(), 25, 0, NOW(), 0, NOW()); + +-- 2. Add play_story plugin to all existing agents that have play_music +-- This ensures consistency - if an agent can play music, it should also be able to play stories +INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info) +SELECT DISTINCT m.agent_id, 'SYSTEM_PLUGIN_STORY', '{{}}' +FROM ai_agent_plugin_mapping m +JOIN ai_model_provider p ON p.id = m.plugin_id +WHERE p.provider_code = 'play_music' + AND NOT EXISTS ( + SELECT 1 FROM ai_agent_plugin_mapping m2 + JOIN ai_model_provider p2 ON p2.id = m2.plugin_id + WHERE m2.agent_id = m.agent_id AND p2.provider_code = 'play_story' + ); + +-- 3. Update documentation +UPDATE `ai_model_provider` SET +`fields` = JSON_ARRAY( + JSON_OBJECT('key', 'story_dir', 'type', 'string', 'label', '故事文件存放路径', 'default', './stories'), + JSON_OBJECT('key', 'story_ext', 'type', 'array', 'label', '故事文件类型', 'default', '.mp3;.wav;.p3'), + JSON_OBJECT('key', 'refresh_time', 'type', 'number', 'label', '故事列表刷新间隔(秒)', 'default', '300') +) +WHERE id = 'SYSTEM_PLUGIN_STORY'; +""" + + # Write SQL file + sql_file_path = f"d:\\cheekofinal\\xiaozhi-esp32-server\\main\\manager-api\\src\\main\\resources\\db\\changelog\\{timestamp}_add_play_story.sql" + with open(sql_file_path, 'w', encoding='utf-8') as f: + f.write(sql_content) + + # Generate changelog entry + changelog_entry = f""" - changeSet: + id: {timestamp} + author: claude + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/{timestamp}_add_play_story.sql""" + + print(f"\n=== Generated Files ===") + print(f"SQL Script: {sql_file_path}") + print("\nAdd this to db.changelog-master.yaml:") + print(changelog_entry) + + return sql_file_path + +def main(): + """Main function to check plugin mappings and generate SQL""" + print("Checking plugin mappings and agent configurations...") + + connection = connect_to_database() + if not connection: + return + + try: + # Check current state + check_plugin_providers(connection) + check_function_call_config(connection) + agents = check_agents(connection) + check_plugin_mappings(connection, agents) + check_play_story_status(connection) + + # Generate SQL script + sql_file = generate_sql_script() + + print(f"\n=== Summary ===") + print("1. Check the current plugin mappings above") + print("2. Run the generated SQL script to add play_story support") + print("3. Update db.changelog-master.yaml with the new changeset") + print("4. Restart the manager-api to apply the changes") + + except Error as e: + print(f"Error during database operations: {e}") + + finally: + if connection.is_connected(): + connection.close() + print("\nDatabase connection closed.") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/main/xiaozhi-server/check_tts_config.py b/main/xiaozhi-server/check_tts_config.py new file mode 100644 index 000000000..48c184ce7 --- /dev/null +++ b/main/xiaozhi-server/check_tts_config.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +""" +Check and update TTS EdgeTTS voice configuration in database +""" +import mysql.connector +import json +from mysql.connector import Error + +# Database configuration +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'database': 'railway', + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'ssl_disabled': True, + 'use_unicode': True, + 'charset': 'utf8mb4' +} + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect(**DB_CONFIG) + if connection.is_connected(): + print("Connected to database") + return connection + except Error as e: + print(f"Connection error: {e}") + return None + +def check_tts_configurations(connection): + """Check TTS configurations in database""" + cursor = connection.cursor() + + print("=== TTS CONFIGURATION CHECK ===\n") + + # First, check available columns + try: + cursor.execute("DESCRIBE ai_model_config") + columns = cursor.fetchall() + config_columns = [col[0] for col in columns] + print(f"Available ai_model_config columns: {config_columns}") + + # Use correct column names + name_col = 'name' if 'name' in config_columns else ('model_name' if 'model_name' in config_columns else 'id') + + # 1. Check ai_model_config for TTS entries + print("\n1. TTS Model Configurations:") + cursor.execute(f""" + SELECT id, model_type, {name_col}, config_json + FROM ai_model_config + WHERE model_type = 'TTS' + ORDER BY id + """) + except Error as e: + print(f"Error checking columns: {e}") + return [] + tts_configs = cursor.fetchall() + + edgetts_configs = [] + + if tts_configs: + for config in tts_configs: + print(f" ID: {config[0]}") + print(f" Name: {config[2]}") + try: + config_json = json.loads(config[3]) if config[3] else {} + print(f" Config: {json.dumps(config_json, indent=4)}") + + # Check if this is EdgeTTS and has voice config + if config_json.get('type') == 'edge' or 'edge' in config[0].lower(): + voice = config_json.get('voice', 'Not specified') + print(f" >>> EdgeTTS Voice: {voice}") + if voice == 'en-GB-MaisieNeural': + print(f" >>> NEEDS UPDATE: Found en-GB-MaisieNeural") + edgetts_configs.append({ + 'id': config[0], + 'name': config[2], + 'config': config_json, + 'needs_update': True + }) + elif voice == 'en-US-JennyNeural': + print(f" >>> OK: Already using en-US-JennyNeural") + edgetts_configs.append({ + 'id': config[0], + 'name': config[2], + 'config': config_json, + 'needs_update': False + }) + else: + edgetts_configs.append({ + 'id': config[0], + 'name': config[2], + 'config': config_json, + 'needs_update': False, + 'current_voice': voice + }) + + except json.JSONDecodeError: + print(f" Config: {config[3]} (Invalid JSON)") + print(" ---") + else: + print(" No TTS configurations found") + + # 2. Check ai_model_provider for TTS providers + print("\n2. TTS Model Providers:") + try: + cursor.execute("DESCRIBE ai_model_provider") + provider_columns = [col[0] for col in cursor.fetchall()] + provider_name_col = 'name' if 'name' in provider_columns else ('provider_name' if 'provider_name' in provider_columns else 'id') + + cursor.execute(f""" + SELECT id, provider_code, {provider_name_col}, fields + FROM ai_model_provider + WHERE model_type = 'TTS' + ORDER BY provider_code + """) + except Error as e: + print(f"Error checking provider columns: {e}") + cursor.execute(""" + SELECT id, provider_code, fields + FROM ai_model_provider + WHERE model_type = 'TTS' + ORDER BY provider_code + """) + tts_providers = cursor.fetchall() + + if tts_providers: + for provider in tts_providers: + print(f" ID: {provider[0]}") + print(f" Code: {provider[1]}") + if len(provider) > 2: + print(f" Name: {provider[2]}") + fields_idx = 3 + else: + fields_idx = 2 + + if len(provider) > fields_idx: + try: + fields = json.loads(provider[fields_idx]) if provider[fields_idx] else [] + if fields: + print(f" Fields: {json.dumps(fields, indent=4)}") + else: + print(" Fields: (none)") + except: + print(f" Fields: {provider[fields_idx]}") + print(" ---") + else: + print(" No TTS providers found") + + # 3. Check agents and their TTS assignments + print("\n3. Agent TTS Assignments:") + cursor.execute(""" + SELECT a.id, a.agent_name, a.tts_model_id, a.tts_voice_id + FROM ai_agent a + WHERE a.tts_model_id IS NOT NULL OR a.tts_voice_id IS NOT NULL + ORDER BY a.agent_name + """) + agent_tts = cursor.fetchall() + + if agent_tts: + for agent in agent_tts: + print(f" Agent: {agent[1]} ({agent[0]})") + print(f" TTS Model: {agent[2] if agent[2] else 'Not set'}") + print(f" TTS Voice: {agent[3] if agent[3] else 'Not set'}") + print(" ---") + else: + print(" No agents with TTS assignments found") + + cursor.close() + return edgetts_configs + +def update_edgetts_voice(connection, edgetts_configs): + """Update EdgeTTS voice configurations""" + cursor = connection.cursor() + + print("\n=== UPDATING EDGETTS VOICE ===\n") + + updates_made = 0 + + for config_info in edgetts_configs: + if config_info.get('needs_update', False): + config_id = config_info['id'] + current_config = config_info['config'] + + # Update the voice + current_config['voice'] = 'en-US-JennyNeural' + + # Update in database + try: + cursor.execute(""" + UPDATE ai_model_config + SET config_json = %s + WHERE id = %s + """, (json.dumps(current_config), config_id)) + + print(f"[UPDATED] {config_id}: voice changed to en-US-JennyNeural") + updates_made += 1 + + except Error as e: + print(f"[ERROR] Failed to update {config_id}: {e}") + + if updates_made > 0: + try: + connection.commit() + print(f"\n[SUCCESS] {updates_made} TTS configurations updated successfully!") + except Error as e: + connection.rollback() + print(f"\n[ERROR] Failed to commit changes: {e}") + else: + print("\n[INFO] No updates needed - all EdgeTTS configs already use correct voice") + + cursor.close() + return updates_made + +def main(): + connection = connect_to_database() + if not connection: + return + + try: + # Check current TTS configurations + edgetts_configs = check_tts_configurations(connection) + + # Update if needed + if edgetts_configs: + needs_update = any(config.get('needs_update', False) for config in edgetts_configs) + + if needs_update: + print("\n" + "="*50) + print("Found EdgeTTS configurations that need updating!") + print("="*50) + + response = input("Do you want to update them? (y/N): ").strip().lower() + if response == 'y' or response == 'yes': + updates_made = update_edgetts_voice(connection, edgetts_configs) + + if updates_made > 0: + print("\n[NEXT STEPS]") + print("1. Restart the manager-api to reload configurations") + print("2. Test TTS with the new en-US-JennyNeural voice") + else: + print("\nNo changes made.") + else: + print("\n[INFO] All EdgeTTS configurations are already using the correct voice!") + else: + print("\n[INFO] No EdgeTTS configurations found in database") + + finally: + if connection.is_connected(): + connection.close() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index d4013834b..cb5041114 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -1135,9 +1135,12 @@ class ConnectionHandler: # Clear ASR audio buffer to prevent processing leftover audio if hasattr(self, 'asr_audio'): self.asr_audio.clear() - # Reset VAD recording start time for 10-second timeout + # Reset VAD recording start time for timeout if hasattr(self, 'vad_recording_start_time'): delattr(self, 'vad_recording_start_time') + # Reset timeout flag + if hasattr(self, '_timeout_triggered'): + self._timeout_triggered = False # Clear ASR audio queue for this specific connection only if hasattr(self, 'asr_audio_queue'): # Empty the queue by getting all items without blocking diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index 4fa07e544..6fc30a132 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -74,15 +74,38 @@ class ASRProviderBase(ABC): else: logger.bind(tag=TAG).debug("No recording start time found") - if len(conn.asr_audio) > 0 and recording_start_time: + if len(conn.asr_audio) > 0 and recording_start_time and not conn.client_voice_stop: current_time = time.time() recording_duration = current_time - recording_start_time max_recording_time = conn.config.get('max_recording_time', 10.0) logger.bind(tag=TAG).debug(f"Recording duration: {recording_duration:.2f}s, max: {max_recording_time}s, audio chunks: {len(conn.asr_audio)}") if recording_duration >= max_recording_time: - logger.bind(tag=TAG).info(f"Maximum recording time reached ({recording_duration:.2f}s) - forcing voice stop") - conn.client_voice_stop = True - have_voice = False # Force stop current voice detection + # Use a timeout flag to prevent multiple timeout messages + if not hasattr(conn, '_timeout_triggered') or not conn._timeout_triggered: + logger.bind(tag=TAG).info(f"Maximum recording time reached ({recording_duration:.2f}s) - forcing voice stop") + conn._timeout_triggered = True + + # Force voice stop using the same logic as VAD silence detection + conn.client_voice_stop = True + have_voice = False + + # Process any accumulated audio before resetting (same as normal VAD flow) + if len(conn.asr_audio) > 20: + asr_audio_task = conn.asr_audio.copy() + conn.asr_audio.clear() + conn.reset_vad_states() + conn._timeout_triggered = False # Reset for next session + # Process the accumulated audio + asyncio.create_task(self.handle_voice_stop(conn, asr_audio_task)) + else: + # No significant audio to process, just reset everything + conn.reset_vad_states() + conn._timeout_triggered = False # Reset for next session + + return # Exit early like VAD does + else: + # Already triggered timeout, skip this audio chunk + return # Debug logging if not hasattr(conn, '_asr_log_counter'): diff --git a/main/xiaozhi-server/core/utils/llm.py b/main/xiaozhi-server/core/utils/llm.py index 90c921af2..8329fecb8 100644 --- a/main/xiaozhi-server/core/utils/llm.py +++ b/main/xiaozhi-server/core/utils/llm.py @@ -13,11 +13,48 @@ logger = setup_logging() def create_instance(class_name, *args, **kwargs): # Create LLM instance - if os.path.exists(os.path.join('core', 'providers', 'llm', class_name, f'{class_name}.py')): + + # Try relative path first (original behavior) + provider_path = os.path.join('core', 'providers', 'llm', class_name, f'{class_name}.py') + + # If relative path doesn't work, try absolute path from project root + if not os.path.exists(provider_path): + provider_path = os.path.join(project_root, 'core', 'providers', 'llm', class_name, f'{class_name}.py') + + # Debug logging + logger.bind(tag=__name__).info(f"Looking for LLM provider: {class_name}") + logger.bind(tag=__name__).info(f"Current working directory: {os.getcwd()}") + logger.bind(tag=__name__).info(f"Project root: {project_root}") + logger.bind(tag=__name__).info(f"Provider path: {provider_path}") + logger.bind(tag=__name__).info(f"Provider exists: {os.path.exists(provider_path)}") + + if os.path.exists(provider_path): lib_name = f'core.providers.llm.{class_name}.{class_name}' + logger.bind(tag=__name__).info(f"Loading module: {lib_name}") + if lib_name not in sys.modules: - sys.modules[lib_name] = importlib.import_module(f'{lib_name}') + try: + sys.modules[lib_name] = importlib.import_module(f'{lib_name}') + logger.bind(tag=__name__).info(f"Successfully imported: {lib_name}") + except ImportError as e: + logger.bind(tag=__name__).error(f"Failed to import {lib_name}: {e}") + raise ValueError(f"Failed to import LLM provider {class_name}: {e}") + return sys.modules[lib_name].LLMProvider(*args, **kwargs) - - raise ValueError( - f"Unsupported LLM type: {class_name}, please check if the type in this configuration is set correctly") + + # Enhanced error message with debugging info + cwd = os.getcwd() + available_providers = [] + llm_dir = os.path.join(project_root, 'core', 'providers', 'llm') + if os.path.exists(llm_dir): + available_providers = [d for d in os.listdir(llm_dir) + if os.path.isdir(os.path.join(llm_dir, d)) and d != '__pycache__'] + + error_msg = (f"Unsupported LLM type: {class_name}\n" + f"Current working directory: {cwd}\n" + f"Project root: {project_root}\n" + f"Searched path: {provider_path}\n" + f"Available providers: {available_providers}") + + logger.bind(tag=__name__).error(error_msg) + raise ValueError(error_msg) diff --git a/main/xiaozhi-server/debug_llm_loading.py b/main/xiaozhi-server/debug_llm_loading.py new file mode 100644 index 000000000..c4ab73e9b --- /dev/null +++ b/main/xiaozhi-server/debug_llm_loading.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +""" +Debug script to check LLM provider loading +""" +import os +import sys + +def debug_llm_loading(): + """Debug the LLM loading mechanism""" + print("=== LLM Loading Debug ===") + + # Check current working directory + cwd = os.getcwd() + print(f"Current working directory: {cwd}") + + # Check the path that the code is looking for + class_name = "openai" + provider_path = os.path.join('core', 'providers', 'llm', class_name, f'{class_name}.py') + absolute_provider_path = os.path.abspath(provider_path) + + print(f"Looking for provider at: {provider_path}") + print(f"Absolute path: {absolute_provider_path}") + print(f"Path exists: {os.path.exists(provider_path)}") + + # Check if the core directory exists + core_path = os.path.join('core') + print(f"Core directory exists: {os.path.exists(core_path)}") + + if os.path.exists(core_path): + providers_path = os.path.join('core', 'providers') + print(f"Providers directory exists: {os.path.exists(providers_path)}") + + if os.path.exists(providers_path): + llm_path = os.path.join('core', 'providers', 'llm') + print(f"LLM directory exists: {os.path.exists(llm_path)}") + + if os.path.exists(llm_path): + openai_dir = os.path.join('core', 'providers', 'llm', 'openai') + print(f"OpenAI directory exists: {os.path.exists(openai_dir)}") + + if os.path.exists(openai_dir): + openai_file = os.path.join('core', 'providers', 'llm', 'openai', 'openai.py') + print(f"OpenAI file exists: {os.path.exists(openai_file)}") + else: + # List what's in the llm directory + try: + llm_contents = os.listdir(llm_path) + print(f"Contents of {llm_path}: {llm_contents}") + except Exception as e: + print(f"Error listing {llm_path}: {e}") + + # Check Python path + print(f"Python path: {sys.path[:3]}...") # Show first 3 entries + + # Try to see if we can import the module directly + try: + import core.providers.llm.openai.openai + print("✅ Direct import of openai module successful") + except ImportError as e: + print(f"❌ Direct import failed: {e}") + +if __name__ == "__main__": + debug_llm_loading() \ No newline at end of file diff --git a/main/xiaozhi-server/fix_database_config.py b/main/xiaozhi-server/fix_database_config.py new file mode 100644 index 000000000..77301409c --- /dev/null +++ b/main/xiaozhi-server/fix_database_config.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +""" +Script to fix corrupted database configuration +""" +import json +import httpx + +# Configuration +API_URL = "http://139.59.7.72:8002/toy" +SECRET = "66122e75-3b2a-45d7-a082-0f0894529348" + +def get_current_config(): + """Get current configuration from database""" + headers = { + "Authorization": f"Bearer {SECRET}", + "Content-Type": "application/json" + } + + response = httpx.post(f"{API_URL}/config/server-base", headers=headers) + response.raise_for_status() + return response.json()["data"] + +def update_config(config_data): + """Update configuration in database""" + headers = { + "Authorization": f"Bearer {SECRET}", + "Content-Type": "application/json" + } + + # Assuming there's an update endpoint - we might need to find the correct one + response = httpx.put(f"{API_URL}/config/server-base", headers=headers, json=config_data) + response.raise_for_status() + return response.json() + +def fix_config(): + """Fix the corrupted configuration""" + print("Getting current config...") + config = get_current_config() + + # Fix the corrupted log_level + if "log" in config and config["log"].get("log_level") == "http://139.59.7.72:8002/toy/ota/": + print("Fixing corrupted log_level...") + config["log"]["log_level"] = "INFO" + + # Ensure LLM configuration is correct (it seems to be already correct) + if "LLM" in config and "Groq LLM" in config["LLM"]: + llm_config = config["LLM"]["Groq LLM"] + print(f"Current LLM config: {json.dumps(llm_config, indent=2)}") + + # Add missing fields that might be needed + llm_config.update({ + "timeout": 15, + "max_retries": 2, + "retry_delay": 1 + }) + + print("Fixed configuration:") + print(json.dumps(config, indent=2)) + + # For now, just print the config to see what needs to be fixed + # We'll need to find the correct update endpoint + return config + +if __name__ == "__main__": + try: + fixed_config = fix_config() + print("\nConfiguration has been analyzed. The main issue is the corrupted log_level.") + print("You may need to use the admin interface to update this configuration.") + except Exception as e: + print(f"Error: {e}") \ No newline at end of file diff --git a/main/xiaozhi-server/fix_log_config.py b/main/xiaozhi-server/fix_log_config.py new file mode 100644 index 000000000..0dc2757c1 --- /dev/null +++ b/main/xiaozhi-server/fix_log_config.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +""" +Script to fix the corrupted log.log_level parameter +""" +import mysql.connector +from mysql.connector import Error + +# Database configuration +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'database': 'railway', + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'ssl_disabled': True, + 'use_unicode': True, + 'charset': 'utf8mb4' +} + +def fix_log_level(): + """Fix the corrupted log.log_level parameter""" + connection = None + try: + connection = mysql.connector.connect(**DB_CONFIG) + cursor = connection.cursor() + + # Check current value + cursor.execute("SELECT param_value FROM sys_params WHERE param_code = 'log.log_level'") + current_value = cursor.fetchone() + print(f"Current log.log_level value: {current_value[0] if current_value else 'NOT FOUND'}") + + # Fix the value + cursor.execute( + "UPDATE sys_params SET param_value = %s, update_date = NOW() WHERE param_code = %s", + ("INFO", "log.log_level") + ) + connection.commit() + + # Verify the fix + cursor.execute("SELECT param_value FROM sys_params WHERE param_code = 'log.log_level'") + new_value = cursor.fetchone() + print(f"Fixed log.log_level value: {new_value[0] if new_value else 'NOT FOUND'}") + + print("SUCCESS: log.log_level has been fixed!") + + except Error as e: + print(f"Error: {e}") + if connection: + connection.rollback() + finally: + if connection and connection.is_connected(): + connection.close() + +if __name__ == "__main__": + fix_log_level() \ No newline at end of file diff --git a/main/xiaozhi-server/simple_check.py b/main/xiaozhi-server/simple_check.py new file mode 100644 index 000000000..81a200e09 --- /dev/null +++ b/main/xiaozhi-server/simple_check.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +""" +Simple script to check plugin status and generate SQL for play_story +""" +import mysql.connector +import json +from mysql.connector import Error + +# Database configuration from application-dev.yml +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'database': 'railway', + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'ssl_disabled': True, + 'use_unicode': True, + 'charset': 'utf8mb4' +} + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect(**DB_CONFIG) + if connection.is_connected(): + print("Connected to database") + return connection + except Error as e: + print(f"Connection error: {e}") + return None + +def check_current_state(connection): + """Check current plugin and agent state""" + cursor = connection.cursor() + + # Check plugin providers + print("\n=== Plugin Providers ===") + cursor.execute("SELECT id, provider_code FROM ai_model_provider WHERE model_type = 'Plugin'") + providers = cursor.fetchall() + + has_play_music = False + has_play_story = False + + for provider in providers: + print(f" {provider[0]} -> {provider[1]}") + if provider[1] == 'play_music': + has_play_music = True + elif provider[1] == 'play_story': + has_play_story = True + + print(f" play_music found: {has_play_music}") + print(f" play_story found: {has_play_story}") + + # Check agents + print("\n=== Agents ===") + try: + cursor.execute("DESCRIBE ai_agent") + columns = cursor.fetchall() + agent_columns = [col[0] for col in columns] + print(f" Available columns: {agent_columns}") + + # Try to get agents with available columns + if 'name' in agent_columns: + cursor.execute("SELECT id, name FROM ai_agent LIMIT 5") + elif 'agent_name' in agent_columns: + cursor.execute("SELECT id, agent_name FROM ai_agent LIMIT 5") + else: + cursor.execute("SELECT id FROM ai_agent LIMIT 5") + agents = cursor.fetchall() + + for agent in agents: + if len(agent) > 1: + print(f" {agent[0]} -> {agent[1]}") + else: + print(f" {agent[0]}") + except Error as e: + print(f" Error checking agents: {e}") + + # Check plugin mappings for play_music + if has_play_music: + print("\n=== Agents with play_music ===") + name_column = 'name' if 'name' in agent_columns else ('agent_name' if 'agent_name' in agent_columns else 'id') + cursor.execute(f""" + SELECT a.id, a.{name_column} + FROM ai_agent a + JOIN ai_agent_plugin_mapping m ON a.id = m.agent_id + JOIN ai_model_provider p ON p.id = m.plugin_id + WHERE p.provider_code = 'play_music' + """) + music_agents = cursor.fetchall() + + for agent in music_agents: + print(f" {agent[0]} -> {agent[1]}") + + print(f"\nFound {len(music_agents)} agents with play_music") + return len(music_agents), has_play_story + + cursor.close() + return 0, has_play_story + +def generate_sql_files(): + """Generate the SQL files""" + timestamp = "202508291600" + + # SQL script content + sql_content = """-- Add play_story plugin support +-- This adds play_story to all agents that currently have play_music + +-- 1. Add play_story plugin provider +DELETE FROM `ai_model_provider` WHERE id = 'SYSTEM_PLUGIN_STORY'; +INSERT INTO ai_model_provider (id, model_type, provider_code, name, fields, sort, creator, create_date, updater, update_date) +VALUES ('SYSTEM_PLUGIN_STORY', 'Plugin', 'play_story', 'Story Playback', JSON_ARRAY(), 25, 0, NOW(), 0, NOW()); + +-- 2. Add play_story to all agents that have play_music +INSERT INTO ai_agent_plugin_mapping (agent_id, plugin_id, param_info) +SELECT DISTINCT m.agent_id, 'SYSTEM_PLUGIN_STORY', '{}' +FROM ai_agent_plugin_mapping m +JOIN ai_model_provider p ON p.id = m.plugin_id +WHERE p.provider_code = 'play_music' + AND NOT EXISTS ( + SELECT 1 FROM ai_agent_plugin_mapping m2 + JOIN ai_model_provider p2 ON p2.id = m2.plugin_id + WHERE m2.agent_id = m.agent_id AND p2.provider_code = 'play_story' + ); + +-- 3. Add optional configuration fields for play_story +UPDATE `ai_model_provider` SET +fields = JSON_ARRAY( + JSON_OBJECT('key', 'story_dir', 'type', 'string', 'label', 'Story Directory', 'default', './stories'), + JSON_OBJECT('key', 'story_ext', 'type', 'array', 'label', 'Story File Extensions', 'default', '.mp3;.wav;.p3'), + JSON_OBJECT('key', 'refresh_time', 'type', 'number', 'label', 'Refresh Time (seconds)', 'default', '300') +) +WHERE id = 'SYSTEM_PLUGIN_STORY'; +""" + + # Write SQL file + sql_file = f"D:\\cheekofinal\\xiaozhi-esp32-server\\main\\manager-api\\src\\main\\resources\\db\\changelog\\{timestamp}_add_play_story.sql" + with open(sql_file, 'w', encoding='utf-8') as f: + f.write(sql_content) + + print(f"\nSQL file created: {sql_file}") + + # Changelog entry + changelog_entry = f""" - changeSet: + id: {timestamp} + author: claude + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/{timestamp}_add_play_story.sql""" + + print("\nAdd this to db.changelog-master.yaml:") + print(changelog_entry) + + return sql_file + +def main(): + connection = connect_to_database() + if not connection: + return + + try: + music_agents_count, has_story = check_current_state(connection) + + if has_story: + print("\nplay_story already exists in database!") + else: + print(f"\nGenerating SQL to add play_story to {music_agents_count} agents...") + sql_file = generate_sql_files() + print(f"\nNext steps:") + print(f"1. Add the changeset entry to db.changelog-master.yaml") + print(f"2. Restart manager-api to apply changes") + print(f"3. Test play_story functionality") + + finally: + if connection.is_connected(): + connection.close() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/main/xiaozhi-server/simple_intent_check.py b/main/xiaozhi-server/simple_intent_check.py new file mode 100644 index 000000000..2fa85e55c --- /dev/null +++ b/main/xiaozhi-server/simple_intent_check.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +""" +Simple check of Intent function_call and agent plugin mappings +""" +import mysql.connector +import json +from mysql.connector import Error + +# Database configuration +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'database': 'railway', + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'ssl_disabled': True, + 'use_unicode': True, + 'charset': 'utf8mb4' +} + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect(**DB_CONFIG) + if connection.is_connected(): + print("Connected to database") + return connection + except Error as e: + print(f"Connection error: {e}") + return None + +def main(): + connection = connect_to_database() + if not connection: + return + + cursor = connection.cursor() + + try: + print("=== INTENT CONFIGURATION ===") + + # Check Intent_function_call config + cursor.execute("SELECT config_json FROM ai_model_config WHERE id = 'Intent_function_call'") + result = cursor.fetchone() + + if result: + config = json.loads(result[0]) + print(f"Intent config: {config}") + + if 'functions' in config: + print(f"Functions in config: {config['functions']}") + else: + print("No functions in Intent config - uses plugin mappings") + + print("\n=== AGENT PLUGIN MAPPINGS ===") + + # Get a Cheeko agent + cursor.execute("SELECT id, agent_name FROM ai_agent WHERE agent_name LIKE '%Cheeko%' LIMIT 1") + agent = cursor.fetchone() + + if agent: + agent_id, agent_name = agent + print(f"Agent: {agent_name} ({agent_id})") + + # Get plugins for this agent + cursor.execute(""" + SELECT p.provider_code + FROM ai_agent_plugin_mapping m + JOIN ai_model_provider p ON p.id = m.plugin_id + WHERE m.agent_id = %s AND p.model_type = 'Plugin' + ORDER BY p.provider_code + """, (agent_id,)) + + plugins = cursor.fetchall() + available_functions = [plugin[0] for plugin in plugins] + print(f"Available functions: {available_functions}") + + # Check specific functions + expected = ['play_music', 'play_story', 'get_weather', 'get_indian_news_api', 'get_news_from_newsnow'] + + print(f"\nFunction Status:") + for func in expected: + status = "OK" if func in available_functions else "MISSING" + print(f" {func}: {status}") + + missing = [f for f in expected if f not in available_functions] + if missing: + print(f"\nMissing functions: {missing}") + print("These need to be added as plugin mappings to the agent") + else: + print(f"\nAll functions are available via plugin mappings!") + + print("\n=== EXPLANATION ===") + print("Server config shows: {'type': 'function_call'}") + print("Local config shows: functions list") + print("") + print("The new architecture:") + print("1. Intent config only has 'type': 'function_call'") + print("2. Functions come from ai_agent_plugin_mapping per agent") + print("3. Server dynamically builds function list for each agent") + print("4. This allows different agents to have different functions") + + finally: + if connection.is_connected(): + connection.close() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/main/xiaozhi-server/update_database_config.py b/main/xiaozhi-server/update_database_config.py new file mode 100644 index 000000000..e2c4fe3d3 --- /dev/null +++ b/main/xiaozhi-server/update_database_config.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +""" +Script to update database configuration with fixes +""" +import json +import httpx + +# Configuration +API_URL = "http://139.59.7.72:8002/toy" +SECRET = "66122e75-3b2a-45d7-a082-0f0894529348" + +def update_config(): + """Update the database configuration with fixes""" + headers = { + "Authorization": f"Bearer {SECRET}", + "Content-Type": "application/json" + } + + # The main fix: correct the corrupted log_level + config_fixes = { + "log": { + "log_level": "INFO" + } + } + + print("Updating database configuration...") + print(f"Fixing log_level to: INFO") + + response = httpx.put(f"{API_URL}/config/server-base", headers=headers, json=config_fixes) + response.raise_for_status() + + result = response.json() + print(f"Update result: {json.dumps(result, indent=2)}") + + return result + +if __name__ == "__main__": + try: + result = update_config() + print("\nConfiguration updated successfully!") + print("The corrupted log_level has been fixed.") + print("You can now try running the application again.") + except Exception as e: + print(f"Error updating configuration: {e}") + import traceback + traceback.print_exc() \ No newline at end of file diff --git a/main/xiaozhi-server/update_edge_tts_voice.py b/main/xiaozhi-server/update_edge_tts_voice.py new file mode 100644 index 000000000..7d73bc470 --- /dev/null +++ b/main/xiaozhi-server/update_edge_tts_voice.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +""" +Update EdgeTTS voice from en-GB-MaisieNeural to en-US-JennyNeural in database +""" +import mysql.connector +import json +from mysql.connector import Error + +# Database configuration +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'database': 'railway', + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'ssl_disabled': True, + 'use_unicode': True, + 'charset': 'utf8mb4' +} + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect(**DB_CONFIG) + if connection.is_connected(): + print("Connected to database") + return connection + except Error as e: + print(f"Connection error: {e}") + return None + +def update_edge_tts_voice(connection): + """Update EdgeTTS voice configuration""" + cursor = connection.cursor() + + print("=== UPDATING EDGETTS VOICE ===\n") + + # 1. First, check the current TTS_EdgeTTS configuration + cursor.execute(""" + SELECT id, model_name, config_json + FROM ai_model_config + WHERE id = 'TTS_EdgeTTS' + """) + result = cursor.fetchone() + + if not result: + print("[ERROR] TTS_EdgeTTS configuration not found!") + return False + + config_id, model_name, config_json = result + print(f"Found TTS EdgeTTS configuration: {config_id} - {model_name}") + + try: + config = json.loads(config_json) if config_json else {} + current_voice = config.get('voice', 'Not specified') + print(f"Current voice: {current_voice}") + + if current_voice == 'en-US-JennyNeural': + print("[INFO] Voice is already set to en-US-JennyNeural - no update needed!") + return True + elif current_voice == 'en-GB-MaisieNeural': + print("[UPDATE] Changing voice from en-GB-MaisieNeural to en-US-JennyNeural") + + # Update the voice + config['voice'] = 'en-US-JennyNeural' + + # Update in database + cursor.execute(""" + UPDATE ai_model_config + SET config_json = %s + WHERE id = %s + """, (json.dumps(config), config_id)) + + connection.commit() + print("[SUCCESS] EdgeTTS voice updated successfully!") + return True + else: + print(f"[INFO] Current voice is '{current_voice}' - updating to en-US-JennyNeural") + config['voice'] = 'en-US-JennyNeural' + + cursor.execute(""" + UPDATE ai_model_config + SET config_json = %s + WHERE id = %s + """, (json.dumps(config), config_id)) + + connection.commit() + print("[SUCCESS] EdgeTTS voice updated successfully!") + return True + + except json.JSONDecodeError as e: + print(f"[ERROR] Invalid JSON in config: {e}") + return False + except Error as e: + print(f"[ERROR] Database update failed: {e}") + connection.rollback() + return False + + finally: + cursor.close() + +def verify_update(connection): + """Verify the update was successful""" + cursor = connection.cursor() + + print("\n=== VERIFICATION ===") + cursor.execute(""" + SELECT config_json + FROM ai_model_config + WHERE id = 'TTS_EdgeTTS' + """) + result = cursor.fetchone() + + if result: + try: + config = json.loads(result[0]) + voice = config.get('voice', 'Not found') + print(f"Updated voice setting: {voice}") + + if voice == 'en-US-JennyNeural': + print("[VERIFIED] Voice successfully updated to en-US-JennyNeural!") + return True + else: + print(f"[ERROR] Voice is still '{voice}' - update may have failed") + return False + except: + print("[ERROR] Could not parse updated configuration") + return False + else: + print("[ERROR] Could not find TTS_EdgeTTS configuration for verification") + return False + + cursor.close() + +def main(): + connection = connect_to_database() + if not connection: + return + + try: + # Update the configuration + success = update_edge_tts_voice(connection) + + if success: + # Verify the update + verified = verify_update(connection) + + if verified: + print("\n[COMPLETE] EdgeTTS voice has been successfully updated!") + print("\nNext steps:") + print("1. Restart the manager-api to reload the configuration") + print("2. Test TTS functionality with the new en-US-JennyNeural voice") + print("3. The xiaozhi-server should now use the updated voice from the database") + else: + print("\n[WARNING] Update completed but verification failed") + else: + print("\n[FAILED] Could not update EdgeTTS voice configuration") + + finally: + if connection.is_connected(): + connection.close() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/main/xiaozhi-server/verify_play_story.py b/main/xiaozhi-server/verify_play_story.py new file mode 100644 index 000000000..c8b4bfaea --- /dev/null +++ b/main/xiaozhi-server/verify_play_story.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +""" +Verify that play_story is properly configured for all agents +""" +import mysql.connector +from mysql.connector import Error + +# Database configuration +DB_CONFIG = { + 'host': 'nozomi.proxy.rlwy.net', + 'port': 25037, + 'database': 'railway', + 'user': 'root', + 'password': 'OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm', + 'ssl_disabled': True, + 'use_unicode': True, + 'charset': 'utf8mb4' +} + +def connect_to_database(): + """Connect to the Railway MySQL database""" + try: + connection = mysql.connector.connect(**DB_CONFIG) + if connection.is_connected(): + print("Connected to database") + return connection + except Error as e: + print(f"Connection error: {e}") + return None + +def verify_play_story_setup(connection): + """Verify play_story setup""" + cursor = connection.cursor() + + print("=== PLAY_STORY VERIFICATION ===\n") + + # 1. Check play_story provider + print("1. Plugin Provider Check:") + cursor.execute(""" + SELECT id, provider_code, name, fields + FROM ai_model_provider + WHERE provider_code = 'play_story' + """) + story_provider = cursor.fetchone() + + if story_provider: + print(f" [OK] Provider found: {story_provider[0]} -> {story_provider[1]}") + print(f" Name: {story_provider[2]}") + print(f" Has fields: {'Yes' if story_provider[3] else 'No'}") + else: + print(" [ERROR] play_story provider NOT found!") + return False + + # 2. Check agents with play_story + print("\n2. Agents with play_story:") + cursor.execute(""" + SELECT a.id, a.agent_name, m.param_info + FROM ai_agent a + JOIN ai_agent_plugin_mapping m ON a.id = m.agent_id + JOIN ai_model_provider p ON p.id = m.plugin_id + WHERE p.provider_code = 'play_story' + ORDER BY a.agent_name + """) + story_agents = cursor.fetchall() + + if story_agents: + print(f" [OK] Found {len(story_agents)} agents with play_story:") + for agent in story_agents: + print(f" - {agent[1]} ({agent[0]})") + else: + print(" [ERROR] No agents have play_story mapping!") + return False + + # 3. Check agents with play_music + print("\n3. Agents with play_music:") + cursor.execute(""" + SELECT a.id, a.agent_name + FROM ai_agent a + JOIN ai_agent_plugin_mapping m ON a.id = m.agent_id + JOIN ai_model_provider p ON p.id = m.plugin_id + WHERE p.provider_code = 'play_music' + ORDER BY a.agent_name + """) + music_agents = cursor.fetchall() + + music_agent_ids = {agent[0] for agent in music_agents} + story_agent_ids = {agent[0] for agent in story_agents} + + print(f" Found {len(music_agents)} agents with play_music:") + for agent in music_agents: + has_story = agent[0] in story_agent_ids + status = "[OK]" if has_story else "[MISSING]" + print(f" - {agent[1]} ({agent[0]}) {status} {'has play_story' if has_story else 'missing play_story'}") + + # 4. Summary + print(f"\n=== SUMMARY ===") + print(f"[OK] play_story provider: EXISTS") + print(f"[OK] Agents with play_music: {len(music_agents)}") + print(f"[OK] Agents with play_story: {len(story_agents)}") + + missing_story = music_agent_ids - story_agent_ids + if missing_story: + print(f"[ERROR] Agents missing play_story: {len(missing_story)}") + print(" These agents have play_music but not play_story:") + for agent_id in missing_story: + agent_name = next((a[1] for a in music_agents if a[0] == agent_id), "Unknown") + print(f" - {agent_name} ({agent_id})") + return False + else: + print("[OK] All agents with play_music also have play_story!") + return True + + cursor.close() + +def main(): + connection = connect_to_database() + if not connection: + return + + try: + success = verify_play_story_setup(connection) + + if success: + print("\n[SUCCESS] play_story is properly configured!") + print("\nNow you can test play_story functionality with manager-api config.") + else: + print("\n[ISSUE] play_story setup is incomplete!") + print("You may need to restart the manager-api or run the SQL script manually.") + + finally: + if connection.is_connected(): + connection.close() + +if __name__ == "__main__": + main() \ No newline at end of file