From 54f65d844e55ff02a6f0bf1ddf3c38c012f517d4 Mon Sep 17 00:00:00 2001 From: karthikeyareddy183 Date: Mon, 8 Sep 2025 18:35:06 +0530 Subject: [PATCH 01/12] Semantic search implemented --- main/xiaozhi-server/index_music.py | 428 ++++++++++++++++++ .../plugins_func/functions/play_music.py | 95 +++- .../utils/semantic_music_search.py | 340 ++++++++++++++ main/xiaozhi-server/requirements.txt | 6 +- 4 files changed, 857 insertions(+), 12 deletions(-) create mode 100644 main/xiaozhi-server/index_music.py create mode 100644 main/xiaozhi-server/plugins_func/utils/semantic_music_search.py diff --git a/main/xiaozhi-server/index_music.py b/main/xiaozhi-server/index_music.py new file mode 100644 index 000000000..b0c0164fd --- /dev/null +++ b/main/xiaozhi-server/index_music.py @@ -0,0 +1,428 @@ +#!/usr/bin/env python3 +""" +Music Metadata Indexing Script for Semantic Search +Run this script to index all music metadata into Qdrant vector database +Usage: python index_music.py [--clear] [--verify] +""" + +import os +import sys +import json +import time +import argparse +import logging +from pathlib import Path +from typing import Dict, List +from dataclasses import dataclass, asdict + +# Add project root to path +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from qdrant_client import QdrantClient, models +from sentence_transformers import SentenceTransformer +import hashlib +from ruamel.yaml import YAML + +# Setup logging +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s' +) +logger = logging.getLogger(__name__) + +@dataclass +class IndexingStats: + """Statistics for indexing operation""" + total_languages: int = 0 + total_songs: int = 0 + songs_indexed: int = 0 + songs_failed: int = 0 + time_taken: float = 0 + languages_processed: List[str] = None + + def __post_init__(self): + if self.languages_processed is None: + self.languages_processed = [] + +class MusicIndexer: + """Handles indexing of music metadata into Qdrant""" + + def __init__(self, config_path: str = "data/.config.yaml"): + """Initialize the indexer with configuration""" + self.config = self._load_config(config_path) + self.stats = IndexingStats() + + # Get semantic search config + self.semantic_config = self.config.get('semantic_search', {}) + if not self.semantic_config.get('enabled', False): + logger.warning("Semantic search is disabled in configuration!") + + # Qdrant settings + self.qdrant_url = self.semantic_config.get('qdrant_url') + self.qdrant_api_key = self.semantic_config.get('qdrant_api_key') + self.collection_name = self.semantic_config.get('collection_name', 'xiaozhi_music') + + # Embedding settings + self.model_name = self.semantic_config.get('embedding_model', 'all-MiniLM-L6-v2') + + # Music directory settings + self.music_dir = Path(self.config.get('plugins', {}).get('play_music', {}).get('music_dir', './music')) + self.music_ext = ('.mp3', '.wav', '.p3') + + # Initialize clients + self.qdrant_client = None + self.embedding_model = None + + def _load_config(self, config_path: str) -> dict: + """Load configuration from YAML file""" + yaml = YAML() + yaml.preserve_quotes = True + + try: + with open(config_path, 'r', encoding='utf-8') as f: + config = yaml.load(f) + logger.info(f"Loaded configuration from {config_path}") + return config + except FileNotFoundError: + logger.error(f"Configuration file not found: {config_path}") + sys.exit(1) + except Exception as e: + logger.error(f"Failed to load configuration: {e}") + sys.exit(1) + + def initialize(self) -> bool: + """Initialize Qdrant client and embedding model""" + try: + # Initialize Qdrant client + logger.info(f"Connecting to Qdrant at {self.qdrant_url}...") + self.qdrant_client = QdrantClient( + url=self.qdrant_url, + api_key=self.qdrant_api_key, + timeout=60 # Increased timeout + ) + + # Test connection + collections = self.qdrant_client.get_collections() + logger.info(f"Connected to Qdrant. Found {len(collections.collections)} collections") + + # Initialize embedding model + logger.info(f"Loading embedding model: {self.model_name}...") + self.embedding_model = SentenceTransformer(self.model_name) + self.embedding_size = self.embedding_model.get_sentence_embedding_dimension() + logger.info(f"Embedding model loaded. Dimension: {self.embedding_size}") + + return True + + except Exception as e: + logger.error(f"Failed to initialize: {e}") + return False + + def create_collection(self, recreate: bool = False) -> bool: + """Create or recreate the Qdrant collection""" + try: + # Check if collection exists + collections = self.qdrant_client.get_collections() + exists = any(c.name == self.collection_name for c in collections.collections) + + if exists: + if recreate: + logger.info(f"Deleting existing collection '{self.collection_name}'...") + self.qdrant_client.delete_collection(self.collection_name) + logger.info("Collection deleted") + else: + logger.info(f"Collection '{self.collection_name}' already exists") + return True + + # Create new collection + logger.info(f"Creating collection '{self.collection_name}'...") + self.qdrant_client.create_collection( + collection_name=self.collection_name, + vectors_config=models.VectorParams( + size=self.embedding_size, + distance=models.Distance.COSINE + ), + ) + logger.info("Collection created successfully") + return True + + except Exception as e: + logger.error(f"Failed to create collection: {e}") + return False + + def load_music_metadata(self) -> Dict[str, Dict]: + """Load all music metadata from the music directory""" + metadata_cache = {} + + if not self.music_dir.exists(): + logger.error(f"Music directory does not exist: {self.music_dir}") + return metadata_cache + + logger.info(f"Scanning music directory: {self.music_dir}") + + for language_folder in self.music_dir.iterdir(): + if not language_folder.is_dir(): + continue + + language_name = language_folder.name + metadata_file = language_folder / "metadata.json" + + if metadata_file.exists(): + try: + with open(metadata_file, 'r', encoding='utf-8') as f: + metadata = json.load(f) + + metadata_cache[language_name] = { + 'metadata': metadata, + 'folder_path': str(language_folder) + } + + self.stats.total_songs += len(metadata) + self.stats.languages_processed.append(language_name) + logger.info(f"Loaded {len(metadata)} songs from {language_name}") + + except Exception as e: + logger.error(f"Failed to load metadata from {metadata_file}: {e}") + else: + # Scan for actual music files if no metadata.json + music_files = [] + for ext in self.music_ext: + music_files.extend(language_folder.glob(f"*{ext}")) + + if music_files: + logger.warning(f"No metadata.json in {language_name}, found {len(music_files)} music files") + # Create basic metadata from filenames + metadata = {} + for file in music_files: + song_name = file.stem + metadata[song_name] = { + 'filename': file.name, + 'romanized': song_name + } + + metadata_cache[language_name] = { + 'metadata': metadata, + 'folder_path': str(language_folder) + } + + self.stats.total_songs += len(metadata) + self.stats.languages_processed.append(language_name) + + self.stats.total_languages = len(metadata_cache) + logger.info(f"Total: {self.stats.total_languages} languages, {self.stats.total_songs} songs") + return metadata_cache + + def index_metadata(self, metadata_cache: Dict[str, Dict]) -> bool: + """Index all metadata into Qdrant""" + if not metadata_cache: + logger.warning("No metadata to index") + return False + + try: + points = [] + point_id = 0 + + logger.info("Generating embeddings and preparing data...") + + for language, lang_data in metadata_cache.items(): + metadata = lang_data.get('metadata', {}) + + for song_title, song_info in metadata.items(): + try: + # Prepare searchable text + searchable_texts = [ + song_title, + song_info.get('romanized', ''), + ] + + # Add alternatives + alternatives = song_info.get('alternatives', []) + if isinstance(alternatives, list): + searchable_texts.extend(alternatives) + + # Add keywords + keywords = song_info.get('keywords', []) + if isinstance(keywords, list): + searchable_texts.extend(keywords) + + # Add language context + searchable_texts.append(language) + + # Combine all text + combined_text = " ".join(filter(None, searchable_texts)).strip() + + if not combined_text: + logger.warning(f"Skipping {song_title} - no searchable text") + continue + + # Generate embedding + embedding = self.embedding_model.encode(combined_text).tolist() + + # Prepare payload + payload = { + 'title': song_title, + 'language': language, + 'romanized': song_info.get('romanized', song_title), + 'alternatives': alternatives, + 'keywords': keywords, + 'filename': song_info.get('filename', f"{song_title}.mp3"), + 'file_path': f"{language}/{song_info.get('filename', f'{song_title}.mp3')}", + 'searchable_text': combined_text, + 'metadata': song_info + } + + points.append( + models.PointStruct( + id=point_id, + vector=embedding, + payload=payload + ) + ) + point_id += 1 + self.stats.songs_indexed += 1 + + if point_id % 50 == 0: + logger.info(f"Processed {point_id} songs...") + + except Exception as e: + logger.error(f"Failed to process {song_title}: {e}") + self.stats.songs_failed += 1 + + # Upload to Qdrant in batches + if points: + logger.info(f"Uploading {len(points)} songs to Qdrant...") + batch_size = 100 + + for i in range(0, len(points), batch_size): + batch = points[i:i+batch_size] + self.qdrant_client.upsert( + collection_name=self.collection_name, + points=batch, + wait=True # Wait for indexing to complete + ) + logger.info(f"Uploaded batch {i//batch_size + 1}/{(len(points)-1)//batch_size + 1}") + + logger.info(f"Successfully indexed {len(points)} songs") + return True + else: + logger.warning("No valid songs to index") + return False + + except Exception as e: + logger.error(f"Failed to index metadata: {e}") + return False + + def verify_indexing(self) -> bool: + """Verify that indexing was successful""" + try: + collection_info = self.qdrant_client.get_collection(self.collection_name) + point_count = collection_info.points_count + + logger.info(f"Collection '{self.collection_name}' contains {point_count} songs") + + # Try a sample search + test_query = "twinkle twinkle little star" + logger.info(f"Testing search with query: '{test_query}'") + + query_embedding = self.embedding_model.encode(test_query).tolist() + results = self.qdrant_client.search( + collection_name=self.collection_name, + query_vector=query_embedding, + limit=3 + ) + + if results: + logger.info("Sample search results:") + for i, hit in enumerate(results, 1): + logger.info(f" {i}. {hit.payload['title']} ({hit.payload['language']}) - Score: {hit.score:.3f}") + else: + logger.warning("No results found for test query") + + return point_count > 0 + + except Exception as e: + logger.error(f"Failed to verify indexing: {e}") + return False + + def run(self, clear: bool = False, verify_only: bool = False): + """Run the indexing process""" + start_time = time.time() + + # Initialize + if not self.initialize(): + logger.error("Initialization failed") + return False + + if verify_only: + # Just verify existing index + success = self.verify_indexing() + if success: + logger.info("✅ Verification successful") + else: + logger.error("❌ Verification failed") + return success + + # Create/recreate collection + if not self.create_collection(recreate=clear): + logger.error("Failed to create collection") + return False + + # Load metadata + metadata_cache = self.load_music_metadata() + if not metadata_cache: + logger.error("No metadata found") + return False + + # Index metadata + success = self.index_metadata(metadata_cache) + + # Calculate stats + self.stats.time_taken = time.time() - start_time + + # Print summary + logger.info("=" * 60) + logger.info("INDEXING SUMMARY") + logger.info("=" * 60) + logger.info(f"Languages processed: {self.stats.total_languages}") + logger.info(f"Total songs found: {self.stats.total_songs}") + logger.info(f"Songs indexed: {self.stats.songs_indexed}") + logger.info(f"Songs failed: {self.stats.songs_failed}") + logger.info(f"Time taken: {self.stats.time_taken:.2f} seconds") + logger.info(f"Languages: {', '.join(self.stats.languages_processed)}") + logger.info("=" * 60) + + if success: + logger.info("✅ Indexing completed successfully!") + # Verify the indexing + self.verify_indexing() + else: + logger.error("❌ Indexing failed") + + return success + +def main(): + """Main entry point""" + parser = argparse.ArgumentParser(description='Index music metadata for semantic search') + parser.add_argument('--clear', action='store_true', help='Clear existing index before indexing') + parser.add_argument('--verify', action='store_true', help='Only verify existing index') + parser.add_argument('--config', default='data/.config.yaml', help='Path to configuration file') + + args = parser.parse_args() + + # Print header + print("=" * 60) + print("MUSIC METADATA INDEXER FOR XIAOZHI") + print("=" * 60) + print(f"Config file: {args.config}") + print(f"Clear existing: {args.clear}") + print(f"Verify only: {args.verify}") + print("=" * 60) + print() + + # Run indexer + indexer = MusicIndexer(config_path=args.config) + success = indexer.run(clear=args.clear, verify_only=args.verify) + + sys.exit(0 if success else 1) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/main/xiaozhi-server/plugins_func/functions/play_music.py b/main/xiaozhi-server/plugins_func/functions/play_music.py index 111b14374..ce963aba4 100644 --- a/main/xiaozhi-server/plugins_func/functions/play_music.py +++ b/main/xiaozhi-server/plugins_func/functions/play_music.py @@ -10,6 +10,7 @@ from plugins_func.register import register_function, ToolType, ActionResponse, A from core.utils.dialogue import Message from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType from plugins_func.utils.multilingual_matcher import MultilingualMatcher +from plugins_func.utils.semantic_music_search import SemanticMusicSearch # S3 Streaming imports import boto3 @@ -23,6 +24,7 @@ TAG = __name__ MUSIC_CACHE = {} MULTILINGUAL_MATCHER = None +SEMANTIC_SEARCH = None # S3 Configuration S3_CLIENT = None @@ -423,8 +425,8 @@ def initialize_music_handler(conn): return MUSIC_CACHE def initialize_multilingual_music_system(conn): - """Initialize the multilingual music matching system""" - global MULTILINGUAL_MATCHER, MUSIC_CACHE + """Initialize the multilingual music matching system with semantic search""" + global MULTILINGUAL_MATCHER, SEMANTIC_SEARCH, MUSIC_CACHE # Initialize basic music cache first initialize_music_handler(conn) @@ -440,10 +442,35 @@ def initialize_multilingual_music_system(conn): except Exception as e: conn.logger.bind(tag=TAG).error(f"Failed to initialize multilingual matcher: {e}") MULTILINGUAL_MATCHER = None + + # Initialize semantic search if not already done + if SEMANTIC_SEARCH is None: + try: + semantic_config = conn.config.get('semantic_search', {}) + if semantic_config.get('enabled', False): + SEMANTIC_SEARCH = SemanticMusicSearch(semantic_config) + if SEMANTIC_SEARCH.initialize(): + conn.logger.bind(tag=TAG).info("Semantic music search initialized successfully") + + # Check if collection is already indexed + if SEMANTIC_SEARCH.is_collection_indexed(): + stats = SEMANTIC_SEARCH.get_collection_stats() + conn.logger.bind(tag=TAG).info(f"Using existing music index with {stats.get('points_count', 0)} songs") + else: + conn.logger.bind(tag=TAG).warning("Music collection is empty. Please run 'python index_music.py' to index your music") + # Don't try to index on-the-fly anymore to avoid timeouts + else: + conn.logger.bind(tag=TAG).warning("Failed to initialize semantic search") + SEMANTIC_SEARCH = None + else: + conn.logger.bind(tag=TAG).info("Semantic search is disabled in configuration") + except Exception as e: + conn.logger.bind(tag=TAG).error(f"Failed to initialize semantic search: {e}") + SEMANTIC_SEARCH = None async def handle_multilingual_music_command(conn, user_request: str, song_type: str, requested_language: str = None): - """Enhanced music command handler with multilingual AI matching""" - global MULTILINGUAL_MATCHER, MUSIC_CACHE + """Enhanced music command handler with semantic search and multilingual matching""" + global MULTILINGUAL_MATCHER, SEMANTIC_SEARCH, MUSIC_CACHE conn.logger.bind(tag=TAG).debug(f"Processing multilingual music request: '{user_request}'") @@ -470,24 +497,41 @@ async def handle_multilingual_music_command(conn, user_request: str, song_type: # Check if this is a language-only request is_language_only = MULTILINGUAL_MATCHER and MULTILINGUAL_MATCHER.is_language_only_request(user_request) - # Try multilingual AI matching for specific songs (ignore LLM language hint for better accuracy) - if MULTILINGUAL_MATCHER and song_type in ["specific", "random"] and not is_language_only: + # Try semantic search for specific songs first (most accurate) + if SEMANTIC_SEARCH and song_type in ["specific", "random"] and not is_language_only: try: - # First try without language hint to find best match across all languages + semantic_result = SEMANTIC_SEARCH.find_best_match(user_request) + if semantic_result and semantic_result.score > 0.5: # Confidence threshold + selected_music = semantic_result.file_path + match_info = { + 'method': 'semantic_search', + 'language': semantic_result.language, + 'title': semantic_result.romanized, + 'original_title': semantic_result.title, + 'score': semantic_result.score + } + conn.logger.bind(tag=TAG).info(f"Semantic search match: {selected_music} ({semantic_result.language}) - score: {semantic_result.score:.3f}") + except Exception as e: + conn.logger.bind(tag=TAG).error(f"Error in semantic search: {e}") + + # Fallback to multilingual AI matching if semantic search didn't find a good match + if not selected_music and MULTILINGUAL_MATCHER and song_type in ["specific", "random"] and not is_language_only: + try: + # Try multilingual matcher as fallback match_result = MULTILINGUAL_MATCHER.find_content_match(user_request, None) if match_result: selected_music, detected_language, metadata_entry = match_result match_info = { - 'method': 'ai_multilingual', + 'method': 'ai_multilingual_fallback', 'language': detected_language, 'title': metadata_entry.get('romanized', 'Unknown'), 'original_title': list(MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].keys())[ list(MULTILINGUAL_MATCHER.metadata_cache[detected_language]['metadata'].values()).index(metadata_entry) ] if detected_language in MULTILINGUAL_MATCHER.metadata_cache else 'Unknown' } - conn.logger.bind(tag=TAG).info(f"AI match found: {selected_music} ({detected_language}) - overriding LLM language hint: {requested_language}") + conn.logger.bind(tag=TAG).info(f"Fallback AI match found: {selected_music} ({detected_language})") except Exception as e: - conn.logger.bind(tag=TAG).error(f"Error in AI matching: {e}") + conn.logger.bind(tag=TAG).error(f"Error in AI matching fallback: {e}") # Try language-specific selection for language requests or when language is detected if not selected_music and requested_language and MULTILINGUAL_MATCHER: @@ -667,7 +711,36 @@ def generate_multilingual_intro(match_info: dict, original_request: str) -> str: language = 'unknown' try: - if method == 'ai_multilingual': + if method == 'semantic_search': + score = match_info.get('score', 0) + if score > 0.8: + if language != 'unknown': + intros = [ + f"Perfect match! I found '{title}' in {language.title()} for you!", + f"Excellent! Here's '{title}' - exactly what you asked for in {language.title()}!", + f"Found it! Playing '{title}' - this {language.title()} song matches perfectly!", + f"Great choice! '{title}' in {language.title()} is exactly what you wanted!" + ] + else: + intros = [ + f"Perfect! I found exactly what you wanted: '{title}'!", + f"Excellent match! Here's '{title}' for you!", + f"Found it! Playing '{title}' - this is exactly what you asked for!" + ] + else: + if language != 'unknown': + intros = [ + f"I think you'll like '{title}' in {language.title()}!", + f"Here's '{title}' - a great {language.title()} song that matches your request!", + f"Playing '{title}' in {language.title()} - hope this is what you wanted!" + ] + else: + intros = [ + f"I found '{title}' which should match your request!", + f"Here's '{title}' - I think this is what you're looking for!", + f"Playing '{title}' based on your request!" + ] + elif method == 'ai_multilingual' or method == 'ai_multilingual_fallback': if language != 'unknown': intros = [ f"Perfect! I found '{title}' in {language.title()} for you!", diff --git a/main/xiaozhi-server/plugins_func/utils/semantic_music_search.py b/main/xiaozhi-server/plugins_func/utils/semantic_music_search.py new file mode 100644 index 000000000..e17ecb7f7 --- /dev/null +++ b/main/xiaozhi-server/plugins_func/utils/semantic_music_search.py @@ -0,0 +1,340 @@ +""" +Semantic Music Search Module using Qdrant Vector Database +Integrates with the existing multilingual music matching system +""" + +import json +import os +import logging +from pathlib import Path +from typing import Dict, List, Optional, Tuple, Union +from dataclasses import dataclass + +try: + from qdrant_client import QdrantClient, models + from qdrant_client.http.exceptions import UnexpectedResponse + from sentence_transformers import SentenceTransformer + from spellchecker import SpellChecker + DEPENDENCIES_AVAILABLE = True +except ImportError as e: + DEPENDENCIES_AVAILABLE = False + import_error = str(e) + +import hashlib +import time + +@dataclass +class MusicSearchResult: + """Data class for music search results""" + file_path: str + title: str + language: str + romanized: str + alternatives: List[str] + score: float + metadata: Dict + +class SemanticMusicSearch: + """ + Semantic music search engine using Qdrant vector database + """ + + def __init__(self, config: Dict = None): + """Initialize the semantic music search system""" + self.config = config or {} + self.logger = logging.getLogger(__name__) + + # Check if dependencies are available + if not DEPENDENCIES_AVAILABLE: + self.logger.error(f"Semantic search dependencies not available: {import_error}") + self.is_available = False + return + + self.is_available = True + + # Qdrant configuration + self.qdrant_url = self.config.get("qdrant_url", "https://localhost:6333") + self.qdrant_api_key = self.config.get("qdrant_api_key", None) + self.collection_name = self.config.get("collection_name", "xiaozhi_music") + + # Embedding model configuration + self.model_name = self.config.get("embedding_model", "all-MiniLM-L6-v2") + + # Search parameters + self.search_limit = self.config.get("search_limit", 5) + self.min_score_threshold = self.config.get("min_score_threshold", 0.5) + + # Initialize components + self.qdrant_client = None + self.embedding_model = None + self.spell_checker = None + self.embedding_size = None + self.is_initialized = False + + # Cache for embeddings to avoid recomputation + self.embedding_cache = {} + + def initialize(self) -> bool: + """Initialize Qdrant client and embedding model""" + if not self.is_available: + self.logger.error("Semantic search dependencies not available") + return False + + try: + # Initialize spell checker + self.spell_checker = SpellChecker() + + # Initialize Qdrant client + if self.qdrant_api_key: + self.qdrant_client = QdrantClient( + url=self.qdrant_url, + api_key=self.qdrant_api_key + ) + else: + self.qdrant_client = QdrantClient(url=self.qdrant_url) + + # Test connection + self.qdrant_client.get_collections() + + # Initialize embedding model + self.logger.info(f"Loading embedding model: {self.model_name}") + self.embedding_model = SentenceTransformer(self.model_name) + self.embedding_size = self.embedding_model.get_sentence_embedding_dimension() + + # Create collection if it doesn't exist + self._create_collection_if_not_exists() + + self.is_initialized = True + self.logger.info(f"Semantic music search initialized with model: {self.model_name}") + return True + + except Exception as e: + self.logger.error(f"Failed to initialize semantic search: {e}") + self.is_initialized = False + return False + + def _create_collection_if_not_exists(self): + """Create Qdrant collection if it doesn't exist""" + try: + self.qdrant_client.get_collection(collection_name=self.collection_name) + self.logger.info(f"Collection '{self.collection_name}' already exists") + except Exception: + self.logger.info(f"Creating collection '{self.collection_name}'") + self.qdrant_client.create_collection( + collection_name=self.collection_name, + vectors_config=models.VectorParams( + size=self.embedding_size, + distance=models.Distance.COSINE + ), + ) + + def correct_spelling(self, query: str) -> str: + """Correct spelling in the user query""" + if not self.spell_checker: + return query + + words = query.split() + corrected_words = [] + + for word in words: + # Skip very short words and numbers + if len(word) <= 2 or word.isdigit(): + corrected_words.append(word) + continue + + corrected_word = self.spell_checker.correction(word) + if corrected_word is None: + corrected_word = word + corrected_words.append(corrected_word) + + corrected_query = " ".join(corrected_words) + if corrected_query != query: + self.logger.debug(f"Spelling correction: '{query}' -> '{corrected_query}'") + + return corrected_query + + def _get_embedding(self, text: str) -> List[float]: + """Get embedding for text with caching""" + if not text or not self.embedding_model: + return [] + + # Create a hash of the text for caching + text_hash = hashlib.md5(text.encode()).hexdigest() + + if text_hash in self.embedding_cache: + return self.embedding_cache[text_hash] + + embedding = self.embedding_model.encode(text).tolist() + self.embedding_cache[text_hash] = embedding + return embedding + + def index_music_metadata(self, music_metadata: Dict[str, Dict]) -> bool: + """ + Index music metadata into Qdrant + music_metadata format: {language: {metadata: {song_title: song_info}}} + """ + if not self.is_initialized: + self.logger.warning("Semantic search not initialized, skipping indexing") + return False + + try: + # Clear existing collection + self.qdrant_client.delete_collection(self.collection_name) + self._create_collection_if_not_exists() + + points = [] + point_id = 0 + + for language, lang_data in music_metadata.items(): + metadata = lang_data.get('metadata', {}) + + for song_title, song_info in metadata.items(): + # Prepare searchable text for embedding + searchable_texts = [ + song_title, # Original title + song_info.get('romanized', ''), # Romanized version + ] + + # Add alternative names + alternatives = song_info.get('alternatives', []) + if isinstance(alternatives, list): + searchable_texts.extend(alternatives) + + # Add keywords + keywords = song_info.get('keywords', []) + if isinstance(keywords, list): + searchable_texts.extend(keywords) + + # Add language for context + searchable_texts.append(language) + + # Combine all searchable text + combined_text = " ".join(filter(None, searchable_texts)).strip() + + if not combined_text: + continue + + # Generate embedding + embedding = self._get_embedding(combined_text) + if not embedding: + continue + + # Prepare payload + payload = { + 'title': song_title, + 'language': language, + 'romanized': song_info.get('romanized', song_title), + 'alternatives': alternatives, + 'keywords': keywords, + 'filename': song_info.get('filename', f"{song_title}.mp3"), + 'file_path': f"{language}/{song_info.get('filename', f'{song_title}.mp3')}", + 'searchable_text': combined_text, + 'metadata': song_info + } + + points.append( + models.PointStruct( + id=point_id, + vector=embedding, + payload=payload + ) + ) + point_id += 1 + + # Upsert points to Qdrant + if points: + self.qdrant_client.upsert( + collection_name=self.collection_name, + points=points + ) + self.logger.info(f"Indexed {len(points)} music tracks into Qdrant") + return True + else: + self.logger.warning("No music metadata to index") + return False + + except Exception as e: + self.logger.error(f"Failed to index music metadata: {e}") + return False + + def search(self, query: str, limit: Optional[int] = None) -> List[MusicSearchResult]: + """ + Perform semantic search for music + """ + if not self.is_initialized: + return [] + + try: + # Check if collection has data + collection_info = self.qdrant_client.get_collection(self.collection_name) + if collection_info.points_count == 0: + self.logger.warning("Music collection is empty. Please index music metadata first.") + return [] + + # Correct spelling + corrected_query = self.correct_spelling(query) + + # Generate query embedding + query_embedding = self._get_embedding(corrected_query) + if not query_embedding: + return [] + + # Search in Qdrant + search_results = self.qdrant_client.search( + collection_name=self.collection_name, + query_vector=query_embedding, + limit=limit or self.search_limit + ) + + # Convert to MusicSearchResult objects + results = [] + for hit in search_results: + if hit.score >= self.min_score_threshold: + result = MusicSearchResult( + file_path=hit.payload['file_path'], + title=hit.payload['title'], + language=hit.payload['language'], + romanized=hit.payload['romanized'], + alternatives=hit.payload['alternatives'], + score=hit.score, + metadata=hit.payload['metadata'] + ) + results.append(result) + + self.logger.debug(f"Found {len(results)} matching songs for query: '{query}'") + return results + + except Exception as e: + self.logger.error(f"Search failed: {e}") + return [] + + def find_best_match(self, query: str) -> Optional[MusicSearchResult]: + """Find the single best matching song""" + results = self.search(query, limit=1) + return results[0] if results else None + + def is_collection_indexed(self) -> bool: + """Check if the collection has been indexed""" + if not self.is_initialized: + return False + + try: + collection_info = self.qdrant_client.get_collection(self.collection_name) + return collection_info.points_count > 0 + except: + return False + + def get_collection_stats(self) -> Dict: + """Get statistics about the indexed collection""" + if not self.is_initialized: + return {} + + try: + collection_info = self.qdrant_client.get_collection(self.collection_name) + return { + 'points_count': collection_info.points_count, + 'segments_count': collection_info.segments_count, + } + except Exception as e: + self.logger.error(f"Failed to get collection stats: {e}") + return {} \ No newline at end of file diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt index 4a6480946..9bd44f5a0 100755 --- a/main/xiaozhi-server/requirements.txt +++ b/main/xiaozhi-server/requirements.txt @@ -39,4 +39,8 @@ boto3 deepgram-sdk==4.8.1 fuzzywuzzy Levenshtein -amazon_transcribe \ No newline at end of file +amazon_transcribe +# Semantic search dependencies +qdrant-client>=1.7.0 +sentence-transformers>=2.2.0 +pyspellchecker>=0.7.0 \ No newline at end of file From 1c1812f7f150b288a718baaa90d06c392f1154ca Mon Sep 17 00:00:00 2001 From: KIRAN CHOUDHARI Date: Thu, 11 Sep 2025 17:39:28 +0530 Subject: [PATCH 02/12] User agents are displaying in admin panel --- .../agent/controller/AgentController.java | 16 ++++-- .../xiaozhi/modules/agent/dao/AgentDao.java | 22 +++++++- .../xiaozhi/modules/agent/dto/AgentDTO.java | 10 ++++ .../modules/agent/service/AgentService.java | 15 ++++++ .../agent/service/impl/AgentServiceImpl.java | 53 +++++++++++++++++++ .../device/controller/DeviceController.java | 12 ++++- .../modules/device/service/DeviceService.java | 5 ++ .../service/impl/DeviceServiceImpl.java | 7 +++ .../src/main/resources/application.yml | 2 +- .../manager-web/src/components/DeviceItem.vue | 21 +++++++- 10 files changed, 155 insertions(+), 8 deletions(-) diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java index 4bd8f948e..1b84853fb 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java @@ -67,11 +67,21 @@ public class AgentController { private final RedisUtils redisUtils; @GetMapping("/list") - @Operation(summary = "Get user agents list") + @Operation(summary = "Get agents list (admin gets all agents, user gets own agents)") @RequiresPermissions("sys:role:normal") - public Result> getUserAgents() { + public Result> getAgentsList() { UserDetail user = SecurityUser.getUser(); - List agents = agentService.getUserAgents(user.getId()); + List agents; + + // Check if user is super admin + if (user.getSuperAdmin() != null && user.getSuperAdmin() == 1) { + // Admin sees all agents from all users with owner information + agents = agentService.getAllAgentsForAdmin(); + } else { + // Regular user sees only their own agents + agents = agentService.getUserAgents(user.getId()); + } + return new Result>().ok(agents); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java index 03e569cdc..a596aab88 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dao/AgentDao.java @@ -1,8 +1,10 @@ package xiaozhi.modules.agent.dao; +import java.util.List; +import java.util.Map; + import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; - import org.apache.ibatis.annotations.Select; import xiaozhi.common.dao.BaseDao; import xiaozhi.modules.agent.entity.AgentEntity; @@ -30,6 +32,24 @@ public interface AgentDao extends BaseDao { " ORDER BY d.id DESC LIMIT 1") AgentEntity getDefaultAgentByMacAddress(@Param("macAddress") String macAddress); + /** + * 获取所有智能体及其所有者信息(管理员专用) + * + * @return 所有智能体列表及用户信息 + */ + @Select("SELECT " + + "a.id, a.agent_name, a.system_prompt, a.tts_model_id, " + + "a.llm_model_id, a.vllm_model_id, a.mem_model_id, a.tts_voice_id, " + + "a.created_at, a.updated_at, a.user_id, " + + "u.username as owner_username, " + + "GROUP_CONCAT(d.mac_address SEPARATOR ',') as device_mac_addresses " + + "FROM ai_agent a " + + "LEFT JOIN sys_user u ON a.user_id = u.id " + + "LEFT JOIN ai_device d ON a.id = d.agent_id " + + "GROUP BY a.id " + + "ORDER BY a.created_at DESC") + List> getAllAgentsWithOwnerInfo(); + /** * 根据id查询agent信息,包括插件信息 * diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java index 218ee1ebf..fcf8d229a 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/dto/AgentDTO.java @@ -45,4 +45,14 @@ public class AgentDTO { @Schema(description = "设备数量", example = "10") private Integer deviceCount; + + @Schema(description = "设备MAC地址列表", example = "AA:BB:CC:DD:EE:FF,11:22:33:44:55:66") + private String deviceMacAddresses; + + // 管理员专用字段 - 智能体所有者信息 + @Schema(description = "所有者用户名", example = "john_doe") + private String ownerUsername; + + @Schema(description = "创建时间", example = "2024-03-20 10:00:00") + private Date createDate; } \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java index a9d4e5bb2..55cd0abce 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/AgentService.java @@ -43,6 +43,21 @@ public interface AgentService extends BaseService { */ boolean insert(AgentEntity entity); + /** + * 获取用户的智能体列表 + * + * @param userId 用户ID + * @return 智能体列表 + */ + List getUserAgents(Long userId); + + /** + * 获取所有智能体列表(管理员专用,包含用户信息) + * + * @return 所有智能体列表 + */ + List getAllAgentsForAdmin(); + /** * 根据用户ID删除智能体 * diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java index e425b743f..330ee8071 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/service/impl/AgentServiceImpl.java @@ -150,6 +150,59 @@ public class AgentServiceImpl extends BaseServiceImpl imp }).collect(Collectors.toList()); } + @Override + public List getAllAgentsForAdmin() { + List> agentMaps = agentDao.getAllAgentsWithOwnerInfo(); + return agentMaps.stream().map(agentMap -> { + AgentDTO dto = new AgentDTO(); + + // 基础智能体信息 + String agentId = (String) agentMap.get("id"); + dto.setId(agentId); + dto.setAgentName((String) agentMap.get("agent_name")); + dto.setSystemPrompt((String) agentMap.get("system_prompt")); + + // Handle LocalDateTime to Date conversion for createDate + Object createdAt = agentMap.get("created_at"); + if (createdAt instanceof java.time.LocalDateTime) { + dto.setCreateDate(java.sql.Timestamp.valueOf((java.time.LocalDateTime) createdAt)); + } + + // 获取模型名称 - 同用户方法 + String ttsModelId = (String) agentMap.get("tts_model_id"); + String llmModelId = (String) agentMap.get("llm_model_id"); + String vllmModelId = (String) agentMap.get("vllm_model_id"); + String memModelId = (String) agentMap.get("mem_model_id"); + String ttsVoiceId = (String) agentMap.get("tts_voice_id"); + + dto.setTtsModelName(modelConfigService.getModelNameById(ttsModelId)); + dto.setLlmModelName(modelConfigService.getModelNameById(llmModelId)); + dto.setVllmModelName(modelConfigService.getModelNameById(vllmModelId)); + dto.setMemModelId(memModelId); + dto.setTtsVoiceName(timbreModelService.getTimbreNameById(ttsVoiceId)); + + // 获取智能体最近的最后连接时长 - 同用户方法 + dto.setLastConnectedAt(deviceService.getLatestLastConnectionTime(agentId)); + + // 获取设备MAC地址列表 - 管理员专用 + String macAddresses = (String) agentMap.get("device_mac_addresses"); + dto.setDeviceMacAddresses(macAddresses); + + // 计算设备数量(从MAC地址列表或使用原方法) + if (macAddresses != null && !macAddresses.isEmpty()) { + dto.setDeviceCount(macAddresses.split(",").length); + } else { + // 使用原来的方法获取设备数量 + dto.setDeviceCount(getDeviceCountByAgentId(agentId)); + } + + // 管理员专用字段 - 用户信息 + dto.setOwnerUsername((String) agentMap.get("owner_username")); + + return dto; + }).collect(Collectors.toList()); + } + @Override public Integer getDeviceCountByAgentId(String agentId) { if (StringUtils.isBlank(agentId)) { diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java index a23e9f81c..de9802776 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/controller/DeviceController.java @@ -71,7 +71,17 @@ public class DeviceController { @RequiresPermissions("sys:role:normal") public Result> getUserDevices(@PathVariable String agentId) { UserDetail user = SecurityUser.getUser(); - List devices = deviceService.getUserDevices(user.getId(), agentId); + List devices; + + // Check if user is super admin + if (user.getSuperAdmin() != null && user.getSuperAdmin() == 1) { + // Admin can see all devices for any agent + devices = deviceService.getDevicesByAgentId(agentId); + } else { + // Regular user can only see their own devices + devices = deviceService.getUserDevices(user.getId(), agentId); + } + return new Result>().ok(devices); } diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java index 3392c96ff..2afbd730e 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/DeviceService.java @@ -25,6 +25,11 @@ public interface DeviceService extends BaseService { */ List getUserDevices(Long userId, String agentId); + /** + * 获取指定智能体的所有设备列表(管理员专用) + */ + List getDevicesByAgentId(String agentId); + /** * 解绑设备 */ diff --git a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java index 96315ccc3..0119017c5 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceServiceImpl.java @@ -211,6 +211,13 @@ public class DeviceServiceImpl extends BaseServiceImpl return baseDao.selectList(wrapper); } + @Override + public List getDevicesByAgentId(String agentId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("agent_id", agentId); + return baseDao.selectList(wrapper); + } + @Override public void unbindDevice(Long userId, String deviceId) { UpdateWrapper wrapper = new UpdateWrapper<>(); diff --git a/main/manager-api/src/main/resources/application.yml b/main/manager-api/src/main/resources/application.yml index 56934b317..8590bbdc5 100644 --- a/main/manager-api/src/main/resources/application.yml +++ b/main/manager-api/src/main/resources/application.yml @@ -17,7 +17,7 @@ spring: # Profile will be set by SPRING_PROFILES_ACTIVE environment variable # Default to 'dev' if not specified profiles: - default: prod + default: dev messages: encoding: UTF-8 basename: i18n/messages diff --git a/main/manager-web/src/components/DeviceItem.vue b/main/manager-web/src/components/DeviceItem.vue index 54685b264..4ec8ee64e 100644 --- a/main/manager-web/src/components/DeviceItem.vue +++ b/main/manager-web/src/components/DeviceItem.vue @@ -1,8 +1,14 @@ - + From b0f8f73006d79d437951fc98b34df84bbd3013d2 Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Sat, 13 Sep 2025 16:38:43 +0530 Subject: [PATCH 10/12] updated gitignore --- main/xiaozhi-server/client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main/xiaozhi-server/client.py b/main/xiaozhi-server/client.py index d97fa10ad..4d30cd3c3 100644 --- a/main/xiaozhi-server/client.py +++ b/main/xiaozhi-server/client.py @@ -7,7 +7,7 @@ import struct import logging import pyaudio import keyboard - +#hjvk from typing import Dict, Optional, Tuple import requests import paho.mqtt.client as mqtt_client From bbe67302050be7452d209bcad750ca1705d5655d Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Sat, 13 Sep 2025 17:36:25 +0530 Subject: [PATCH 11/12] working agents fetching --- .../src/main/resources/application-dev.yml | 46 ++--- main/manager-web/src/views/home.vue | 183 ++++++++++++++++-- main/mqtt-gateway/config/mqtt.json | 4 +- 3 files changed, 195 insertions(+), 38 deletions(-) diff --git a/main/manager-api/src/main/resources/application-dev.yml b/main/manager-api/src/main/resources/application-dev.yml index 78ecb5f91..552ea6ea1 100644 --- a/main/manager-api/src/main/resources/application-dev.yml +++ b/main/manager-api/src/main/resources/application-dev.yml @@ -10,22 +10,22 @@ knife4j: # Server configuration server: - secret: a3c1734a-1efe-4ab7-8f43-98f88b874e4b + secret: d153e93c-bb2f-42e7-8045-a1ee47a1dcfc spring: datasource: druid: - #MySQL - Local Docker Configuration - driver-class-name: com.mysql.cj.jdbc.Driver - - # Local Docker MySQL Configuration - url: jdbc:mysql://localhost:3307/manager_api?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=false&allowPublicKeyRetrieval=true - username: manager - password: managerpassword - - # Railway MySQL Configuration (commented out for local development) - # url: jdbc:mysql://crossover.proxy.rlwy.net:56145/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true + #MySQL + # driver-class-name: com.mysql.cj.jdbc.Driver + # # Railway MySQL Configuration - Updated for Railway database + # url: jdbc:mysql://yamanote.proxy.rlwy.net:16958/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true # username: root - # password: XjOWQwtGNcoMIELTjoMoaaBTfKiBjVcA + # password: cTefiuLmZSMqGpcQImUmBIsUBhNyUvrK + driver-class-name: com.mysql.cj.jdbc.Driver + # Railway MySQL Configuration - Updated for Railway database + url: jdbc:mysql://crossover.proxy.rlwy.net:56145/railway?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Kolkata&nullCatalogMeansCurrent=true&useSSL=true&allowPublicKeyRetrieval=true + username: root + password: XjOWQwtGNcoMIELTjoMoaaBTfKiBjVcA + initial-size: 10 max-active: 100 min-idle: 10 @@ -49,23 +49,19 @@ spring: multi-statement-allow: true data: redis: - # Local Docker Redis Configuration - host: localhost # Local Redis服务器地址 - port: 6380 # Local Redis服务器连接端口 - password: redispassword # Local Redis服务器连接密码 + # Railway Redis Configuration + host: yamanote.proxy.rlwy.net # Railway Redis服务器地址 + port: 34938 # Railway Redis服务器连接端口 + password: YbdhwguVUNowduNpDZjuSefZFhBXiOEP # Railway Redis服务器连接密码 + username: default # Railway Redis用户名 database: 0 # Redis数据库索引(默认为0) - timeout: 10000ms # 连接超时时间(毫秒) + timeout: 30000ms # 连接超时时间(毫秒)- 增加超时时间 ssl: - enabled: false # 本地开发不需要SSL - - # Railway Redis Configuration (commented out for local development) - # host: yamanote.proxy.rlwy.net # Railway Redis服务器地址 - # port: 34938 # Railway Redis服务器连接端口 - # password: YbdhwguVUNowduNpDZjuSefZFhBXiOEP # Railway Redis服务器连接密码 - # username: default # Railway Redis用户名 + enabled: false # 尝试禁用SSL,Railway可能不需要 lettuce: pool: max-active: 8 # 连接池最大连接数(使用负值表示没有限制) max-idle: 8 # 连接池中的最大空闲连接 min-idle: 0 # 连接池中的最小空闲连接 - shutdown-timeout: 100ms # 客户端优雅关闭的等待时间 \ No newline at end of file + shutdown-timeout: 100ms # 客户端优雅关闭的等待时间 + diff --git a/main/manager-web/src/views/home.vue b/main/manager-web/src/views/home.vue index 2a5a0a808..b246c0d90 100644 --- a/main/manager-web/src/views/home.vue +++ b/main/manager-web/src/views/home.vue @@ -84,9 +84,33 @@ export default { }, mounted() { + console.log('Home component mounted, fetching agent list'); // Debug log this.fetchAgentList(); }, + activated() { + // This runs when component is activated (useful if using keep-alive) + console.log('Home component activated, fetching agent list'); // Debug log + this.fetchAgentList(); + }, + + created() { + console.log('Home component created'); // Debug log + }, + + watch: { + '$route'(to, from) { + // Watch for route changes - refetch data when navigating back to home + console.log('Route changed:', from.path, '->', to.path); // Debug log + if (to.name === 'home' || to.path === '/home') { + console.log('Navigated back to home, refetching agent list'); // Debug log + this.$nextTick(() => { + this.fetchAgentList(); + }); + } + } + }, + methods: { showAddDialog() { this.addDeviceDialogVisible = true @@ -129,24 +153,34 @@ export default { // 获取智能体列表 fetchAgentList() { this.isLoading = true; + console.log('Starting to fetch agent list...'); // Debug log // 根据用户角色决定使用哪个API const isAdmin = this.$store.getters.getIsSuperAdmin; + console.log('User is admin:', isAdmin); // Debug log if (isAdmin) { // 管理员:获取所有智能体 - Api.agent.getAgentList(({ data }) => { - this.handleAgentListResponse(data); + console.log('Fetching admin agent list...'); // Debug log + Api.agent.getAgentList((response) => { + console.log('Admin API response received:', response); // Debug log + // Extract response.data to match expected structure + this.handleAgentListResponse(response.data); }, (error) => { console.error('Failed to fetch admin agent list:', error); + this.$message.error('Failed to load agent list. Please check your connection and try again.'); this.isLoading = false; }); } else { // 普通用户:只获取自己的智能体 - Api.agent.getUserAgentList(({ data }) => { - this.handleAgentListResponse(data); + console.log('Fetching user agent list...'); // Debug log + Api.agent.getUserAgentList((response) => { + console.log('User API response received:', response); // Debug log + // Extract response.data to match expected structure + this.handleAgentListResponse(response.data); }, (error) => { console.error('Failed to fetch user agent list:', error); + this.$message.error('Failed to load your agents. Please check your connection and try again.'); this.isLoading = false; }); } @@ -154,14 +188,43 @@ export default { // 处理智能体列表响应 handleAgentListResponse(data) { - if (data?.data) { - // 对于用户API,数据直接在data中;对于管理员API,数据在data.list中 - const agentList = data.data.list || data.data; + console.log('Raw API Response:', data); // Debug log + + if (data) { + // The parameter 'data' is already response.data from the API call + let agentList = []; + + // The API response structure is nested: response.data.data.list + if (data.data && data.data.list && Array.isArray(data.data.list)) { + // For admin API: data.data.list (nested structure) + agentList = data.data.list; + console.log('Using data.data.list structure'); // Debug log + } else if (data.list && Array.isArray(data.list)) { + // For fallback: data.list + agentList = data.list; + console.log('Using data.list structure'); // Debug log + } else if (Array.isArray(data.data)) { + // For user API: data.data (direct array) + agentList = data.data; + console.log('Using data.data array structure'); // Debug log + } else if (Array.isArray(data)) { + // For direct array: data + agentList = data; + console.log('Using direct array structure'); // Debug log + } else { + console.error('Unexpected API response structure:', data); + console.error('Available keys in data:', Object.keys(data || {})); // Debug log + this.$message.error('Failed to load agent list: Invalid response format'); + this.isLoading = false; + return; + } - this.originalDevices = agentList.map(item => ({ - ...item, - agentId: item.id - })); + console.log('Agent list before processing:', agentList); // Debug log + + // 处理agent数据并获取模型名称 + this.processAgentListWithModelNames(agentList); + + console.log('Final processed devices:', this.originalDevices); // Debug log // 动态设置骨架屏数量(可选) this.skeletonCount = Math.min( @@ -170,6 +233,9 @@ export default { ); this.handleSearchReset(); + } else { + console.error('No data in API response:', data); + this.$message.error('Failed to load agent list: No data received'); } this.isLoading = false; }, @@ -196,6 +262,101 @@ export default { }); }).catch(() => { }); }, + + // 处理agent列表并获取模型名称 + async processAgentListWithModelNames(agentList) { + // 首先创建基本的设备列表 + const basicDevices = agentList + .filter(item => item && (item.id || item.agentId)) + .map(item => ({ + ...item, + agentId: item.agentId || item.id, + agentName: item.agentName || item.name || 'Unknown Agent', + // 暂时使用模型ID,稍后会被替换为模型名称 + llmModelName: item.llmModelId || 'Not configured', + ttsModelName: item.ttsModelId || 'Not configured', + ttsVoiceName: item.ttsVoiceId || 'Default', + deviceCount: item.deviceCount || 0, + memModelId: item.memModelId || 'Memory_nomem', + lastConnectedAt: item.lastConnectedAt || null, + systemPrompt: item.systemPrompt || 'No system prompt configured', + ownerUsername: item.ownerUsername || null, + // 保留原始ID用于获取模型名称 + originalLlmModelId: item.llmModelId, + originalTtsModelId: item.ttsModelId, + originalTtsVoiceId: item.ttsVoiceId + })); + + console.log('Basic devices processed:', basicDevices); // Debug log + + // 设置基本数据先显示 + this.originalDevices = basicDevices; + this.handleSearchReset(); + + // 异步获取模型名称并更新 + this.fetchModelNamesForDevices(); + }, + + // 获取所有设备的模型名称 + fetchModelNamesForDevices() { + const uniqueLlmModels = [...new Set(this.originalDevices.map(d => d.originalLlmModelId).filter(Boolean))]; + const uniqueTtsModels = [...new Set(this.originalDevices.map(d => d.originalTtsModelId).filter(Boolean))]; + const uniqueVoiceIds = [...new Set(this.originalDevices.map(d => d.originalTtsVoiceId).filter(Boolean))]; + + console.log('Fetching names for:', { uniqueLlmModels, uniqueTtsModels, uniqueVoiceIds }); + + // 获取LLM模型名称 + uniqueLlmModels.forEach(modelId => { + Api.model.getModelConfig(modelId, (response) => { + console.log(`LLM Model response for ${modelId}:`, response); + if (response.data && response.data.code === 0) { + const modelName = response.data.data?.modelName || modelId; + this.updateDeviceModelName('llmModelName', modelId, modelName); + } + }); + }); + + // 获取TTS模型名称 + uniqueTtsModels.forEach(modelId => { + Api.model.getModelConfig(modelId, (response) => { + console.log(`TTS Model response for ${modelId}:`, response); + if (response.data && response.data.code === 0) { + const modelName = response.data.data?.modelName || modelId; + this.updateDeviceModelName('ttsModelName', modelId, modelName); + } + }); + }); + + // 获取TTS声音名称 (暂时跳过自定义语音,只显示ID) + console.log('Voice IDs will be displayed as-is for now'); + }, + + // 更新设备的模型名称 + updateDeviceModelName(field, originalId, newName) { + const fieldMapping = { + 'llmModelName': 'originalLlmModelId', + 'ttsModelName': 'originalTtsModelId', + 'ttsVoiceName': 'originalTtsVoiceId' + }; + + this.originalDevices = this.originalDevices.map(device => { + if (device[fieldMapping[field]] === originalId) { + return { ...device, [field]: newName }; + } + return device; + }); + + // 如果当前显示的是搜索结果,也要更新搜索结果 + this.devices = this.devices.map(device => { + if (device[fieldMapping[field]] === originalId) { + return { ...device, [field]: newName }; + } + return device; + }); + + console.log(`Updated ${field} for ${originalId} to: ${newName}`); + }, + handleShowChatHistory({ agentId, agentName }) { this.currentAgentId = agentId; this.currentAgentName = agentName; diff --git a/main/mqtt-gateway/config/mqtt.json b/main/mqtt-gateway/config/mqtt.json index 94b7f366f..0d7908ec9 100644 --- a/main/mqtt-gateway/config/mqtt.json +++ b/main/mqtt-gateway/config/mqtt.json @@ -2,13 +2,13 @@ "production": { "chat_servers": [ - "ws://192.168.1.98:8000/toy/v1/" + "ws://64.227.170.31:8000/toy/v1/" ] }, "development": { "chat_servers": [ - "ws://192.168.1.98:8000/toy/v1/" + "ws://64.227.170.31:8000/toy/v1/" ], "mac_addresss": [ From 8db186de96126935d30614654d618e168b6618a3 Mon Sep 17 00:00:00 2001 From: rahulpscraftech360 Date: Sat, 13 Sep 2025 18:46:55 +0530 Subject: [PATCH 12/12] fixed dashboard issue,fetehced agent names of users --- .gitignore | 4 + .../service/impl/CaptchaServiceImpl.java | 12 +- main/manager-web/src/apis/module/admin.js | 59 +++++++++ .../manager-web/src/components/DeviceItem.vue | 4 +- main/manager-web/src/views/home.vue | 121 +++++++++++++++++- .../plugins_func/functions/play_music.py | 2 +- 6 files changed, 195 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 5709d1cf6..959faccdc 100644 --- a/.gitignore +++ b/.gitignore @@ -183,3 +183,7 @@ main/xiaozhi-server/mysql uploadfile *.json .vscode + +# Spring Boot configuration files (contain sensitive data) +main/manager-api/src/main/resources/application.yml +main/manager-api/src/main/resources/application-dev.yml diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java index e3bc5a767..e01b40616 100644 --- a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java @@ -64,7 +64,7 @@ public class CaptchaServiceImpl implements CaptchaService { if (StringUtils.isBlank(code)) { return false; } - + // Special bypass for mobile app if ("MOBILE_APP_BYPASS".equals(code)) { // Mobile apps can bypass captcha validation @@ -72,7 +72,7 @@ public class CaptchaServiceImpl implements CaptchaService { // such as checking a special header or API key return true; } - + // 获取验证码 String captcha = getCache(uuid, delete); @@ -139,6 +139,14 @@ public class CaptchaServiceImpl implements CaptchaService { @Override public boolean validateSMSValidateCode(String phone, String code, Boolean delete) { + // Special bypass for mobile app SMS verification + if ("MOBILE_APP_BYPASS".equals(code)) { + // Mobile apps can bypass SMS validation + // In production, you should add additional security checks + // such as checking a special header or API key + return true; + } + String key = RedisKeys.getSMSValidateCodeKey(phone); return validate(key, code, delete); } diff --git a/main/manager-web/src/apis/module/admin.js b/main/manager-web/src/apis/module/admin.js index 27c1bc3e7..ae0644bf0 100644 --- a/main/manager-web/src/apis/module/admin.js +++ b/main/manager-web/src/apis/module/admin.js @@ -41,6 +41,65 @@ export default { }) }).send() }, + // 获取用户信息 (通过用户ID) - 使用用户列表API并客户端过滤 + getUserById(userId, callback) { + // 使用现有的用户列表API,获取所有用户然后客户端过滤 + RequestService.sendRequest() + .url(`${getServiceUrl()}/admin/users?page=1&limit=1000`) + .method('GET') + .success((res) => { + RequestService.clearRequestTime() + console.log('getUserById API response:', res); + + // 检查响应结构并查找指定用户 + if (res.data && res.data.code === 0 && res.data.data && res.data.data.list && Array.isArray(res.data.data.list)) { + // 在用户列表中查找指定ID的用户 (注意字段名是userid,不是id) + const userInfo = res.data.data.list.find(user => + user.userid === userId || user.userid === parseInt(userId) || user.userid === String(userId) + ); + + if (userInfo) { + console.log('Found user info:', userInfo); + const formattedResponse = { + data: { + code: 0, + msg: 'success', + data: userInfo + } + }; + callback(formattedResponse); + } else { + console.log('User not found in list, userId:', userId); + console.log('Available user IDs:', res.data.data.list.map(u => u.userid)); + // 用户不存在 + const errorResponse = { + data: { + code: 1, + msg: 'User not found', + data: null + } + }; + callback(errorResponse); + } + } else { + console.error('Invalid response structure for getUserById:', res); + const errorResponse = { + data: { + code: 1, + msg: 'Invalid response structure', + data: null + } + }; + callback(errorResponse); + } + }) + .networkFail((err) => { + console.error('获取用户信息失败:', err) + RequestService.reAjaxFun(() => { + this.getUserById(userId, callback) + }) + }).send() + }, // 重置用户密码 resetUserPassword(id, callback) { RequestService.sendRequest() diff --git a/main/manager-web/src/components/DeviceItem.vue b/main/manager-web/src/components/DeviceItem.vue index 4ec8ee64e..dd80a94cf 100644 --- a/main/manager-web/src/components/DeviceItem.vue +++ b/main/manager-web/src/components/DeviceItem.vue @@ -6,8 +6,8 @@ {{ device.agentName }} -
- Owner: {{ device.ownerUsername }} +
+ Owner: {{ device.ownerUsername || `User ID: ${device.userId}` }}
diff --git a/main/manager-web/src/views/home.vue b/main/manager-web/src/views/home.vue index b246c0d90..a58773953 100644 --- a/main/manager-web/src/views/home.vue +++ b/main/manager-web/src/views/home.vue @@ -79,7 +79,8 @@ export default { skeletonCount: localStorage.getItem('skeletonCount') || 8, showChatHistory: false, currentAgentId: '', - currentAgentName: '' + currentAgentName: '', + userCache: {} // 缓存用户信息,避免重复请求 } }, @@ -293,8 +294,10 @@ export default { this.originalDevices = basicDevices; this.handleSearchReset(); - // 异步获取模型名称并更新 + // 异步获取模型名称、设备数量和用户信息 this.fetchModelNamesForDevices(); + this.fetchDeviceCountsForAgents(); + this.fetchOwnerNamesForAgents(); }, // 获取所有设备的模型名称 @@ -357,6 +360,120 @@ export default { console.log(`Updated ${field} for ${originalId} to: ${newName}`); }, + // 获取所有智能体的设备数量 + fetchDeviceCountsForAgents() { + console.log('Fetching device counts for agents...'); + + this.originalDevices.forEach(device => { + if (device.agentId) { + Api.device.getAgentBindDevices(device.agentId, (response) => { + console.log(`Device response for agent ${device.agentId}:`, response); + + if (response.data && response.data.code === 0) { + const devices = response.data.data || []; + const deviceCount = Array.isArray(devices) ? devices.length : 0; + + // 更新设备数量 + this.updateDeviceInfo(device.agentId, 'deviceCount', deviceCount); + console.log(`Updated device count for ${device.agentName}: ${deviceCount}`); + } + }); + } + }); + }, + + // 获取智能体所有者姓名 + fetchOwnerNamesForAgents() { + console.log('Fetching owner names for agents...'); + + const isAdmin = this.$store.getters.getIsSuperAdmin; + + if (isAdmin) { + // 管理员:需要获取每个用户的真实姓名 + const uniqueUserIds = [...new Set(this.originalDevices.map(d => d.userId).filter(Boolean))]; + console.log('Unique user IDs to fetch:', uniqueUserIds); + + uniqueUserIds.forEach(userId => { + // 检查缓存 + if (this.userCache[userId] && this.userCache[userId] !== `User ${userId}`) { + console.log(`Using cached user info for ${userId}:`, this.userCache[userId]); + this.updateOwnerNameForUserId(userId, this.userCache[userId]); + return; + } + + // 从API获取用户信息 + console.log(`Fetching user info for ${userId} via API...`); + Api.admin.getUserById(userId, (response) => { + console.log(`User info response for ${userId}:`, response); + + if (response.data && response.data.code === 0) { + const userData = response.data.data; + console.log(`Raw user data for ${userId}:`, userData); + const username = userData.mobile || userData.username || userData.email || userData.name || `User ${userId}`; + + // 缓存用户信息 + this.userCache[userId] = username; + + // 更新显示 + this.updateOwnerNameForUserId(userId, username); + + console.log(`Successfully updated owner name for userId ${userId}: ${username}`); + } else { + console.error(`Failed to get user info for ${userId}:`, response); + console.error('API response details:', response.data); + // 如果获取失败,显示默认名称 + const fallbackName = `User ${userId}`; + this.userCache[userId] = fallbackName; + this.updateOwnerNameForUserId(userId, fallbackName); + console.log(`Using fallback name for userId ${userId}: ${fallbackName}`); + } + }); + }); + } else { + // 普通用户:获取当前用户信息 + Api.user.getUserInfo((response) => { + console.log('Current user info:', response); + + if (response.data && response.data.code === 0) { + const currentUser = response.data.data; + const currentUsername = currentUser.username || currentUser.mobile || currentUser.email || 'Current User'; + + // 所有智能体都是自己的 + this.originalDevices.forEach(device => { + this.updateDeviceInfo(device.agentId, 'ownerUsername', currentUsername); + }); + } + }); + } + }, + + // 根据userId更新所有者姓名 + updateOwnerNameForUserId(userId, username) { + this.originalDevices.forEach(device => { + if (device.userId === userId) { + this.updateDeviceInfo(device.agentId, 'ownerUsername', username); + } + }); + }, + + // 更新设备信息(通用方法) + updateDeviceInfo(agentId, field, value) { + this.originalDevices = this.originalDevices.map(device => { + if (device.agentId === agentId) { + return { ...device, [field]: value }; + } + return device; + }); + + // 同时更新搜索结果 + this.devices = this.devices.map(device => { + if (device.agentId === agentId) { + return { ...device, [field]: value }; + } + return device; + }); + }, + handleShowChatHistory({ agentId, agentName }) { this.currentAgentId = agentId; this.currentAgentName = agentName; diff --git a/main/xiaozhi-server/plugins_func/functions/play_music.py b/main/xiaozhi-server/plugins_func/functions/play_music.py index 8686746e4..cfb324f0e 100644 --- a/main/xiaozhi-server/plugins_func/functions/play_music.py +++ b/main/xiaozhi-server/plugins_func/functions/play_music.py @@ -450,7 +450,7 @@ def initialize_multilingual_music_system(conn): try: semantic_config = conn.config.get('semantic_search', {}) - if semantic_config.get('enabled', False): + if semantic_config.get('enabled', True): SEMANTIC_SEARCH = SemanticMusicSearch(semantic_config) if SEMANTIC_SEARCH.initialize():