diff --git a/main/live-agent-api/api/v1/internal.py b/main/live-agent-api/api/v1/internal.py index 019dffe8a..5e7800eb0 100644 --- a/main/live-agent-api/api/v1/internal.py +++ b/main/live-agent-api/api/v1/internal.py @@ -4,8 +4,11 @@ from sqlalchemy.ext.asyncio import AsyncSession from infra import get_db from infra.fishaudio import get_fish_audio from services.agent_service import agent_service +from services.device_service import device_service from utils.response import success_response from schemas.agent import AgentConfigResponse +from schemas.device import DefaultAgentResponse, DeviceAgentResolveResponse +from fastapi import Query router = APIRouter() @@ -57,3 +60,90 @@ async def get_agent_config( return success_response(data=response.model_dump()) + +@router.get("/devices/{device_id}/agent-by-wake", summary="Resolve agent by wake word or default") +async def resolve_agent_by_wake( + device_id: str, + wake_word: str | None = Query(None, description="Wake word to match"), + db: AsyncSession = Depends(get_db), + fish_client = Depends(get_fish_audio), +): + """ + Resolve device agent by wake word; fallback to default binding. + Returns agent config for runtime consumption. + """ + resolved = await device_service.resolve_agent_by_wake_word( + db=db, + device_id=device_id, + wake_word=wake_word, + ) + + # enrich language via Fish Audio if voice_id exists + agent_cfg = resolved.agent_config + language = agent_cfg.language + if agent_cfg.voice_id and language is None: + try: + fish_voice = await fish_client.voices.get(agent_cfg.voice_id) + if fish_voice and hasattr(fish_voice, "languages") and fish_voice.languages: + language = ( + fish_voice.languages[0] + if isinstance(fish_voice.languages, list) + else fish_voice.languages + ) + except Exception: + language = None + agent_cfg.language = language + + return success_response( + data=DeviceAgentResolveResponse( + device_id=resolved.device_id, + agent_id=resolved.agent_id, + is_default=resolved.is_default, + match_type=resolved.match_type, + agent_config=agent_cfg, + ).model_dump() + ) + + +@router.get("/devices/{device_id}/default-agent", summary="Get device default agent (internal)") +async def get_default_agent( + device_id: str, + db: AsyncSession = Depends(get_db), + fish_client = Depends(get_fish_audio), +): + """ + Get default agent binding for a device (fallback to latest). + """ + binding, agent = await device_service.get_default_agent(db=db, device_id=device_id) + + language = None + if agent.voice_id: + try: + fish_voice = await fish_client.voices.get(agent.voice_id) + if fish_voice and hasattr(fish_voice, "languages") and fish_voice.languages: + language = ( + fish_voice.languages[0] + if isinstance(fish_voice.languages, list) + else fish_voice.languages + ) + except Exception: + language = None + + agent_cfg = AgentConfigResponse( + agent_id=agent.agent_id, + name=agent.name, + voice_id=agent.voice_id, + language=language, + instruction=agent.instruction, + voice_opening=agent.voice_opening, + voice_closing=agent.voice_closing, + ) + + return success_response( + data=DefaultAgentResponse( + device_id=device_id, + agent=agent_cfg, + is_default=binding.is_default, + ).model_dump() + ) + diff --git a/main/live-agent-api/schemas/device.py b/main/live-agent-api/schemas/device.py index 643e4697c..631f8450c 100644 --- a/main/live-agent-api/schemas/device.py +++ b/main/live-agent-api/schemas/device.py @@ -1,6 +1,8 @@ from datetime import datetime from typing import Optional, List +from typing import Literal from pydantic import BaseModel, Field +from schemas.agent import AgentConfigResponse # ==================== Request Schemas ==================== @@ -58,3 +60,19 @@ class DeviceBoundAgentsResponse(BaseModel): device_id: str agents: List[AgentBindingResponse] = [] + +class DeviceAgentResolveResponse(BaseModel): + """Resolve agent for device by wake word or default""" + device_id: str + agent_id: str + is_default: bool + match_type: Literal["wake_word", "default"] + agent_config: AgentConfigResponse + + +class DefaultAgentResponse(BaseModel): + """Default agent for a device""" + device_id: str + agent: AgentConfigResponse + is_default: bool = True + diff --git a/main/live-agent-api/services/device_service.py b/main/live-agent-api/services/device_service.py index 237a55dc7..a2b66e764 100644 --- a/main/live-agent-api/services/device_service.py +++ b/main/live-agent-api/services/device_service.py @@ -2,15 +2,17 @@ from typing import List from sqlalchemy.ext.asyncio import AsyncSession from repositories.device import Device, AgentDeviceBinding, DeviceModel -from repositories.agent import Agent +from repositories.agent import Agent, AgentModel from utils.exceptions import NotFoundException, BadRequestException from schemas.device import ( DeviceResponse, DeviceWithBindingsResponse, DeviceListResponse, AgentBindingResponse, - DeviceBoundAgentsResponse + DeviceBoundAgentsResponse, + DeviceAgentResolveResponse, ) +from schemas.agent import AgentConfigResponse class DeviceService: @@ -190,6 +192,86 @@ class DeviceService: ] ) + async def get_default_agent( + self, + db: AsyncSession, + device_id: str + ) -> tuple[AgentDeviceBinding, AgentModel]: + """Get default agent binding; fallback to latest binding""" + device = await Device.get_by_id(db, device_id) + if not device: + raise NotFoundException("Device not found") + + binding = await AgentDeviceBinding.get_default_binding(db, device_id) + if not binding: + bindings = await AgentDeviceBinding.get_bindings_by_device(db, device_id) + if not bindings: + raise NotFoundException("Device has no bound agents") + binding = bindings[0] + + agent = await Agent.get_by_id(db, binding.agent_id) + if not agent: + raise NotFoundException("Agent not found for binding") + + return binding, agent + + async def resolve_agent_by_wake_word( + self, + db: AsyncSession, + device_id: str, + wake_word: str | None + ) -> DeviceAgentResolveResponse: + """ + Resolve agent for device by wake_word; fallback to default binding. + """ + device = await Device.get_by_id(db, device_id) + if not device: + raise NotFoundException("Device not found") + + bindings = await AgentDeviceBinding.get_bindings_by_device(db, device_id) + if not bindings: + raise NotFoundException("Device has no bound agents") + + matched_binding = None + matched_agent = None + match_type = "default" + + if wake_word: + for b in bindings: + agent = await Agent.get_by_id(db, b.agent_id) + if agent and agent.wake_word and agent.wake_word.lower() == wake_word.lower(): + matched_binding = b + matched_agent = agent + match_type = "wake_word" + break + + if not matched_binding: + # fallback to default binding + matched_binding = await AgentDeviceBinding.get_default_binding(db, device_id) + if not matched_binding: + matched_binding = bindings[0] + matched_agent = await Agent.get_by_id(db, matched_binding.agent_id) + if not matched_agent: + raise NotFoundException("Agent not found for binding") + + agent_config = AgentConfigResponse( + agent_id=matched_agent.agent_id, + name=matched_agent.name, + voice_id=matched_agent.voice_id, + language=None, + instruction=matched_agent.instruction, + voice_opening=matched_agent.voice_opening, + voice_closing=matched_agent.voice_closing, + ) + + return DeviceAgentResolveResponse( + device_id=device_id, + agent_id=matched_agent.agent_id, + is_default=matched_binding.is_default, + match_type=match_type, + agent_config=agent_config, + ) + async def _build_device_with_bindings( self, db: AsyncSession, diff --git a/main/xiaozhi-server/config/live_agent_api_client.py b/main/xiaozhi-server/config/live_agent_api_client.py index 86df42255..cabcd17a2 100644 --- a/main/xiaozhi-server/config/live_agent_api_client.py +++ b/main/xiaozhi-server/config/live_agent_api_client.py @@ -110,6 +110,44 @@ def get_agent_config_from_api(agent_id: str, config: dict = None) -> Optional[di return None +def get_agent_by_wake_from_api( + device_id: str, + wake_word: str | None = None, + config: dict = None, +) -> Optional[dict]: + """ + Resolve agent for device by wake word; fallback to default binding. + """ + try: + if LiveAgentApiClient._instance is None: + if config is None: + logger.error("LiveAgentApiClient not initialized and no config provided") + return None + LiveAgentApiClient(config) + + params = {} + if wake_word: + params["wake_word"] = wake_word + result = LiveAgentApiClient._request( + "GET", f"/internal/devices/{device_id}/agent-by-wake", params=params + ) + + if result.get("code") == 200 and "data" in result: + logger.info( + f"Successfully resolved agent by wake_word for device_id={device_id}" + ) + return result["data"] + else: + logger.error(f"Invalid response for agent-by-wake: {result}") + return None + except httpx.HTTPStatusError as e: + logger.error(f"HTTP error resolving agent by wake_word: {e}") + return None + except Exception as e: + logger.error(f"Failed to resolve agent by wake_word for {device_id}: {e}") + return None + + def report_chat_message( agent_id: str, role: int, diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 4322b2983..f5ea03295 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -43,7 +43,10 @@ from config.manage_api_client import DeviceNotFoundException, DeviceBindExceptio from core.utils.prompt_manager import PromptManager from core.utils.voiceprint_provider import VoiceprintProvider from core.utils import textUtils -from config.live_agent_api_client import get_agent_config_from_api +from config.live_agent_api_client import ( + get_agent_config_from_api, + get_agent_by_wake_from_api, +) TAG = __name__ auto_import_modules("plugins_func.functions") @@ -84,6 +87,7 @@ class ConnectionHandler: self.max_output_size = 0 self.chat_history_conf = 0 self.audio_format = "opus" + self.defer_agent_init = False # 客户端状态相关 self.client_abort = False @@ -423,6 +427,15 @@ class ConnectionHandler: ) self.logger = create_connection_logger(self.selected_module_str) + # 缺少 agent-id 时,延后 TTS/LLM 初始化,待唤醒词解析后再加载 + if self.read_config_from_live_agent_api and not self.agent_id: + self.defer_agent_init = True + self.logger.bind(tag=TAG).info( + "agent-id missing, defer LLM/TTS init until wake word resolves agent" + ) + else: + self._initialize_agent_config() + """初始化本地组件""" if self.vad is None: self.vad = self._vad @@ -437,29 +450,39 @@ class ConnectionHandler: self.asr.open_audio_channels(self), self.loop ) + init_llm = not self.defer_agent_init + init_tts = not self.defer_agent_init + init_memory = not self.defer_agent_init + init_intent = not self.defer_agent_init + # prewarm LLM first connection - if isinstance(self.llm, LLMProviderBase): - self.llm.prewarm() + if init_llm and isinstance(self.llm, LLMProviderBase): + self.llm.prewarm() """加载记忆""" - self._initialize_memory() + if init_memory: + self._initialize_memory() """加载意图识别""" - self._initialize_intent() + if init_intent: + self._initialize_intent() """更新系统提示词(必须在 TTS 初始化前,以便加载 role 的 TTS 配置)""" - self._init_prompt_enhancement() + if init_tts or init_llm: + self._init_prompt_enhancement() # 初始化 TTS(在 prompt 初始化之后,以便使用 role 的 TTS 配置) - if self.tts is None: + if init_tts and self.tts is None: self.tts = self._initialize_tts() # 打开语音合成通道 - asyncio.run_coroutine_threadsafe( - self.tts.open_audio_channels(self), self.loop - ) + if init_tts and self.tts: + asyncio.run_coroutine_threadsafe( + self.tts.open_audio_channels(self), self.loop + ) """初始化上报线程""" - self._init_report_threads() + if init_tts or init_llm: + self._init_report_threads() - if self._voice_opening: + if self._voice_opening and self.tts: self.logger.bind(tag=TAG).info(f"send the opening message: {self._voice_opening}") opening_sentence_id = str(uuid.uuid4().hex) @@ -862,20 +885,8 @@ class ConnectionHandler: if not private_config: self.logger.bind(tag=TAG).error(f"Failed to get agent config for {self.agent_id}") return - # self.logger.bind(tag=TAG).info(f"private_config: {private_config}") - # self.logger.bind(tag=TAG).info(f"self.config: {self.config}") - self.config["TTS"]["FishSpeech"]["reference_id"] = private_config["voice_id"] - self.config["TTS"]["FishDualStreamTTS"]["reference_id"] = private_config["voice_id"] - self._instruction = private_config["instruction"] - self._voice_opening = private_config["voice_opening"] - self._voice_closing = private_config["voice_closing"] - self._language = private_config["language"] - - # Set chat history config for live-agent-api mode - # 0: disable, 1: text only, 2: text + audio - live_api_config = self.config.get("live-agent-api", {}) - self.chat_history_conf = live_api_config.get("chat_history_conf", 2) - + self._apply_agent_runtime_config(private_config) + init_llm, init_tts, init_memory, init_intent = ( True, True, @@ -913,6 +924,93 @@ class ConnectionHandler: if modules.get("memory", None) is not None: self.memory = modules["memory"] + def _apply_agent_runtime_config(self, private_config: dict): + """Apply agent-specific runtime config to connection""" + if not private_config: + return + voice_id = private_config.get("voice_id") + if voice_id: + if "TTS" in self.config and "FishSpeech" in self.config.get("TTS", {}): + self.config["TTS"]["FishSpeech"]["reference_id"] = voice_id + if "TTS" in self.config and "FishDualStreamTTS" in self.config.get("TTS", {}): + self.config["TTS"]["FishDualStreamTTS"]["reference_id"] = voice_id + self._instruction = private_config.get("instruction", self._instruction) + self._voice_opening = private_config.get("voice_opening", self._voice_opening) + self._voice_closing = private_config.get("voice_closing", self._voice_closing) + self._language = private_config.get("language", self._language) + + # Set chat history config for live-agent-api mode + # 0: disable, 1: text only, 2: text + audio + live_api_config = self.config.get("live-agent-api", {}) + self.chat_history_conf = live_api_config.get("chat_history_conf", 2) + + async def ensure_agent_ready(self, wake_word: str | None = None) -> bool: + """ + Resolve agent when missing and initialize LLM/TTS lazily. + """ + if not self.read_config_from_live_agent_api: + return True + if not self.defer_agent_init and self.tts and self.llm: + return True + + private_config = None + if not self.agent_id: + resolved = get_agent_by_wake_from_api( + self.device_id, wake_word=wake_word, config=self.config + ) + if not resolved: + self.logger.bind(tag=TAG).error( + f"Failed to resolve agent by wake_word for device {self.device_id}" + ) + self.need_bind = True + return False + self.agent_id = resolved.get("agent_id") + private_config = resolved.get("agent_config") + + if private_config is None: + private_config = get_agent_config_from_api(self.agent_id, self.config) + if not private_config: + self.logger.bind(tag=TAG).error( + f"Failed to get agent config for {self.agent_id}" + ) + return False + + self._apply_agent_runtime_config(private_config) + self.defer_agent_init = False + + try: + modules = initialize_modules( + self.logger, + self.config, + False, + False, + True, + True, + False, + False, + ) + except Exception as e: + self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}") + modules = {} + if modules.get("llm", None) is not None: + self.llm = modules["llm"] + if isinstance(self.llm, LLMProviderBase): + self.llm.prewarm() + if modules.get("tts", None) is not None: + self.tts = modules["tts"] + asyncio.run_coroutine_threadsafe( + self.tts.open_audio_channels(self), self.loop + ) + if modules.get("intent", None) is not None: + self.intent = modules["intent"] + if modules.get("memory", None) is not None: + self.memory = modules["memory"] + + # 初始化 prompt 与上报线程 + self._init_prompt_enhancement() + self._init_report_threads() + return True + def change_system_prompt(self, prompt): self.prompt = prompt # 更新系统prompt至上下文 diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 8bbe8e22d..01c05dfa7 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -536,6 +536,11 @@ async def startToChat(conn, text: str, multimodal_content: List[Dict[str, Any]] text: Text content multimodal_content: Optional multimodal content """ + if getattr(conn, "defer_agent_init", False) and not conn.agent_id and getattr(conn, "read_config_from_live_agent_api", False): + ready = await conn.ensure_agent_ready() + if not ready: + return + # check if input is JSON format (contains speaker information) speaker_name = None actual_text = text diff --git a/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py index 99a673547..b0d4b6068 100644 --- a/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py +++ b/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py @@ -100,6 +100,11 @@ class ListenTextMessageHandler(TextMessageHandler): await send_tts_message(conn, "stop", None) conn.client_is_speaking = False elif is_wakeup_words: + if (getattr(conn, "defer_agent_init", False) or not conn.agent_id) and getattr(conn, "read_config_from_live_agent_api", False): + ready = await conn.ensure_agent_ready(filtered_text) + if not ready: + conn.logger.bind(tag=TAG).error("未能解析 agent,结束会话") + return conn.just_woken_up = True # Record timestamp for correct message ordering report_time = int(time.time())