diff --git a/main/live-agent-api/api/v1/agents.py b/main/live-agent-api/api/v1/agents.py index 7c3bea6f9..22258d956 100644 --- a/main/live-agent-api/api/v1/agents.py +++ b/main/live-agent-api/api/v1/agents.py @@ -6,6 +6,7 @@ from infra import get_db, get_s3 from services.agent_service import agent_service from utils.response import success_response from api.auth import get_current_user_id +from schemas.agent import AgentResponse router = APIRouter() @@ -43,7 +44,20 @@ async def get_agent_detail( ): """Get agent detail""" agent = await agent_service.get_agent_detail(db=db, agent_id=agent_id) - return success_response(data=agent.model_dump()) + + + agent_response = AgentResponse( + agent_id=agent.agent_id, + name=agent.name, + avatar_url=agent.avatar_url, + description=agent.description, + voice_id=agent.voice_id, + instruction=agent.instruction, + voice_opening=agent.voice_opening, + voice_closing=agent.voice_closing, + created_at=agent.created_at, + ) + return success_response(data=agent_response.model_dump()) @router.post("", summary="Create Agent") diff --git a/main/live-agent-api/api/v1/internal.py b/main/live-agent-api/api/v1/internal.py index 03aecea87..019dffe8a 100644 --- a/main/live-agent-api/api/v1/internal.py +++ b/main/live-agent-api/api/v1/internal.py @@ -2,18 +2,58 @@ from fastapi import APIRouter, Depends 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 utils.response import success_response +from schemas.agent import AgentConfigResponse router = APIRouter() -@router.get("/agents/{agent_id}/config", summary="Get a specified agent's config") +@router.get("/agents/{agent_id}/config", summary="Get agent config for backend services") async def get_agent_config( agent_id: str, - db: AsyncSession = Depends(get_db) + db: AsyncSession = Depends(get_db), + fish_client = Depends(get_fish_audio) ): - """Get agent configuration for xiaozhi-server""" - config = await agent_service.get_agent_config(db=db, agent_id=agent_id) - return success_response(data=config.model_dump()) + """ + Get agent runtime configuration for xiaozhi-server + + This is an internal API for service-to-service communication: + - No authentication required + - Returns agent config with voice language info from Fish Audio + - Used by xiaozhi-server to drive AI conversations + + Flow: + 1. Get agent config by agent_id + 2. If voice_id exists, fetch voice info from Fish Audio + 3. Extract language and merge into response + """ + # Step 1: Get agent config + agent = await agent_service.get_agent_detail(db=db, agent_id=agent_id) + + # Step 2: If voice_id exists, fetch language from Fish Audio + 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: + # Fish Audio returns a list of languages, take the first one + language = fish_voice.languages[0] if isinstance(fish_voice.languages, list) else fish_voice.languages + except Exception as e: + # If Fish Audio API fails, log but don't fail the request + print(f"Warning: Failed to fetch voice language for {agent.voice_id}: {e}") + + # Step 3: Merge voice language into response + response = 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=response.model_dump()) diff --git a/main/live-agent-api/api/v1/voices.py b/main/live-agent-api/api/v1/voices.py index cd27c3d74..6c3f3043d 100644 --- a/main/live-agent-api/api/v1/voices.py +++ b/main/live-agent-api/api/v1/voices.py @@ -3,7 +3,7 @@ from botocore.args import logger from fastapi import APIRouter, Depends, Query, Form, File, UploadFile from sqlalchemy.ext.asyncio import AsyncSession -from infra import get_db +from infra import get_db, get_s3 from infra.fishaudio import get_fish_audio from services.voice_service import voice_service from schemas.voice import ( @@ -138,36 +138,36 @@ async def get_my_voices( async def clone_voice( audio_file: UploadFile = File(..., description="Audio file for cloning"), text: Optional[str] = Form(None, description="Optional transcription text"), - fish_client = Depends(get_fish_audio) + current_user_id: str = Depends(get_current_user_id), + db: AsyncSession = Depends(get_db), + fish_client = Depends(get_fish_audio), + s3 = Depends(get_s3) ): """ Clone a voice from uploaded audio file - - Supports both direct audio upload and recorded audio - - Text parameter is optional (required for recorded audio) + - Requires authentication + - Stores the original audio in S3 + - Creates voice record in database with default name + - Use PUT /{voice_id} to update name and description later - Uses Fish Audio's fast training mode (typically 30s-2min) """ - # Clone voice - voice_id, samples = await voice_service.clone_voice( + # Clone voice, upload to S3, and save to database + voice = await voice_service.clone_voice( + db=db, + s3=s3, fish_client=fish_client, + owner_id=current_user_id, audio_file=audio_file, text=text ) - # Build response - if samples: - sample = AudioSample( - title=samples[0].title, - text=samples[0].text, - audio=samples[0].audio - ) - else: - sample = None return success_response( data={ - "voice_id": voice_id, - "sample": sample, + "voice_id": voice.voice_id, + "sample_url": voice.sample_url, # S3 URL of stored audio + "sample_text": voice.sample_text # Transcription text }, message="Voice cloned successfully" ) @@ -185,6 +185,7 @@ async def add_voice( Add a Fish Audio voice to user's my voices - Creates a reference to the Fish Audio voice - Name is provided by client (from Fish voice title) + - For cloned voices, can include sample_url and sample_text """ voice = await voice_service.add_voice( db=db, @@ -192,7 +193,9 @@ async def add_voice( owner_id=current_user_id, voice_id=voice_id, name=request.name, - desc=request.desc + desc=request.desc, + sample_url=request.sample_url, + sample_text=request.sample_text ) # Build response @@ -200,6 +203,8 @@ async def add_voice( data=LiveAgentVoice( voice_id=voice.voice_id, name=voice.name, + desc=voice.desc, + created_at=voice.created_at, ).model_dump(exclude_none=True), message="Voice added successfully" ) diff --git a/main/live-agent-api/init_db.sql b/main/live-agent-api/init_db.sql index e81c24d2f..db4e9c61a 100644 --- a/main/live-agent-api/init_db.sql +++ b/main/live-agent-api/init_db.sql @@ -66,6 +66,8 @@ CREATE TABLE IF NOT EXISTS voices ( owner_id VARCHAR(50) NOT NULL, name VARCHAR(100) NOT NULL, "desc" TEXT NOT NULL DEFAULT '', + sample_url TEXT, + sample_text TEXT, created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), updated_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), CONSTRAINT fk_voices_owner FOREIGN KEY (owner_id) @@ -84,6 +86,8 @@ COMMENT ON COLUMN voices.voice_id IS 'Fish Audio voice ID'; COMMENT ON COLUMN voices.owner_id IS 'User ID of voice owner'; COMMENT ON COLUMN voices.name IS 'Voice display name'; COMMENT ON COLUMN voices."desc" IS 'Voice description'; +COMMENT ON COLUMN voices.sample_url IS 'S3 URL of the original audio sample (for cloned voices)'; +COMMENT ON COLUMN voices.sample_text IS 'Transcription text of the audio sample (for cloned voices)'; -- ==================== Table: agent_templates ==================== -- Pre-configured agent templates diff --git a/main/live-agent-api/repositories/voice.py b/main/live-agent-api/repositories/voice.py index 0af5bc715..6f83fb84d 100644 --- a/main/live-agent-api/repositories/voice.py +++ b/main/live-agent-api/repositories/voice.py @@ -29,6 +29,10 @@ class VoiceModel(Base): name: Mapped[str] = mapped_column(String(100), nullable=False) desc: Mapped[str] = mapped_column(Text, nullable=False) + # Audio sample information (for cloned voices) + sample_url: Mapped[str | None] = mapped_column(Text, nullable=True) + sample_text: Mapped[str | None] = mapped_column(Text, nullable=True) + # Timestamps created_at: Mapped[datetime] = mapped_column( TIMESTAMP(timezone=True), @@ -161,14 +165,18 @@ class Voice: voice_id: str, owner_id: str, name: str, - desc: str + desc: str, + sample_url: Optional[str] = None, + sample_text: Optional[str] = None ) -> VoiceModel: """Create a new voice""" voice = VoiceModel( voice_id=voice_id, owner_id=owner_id, name=name, - desc=desc + desc=desc, + sample_url=sample_url, + sample_text=sample_text ) db.add(voice) await db.commit() @@ -180,18 +188,30 @@ class Voice: db: AsyncSession, voice_id: str, owner_id: str, - name: str, - desc: str + name: Optional[str] = None, + desc: Optional[str] = None ) -> VoiceModel: - """Update a voice""" + """Update a voice (only updates provided fields)""" + # Build update values dict with only non-None values + update_values = {} + if name is not None: + update_values['name'] = name + if desc is not None: + update_values['desc'] = desc + + # If no fields to update, just return the existing voice + if not update_values: + voice = await Voice.get_by_voice_and_owner(db, voice_id, owner_id) + return voice + stmt = ( update(VoiceModel) .where(VoiceModel.voice_id == voice_id) .where(VoiceModel.owner_id == owner_id) - .values(name=name, desc=desc) + .values(**update_values) .returning(VoiceModel) ) - result =await db.execute(stmt) + result = await db.execute(stmt) await db.commit() return result.scalar_one() diff --git a/main/live-agent-api/schemas/agent.py b/main/live-agent-api/schemas/agent.py index bd4b47850..9b197aae6 100644 --- a/main/live-agent-api/schemas/agent.py +++ b/main/live-agent-api/schemas/agent.py @@ -35,7 +35,6 @@ class AgentResponse(BaseModel): voice_opening: Optional[str] = None voice_closing: Optional[str] = None created_at: datetime - updated_at: datetime class Config: from_attributes = True @@ -53,10 +52,8 @@ class AgentConfigResponse(BaseModel): agent_id: str name: str voice_id: Optional[str] = None + language: Optional[str] = None # Voice language from Fish Audio instruction: str voice_opening: Optional[str] = None voice_closing: Optional[str] = None - - class Config: - from_attributes = True diff --git a/main/live-agent-api/schemas/voice.py b/main/live-agent-api/schemas/voice.py index 1c70d79ab..85f15be68 100644 --- a/main/live-agent-api/schemas/voice.py +++ b/main/live-agent-api/schemas/voice.py @@ -23,6 +23,8 @@ class VoiceAddRequest(BaseModel): """Voice add request""" name: str = Field(..., min_length=1, max_length=100, description="Voice name") desc: str = Field(..., max_length=500, description="Voice description") + sample_url: Optional[str] = Field(None, description="URL of stored audio sample (for cloned voices)") + sample_text: Optional[str] = Field(None, description="Transcription text (for cloned voices)") # ==================== Response Schemas ==================== @@ -40,7 +42,7 @@ class LiveAgentVoice(BaseModel): samples: Optional[List[AudioSample]] = None - created_at: datetime + created_at: Optional[datetime] = None diff --git a/main/live-agent-api/services/agent_service.py b/main/live-agent-api/services/agent_service.py index e6b6e7d62..29f69dcac 100644 --- a/main/live-agent-api/services/agent_service.py +++ b/main/live-agent-api/services/agent_service.py @@ -40,7 +40,7 @@ class AgentService: """ agents, next_cursor, has_more = await Agent.get_agents_by_owner( db, - owner_id=owner_id, + owner_id=owner_id, cursor=cursor, limit=page_size ) @@ -56,13 +56,13 @@ class AgentService: self, db: AsyncSession, agent_id: str - ) -> AgentResponse: + ) -> AgentModel: """Get agent detail""" agent = await Agent.get_by_id(db, agent_id) if not agent: raise NotFoundException("Agent not found") - return AgentResponse.model_validate(agent) + return agent async def create_agent( self, @@ -178,18 +178,7 @@ class AgentService: # Delete agent await Agent.delete(db, agent_id) - - async def get_agent_config( - self, - db: AsyncSession, - agent_id: str - ) -> AgentConfigResponse: - """Get agent configuration for xiaozhi-server""" - agent = await Agent.get_by_id(db, agent_id) - if not agent: - raise NotFoundException("Agent not found") - return AgentConfigResponse.model_validate(agent) agent_service = AgentService() diff --git a/main/live-agent-api/services/voice_service.py b/main/live-agent-api/services/voice_service.py index 9c0be14e9..3a9c02073 100644 --- a/main/live-agent-api/services/voice_service.py +++ b/main/live-agent-api/services/voice_service.py @@ -6,6 +6,9 @@ from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as Fis from repositories import VoiceModel, Voice from utils.ulid import generate_voice_id + +from repositories import FileRepository +from datetime import datetime, timezone class VoiceService: """Voice service layer""" @@ -90,28 +93,45 @@ class VoiceService: async def clone_voice( self, + db: AsyncSession, + s3, # S3 client for storing audio fish_client: AsyncFishAudio, + owner_id: str, audio_file: UploadFile, text: Optional[str] = None - ) -> Tuple[str, List[FishSample]]: + ) -> VoiceModel: """ - Clone a voice using Fish Audio API + Clone a voice using Fish Audio API, store audio, and save to database Args: db: Database session + s3: S3 client for storing audio fish_client: Fish Audio client - name: Voice name owner_id: User ID - name: Voice name audio_file: Audio file to clone text: Optional transcription text Returns: Created VoiceModel """ + # Generate voice_id for our system + voice_id = generate_voice_id() + # Read audio file content audio_content = await audio_file.read() - voice_id = generate_voice_id() + + # Reset file pointer for S3 upload + await audio_file.seek(0) + + # Upload audio to S3 for storage (using voice_id as filename) + + sample_url = await FileRepository.upload( + s3=s3, + file=audio_file, + folder="voice_samples", + custom_filename=voice_id + ) + # Call Fish Audio API to clone voice fish_voice: FishVoice = await fish_client.voices.create( title=f"live_agent_{voice_id}", @@ -121,7 +141,22 @@ class VoiceService: visibility="private", enhance_audio_quality=True ) - return fish_voice.id, fish_voice.samples + + # Create voice record in database + + default_name = f"{owner_id}'s Cloned Voice {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M')}" + + voice = await Voice.create( + db=db, + voice_id=fish_voice.id, # Use Fish Audio voice ID + owner_id=owner_id, + name=default_name, + desc="", # Empty description, to be updated later + sample_url=sample_url, + sample_text=text + ) + + return voice async def add_voice( self, @@ -131,6 +166,8 @@ class VoiceService: voice_id: str, name: str, desc: str, + sample_url: Optional[str] = None, + sample_text: Optional[str] = None ) -> VoiceModel: """ Add a Fish Audio voice to user's my voices @@ -142,6 +179,8 @@ class VoiceService: voice_id: Audio voice ID name: Voice name desc: Voice description + sample_url: Optional URL of stored audio sample (for cloned voices) + sample_text: Optional transcription text (for cloned voices) Returns: Created VoiceModel @@ -158,7 +197,9 @@ class VoiceService: voice_id=voice_id, # Use Fish Audio voice ID directly owner_id=owner_id, name=name, - desc=desc + desc=desc, + sample_url=sample_url, + sample_text=sample_text ) return voice @@ -193,8 +234,8 @@ class VoiceService: db: AsyncSession, voice_id: str, owner_id: str, - name: str, - desc: str + name: Optional[str] = None, + desc: Optional[str] = None ) -> VoiceModel: """ Update voice name and/or description @@ -203,13 +244,13 @@ class VoiceService: db: Database session voice_id: Voice ID owner_id: User ID - name: New voice name - desc: New voice description + name: New voice name (optional) + desc: New voice description (optional) Returns: Updated VoiceModel """ - # Get existing voice + # Get existing voice to verify ownership voice = await Voice.get_by_voice_and_owner( db=db, voice_id=voice_id, @@ -221,7 +262,7 @@ class VoiceService: raise NotFoundException(f"Voice {voice_id} not found or not owned by user") # Update only provided fields - new_voice = await Voice.update( + updated_voice = await Voice.update( db=db, voice_id=voice_id, owner_id=owner_id, @@ -229,7 +270,7 @@ class VoiceService: desc=desc ) - return new_voice + return updated_voice voice_service = VoiceService() diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py index 4c3f01b19..2859a3f12 100644 --- a/main/xiaozhi-server/config/config_loader.py +++ b/main/xiaozhi-server/config/config_loader.py @@ -2,7 +2,7 @@ import os import yaml from collections.abc import Mapping from config.manage_api_client import init_service, get_server_config, get_agent_models - +from dotenv import load_dotenv def get_project_dir(): """获取项目根目录""" @@ -29,10 +29,24 @@ def load_config(): # 加载默认配置 # default_config = read_config(default_config_path) - custom_config = read_config(custom_config_path) - - if custom_config.get("manager-api", {}).get("url"): - config = get_config_from_api(custom_config) + config = read_config(custom_config_path) + config["read_config_from_live_agent_api"] = True + # load environment variables + load_dotenv() + # tts + select_tts_module = config["selected_module"]["TTS"] + if os.environ.get("REGION") == "LOCAL" and select_tts_module == "FishSpeech": + config["TTS"][select_tts_module]["api_key"] = os.environ.get("FISH_API_KEY") + # asr + select_asr_module = config["selected_module"]["ASR"] + if os.environ.get("REGION") == "LOCAL" and select_asr_module == "GroqASR": + config["ASR"][select_asr_module]["api_key"] = os.environ.get("GROQ_API_KEY") + # llm + select_llm_module = config["selected_module"]["LLM"] + if os.environ.get("REGION") == "LOCAL" and select_llm_module == "GroqLLM": + config["LLM"][select_llm_module]["api_key"] = os.environ.get("GROQ_API_KEY") + # if custom_config.get("manager-api", {}).get("url"): + # config = get_config_from_api(custom_config) # else: # # 合并配置 # config = merge_configs(default_config, custom_config) diff --git a/main/xiaozhi-server/config/live_agent_api_client.py b/main/xiaozhi-server/config/live_agent_api_client.py new file mode 100644 index 000000000..412a167d5 --- /dev/null +++ b/main/xiaozhi-server/config/live_agent_api_client.py @@ -0,0 +1,49 @@ + +import httpx +from config.logger import setup_logging +from typing import Optional + +logger = setup_logging() + +def get_agent_config_from_api(agent_id: str, config: dict) -> Optional[dict]: + """ + Get agent configuration from live-agent-api + + Args: + agent_id: Agent ID + config: System config containing live-agent-api URL + + Returns: + Agent config dict or None if failed + """ + + live_api_config = config.get("live-agent-api", {}) + base_url = live_api_config.get("url", "http://live-agent-api:8080/api/live_agent/v1") + timeout = live_api_config.get("timeout", 10) + + url = f"{base_url}/internal/agents/{agent_id}/config" + + try: + with httpx.Client(timeout=timeout) as client: + response = client.request("GET", url) + response.raise_for_status() + result = response.json() + + # Extract data from success_response format + if result.get("code") == 200 and "data" in result: + agent_config = result["data"] + logger.info(f"Successfully fetched agent config for agent_id={agent_id}") + return agent_config + else: + logger.error(f"Invalid response format from live-agent-api: {result}") + return None + + except httpx.HTTPStatusError as e: + if e.response.status_code == 404: + logger.error(f"Agent not found: agent_id={agent_id}") + else: + logger.error(f"HTTP error fetching agent config: {e}") + return None + except Exception as e: + logger.error(f"Failed to fetch agent config for {agent_id}: {e}") + return None \ No newline at end of file diff --git a/main/xiaozhi-server/core/api/ota_handler.py b/main/xiaozhi-server/core/api/ota_handler.py index b6c88dff7..16bc5c033 100644 --- a/main/xiaozhi-server/core/api/ota_handler.py +++ b/main/xiaozhi-server/core/api/ota_handler.py @@ -80,7 +80,7 @@ class OTAHandler(BaseHandler): self.logger.bind(tag=TAG).info(f"OTA请求ClientID: {client_id}") else: raise Exception("OTA请求ClientID为空") - + data_json = json.loads(data) server_config = self.config["server"] diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index c72ce7f97..961ca6115 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -41,9 +41,9 @@ 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 TAG = __name__ - auto_import_modules("plugins_func.functions") @@ -71,6 +71,7 @@ class ConnectionHandler: self.need_bind = False self.bind_code = None self.read_config_from_api = self.config.get("read_config_from_api", False) + self.read_config_from_live_agent_api = self.config.get("read_config_from_live_agent_api", False) self.websocket = None self.headers = None @@ -160,6 +161,12 @@ class ConnectionHandler: # 初始化提示词管理器 self.prompt_manager = PromptManager(config, self.logger) + # agent-related configs + self._instruction = None + self._voice_opening = None + self._voice_closing = None + self._language = None + async def handle_connection(self, ws): try: # 获取并验证headers @@ -176,6 +183,7 @@ class ConnectionHandler: ) self.device_id = self.headers.get("device-id", None) + self.agent_id = self.headers.get("agent-id", None) # 认证通过,继续处理 self.websocket = ws @@ -192,11 +200,12 @@ class ConnectionHandler: # 启动超时检查任务 self.timeout_task = asyncio.create_task(self._check_timeout()) + # todo: welcome message need to be set after private config is loaded self.welcome_msg = self.config["xiaozhi"] self.welcome_msg["session_id"] = self.session_id # 获取差异化配置 - self._initialize_private_config() + self._initialize_agent_config() # 异步初始化 self.executor.submit(self._initialize_components) @@ -404,16 +413,6 @@ class ConnectionHandler: ) self.logger = create_connection_logger(self.selected_module_str) - """初始化组件""" - if self.config.get("prompt") is not None: - user_prompt = self.config["prompt"] - # 使用快速提示词进行初始化 - prompt = self.prompt_manager.get_quick_prompt(user_prompt) - self.change_system_prompt(prompt) - self.logger.bind(tag=TAG).info( - f"快速初始化组件: prompt成功 {prompt[:50]}..." - ) - """初始化本地组件""" if self.vad is None: self.vad = self._vad @@ -446,6 +445,16 @@ class ConnectionHandler: """初始化上报线程""" self._init_report_threads() + if self._voice_opening: + self.logger.bind(tag=TAG).info(f"send the opening message: {self._voice_opening}") + self.tts.tts_text_queue.put(TTSMessageDTO( + sentence_id=str(uuid.uuid4().hex), + sentence_type=SentenceType.MIDDLE, + content_type=ContentType.TEXT, + content_detail=self._voice_opening, + ) + ) + except Exception as e: self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}") @@ -466,9 +475,10 @@ class ConnectionHandler: # 构建增强的系统提示词(返回 (enhanced_prompt, role_tts_config)) result = self.prompt_manager.build_enhanced_prompt( - self.config["prompt"], - self.device_id, - self.client_ip, + user_prompt=self._instruction, + device_id=self.device_id, + client_ip=self.client_ip, + language=self._language, user_persona=user_persona, ) @@ -655,35 +665,6 @@ class ConnectionHandler: init_vad = check_vad_update(self.common_config, private_config) init_asr = check_asr_update(self.common_config, private_config) - if init_vad: - self.config["VAD"] = private_config["VAD"] - self.config["selected_module"]["VAD"] = private_config["selected_module"][ - "VAD" - ] - if init_asr: - self.config["ASR"] = private_config["ASR"] - self.config["selected_module"]["ASR"] = private_config["selected_module"][ - "ASR" - ] - if private_config.get("TTS", None) is not None: - init_tts = True - self.config["TTS"] = private_config["TTS"] - self.config["selected_module"]["TTS"] = private_config["selected_module"][ - "TTS" - ] - # 标记 API 已设置 TTS 配置(优先级1) - self.config["_api_tts_applied"] = True - if private_config.get("LLM", None) is not None: - init_llm = True - self.config["LLM"] = private_config["LLM"] - self.config["selected_module"]["LLM"] = private_config["selected_module"][ - "LLM" - ] - if private_config.get("VLLM", None) is not None: - self.config["VLLM"] = private_config["VLLM"] - self.config["selected_module"]["VLLM"] = private_config["selected_module"][ - "VLLM" - ] if private_config.get("Memory", None) is not None: init_memory = True self.config["Memory"] = private_config["Memory"] @@ -835,6 +816,56 @@ class ConnectionHandler: if hasattr(self, "loop") and self.loop: asyncio.run_coroutine_threadsafe(self.func_handler._initialize(), self.loop) + def _initialize_agent_config(self): + """initialize agent config""" + if not self.read_config_from_live_agent_api: + return + private_config = get_agent_config_from_api(self.agent_id, self.config) + # 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._instruction = private_config["instruction"] + self._voice_opening = private_config["voice_opening"] + self._voice_closing = private_config["voice_closing"] + self._language = private_config["language"] + + init_llm, init_tts, init_memory, init_intent = ( + True, + True, + False, + False, + ) + + init_vad = False + init_asr = True + + try: + modules = initialize_modules( + self.logger, + self.config, + init_vad, + init_asr, + init_llm, + init_tts, + init_memory, + init_intent, + ) + except Exception as e: + self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}") + modules = {} + if modules.get("tts", None) is not None: + self.tts = modules["tts"] + if modules.get("vad", None) is not None: + self.vad = modules["vad"] + if modules.get("asr", None) is not None: + self.asr = modules["asr"] + if modules.get("llm", None) is not None: + self.llm = modules["llm"] + if modules.get("intent", None) is not None: + self.intent = modules["intent"] + if modules.get("memory", None) is not None: + self.memory = modules["memory"] + 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 4eaf9ab1d..55dfe0f7d 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -6,6 +6,7 @@ from core.handle.abortHandle import handleAbortMessage from core.handle.intentHandler import handle_user_intent from core.utils.output_counter import check_device_output_limit from core.handle.sendAudioHandle import send_stt_message, SentenceType +from core.providers.tts.dto.dto import SentenceType, ContentType, TTSMessageDTO TAG = __name__ diff --git a/main/xiaozhi-server/core/providers/tts/fishspeech.py b/main/xiaozhi-server/core/providers/tts/fishspeech.py index 565857f66..25930265a 100644 --- a/main/xiaozhi-server/core/providers/tts/fishspeech.py +++ b/main/xiaozhi-server/core/providers/tts/fishspeech.py @@ -82,12 +82,16 @@ class TTSProvider(TTSProviderBase): super().__init__(config, delete_audio_file) self.model = config.get("model", "s1") - if config.get("private_voice"): - self.reference_id = config.get("private_voice") - else: - self.reference_id = ( - None if not config.get("reference_id") else config.get("reference_id") - ) + # if config.get("private_voice"): + # self.reference_id = config.get("private_voice") + # else: + # self.reference_id = ( + # None if not config.get("reference_id") else config.get("reference_id") + # ) + if config.get("reference_id"): + self.reference_id = config.get("reference_id") + else: + self.reference_id = None self.reference_audio = parse_string_to_list( config.get('ref_audio')if config.get('ref_audio') else config.get("reference_audio") ) diff --git a/main/xiaozhi-server/core/utils/modules_initialize.py b/main/xiaozhi-server/core/utils/modules_initialize.py index afe041098..ff042aef8 100644 --- a/main/xiaozhi-server/core/utils/modules_initialize.py +++ b/main/xiaozhi-server/core/utils/modules_initialize.py @@ -1,6 +1,8 @@ from typing import Dict, Any from config.logger import setup_logging from core.utils import tts, llm, intent, memory, vad, asr +from dotenv import load_dotenv +import os TAG = __name__ logger = setup_logging() diff --git a/main/xiaozhi-server/core/utils/prompt_manager.py b/main/xiaozhi-server/core/utils/prompt_manager.py index b2dd34df4..e4db75299 100644 --- a/main/xiaozhi-server/core/utils/prompt_manager.py +++ b/main/xiaozhi-server/core/utils/prompt_manager.py @@ -156,6 +156,7 @@ class PromptManager: device_id: str, client_ip: str = None, user_persona: str = None, + language: str = None, *args, **kwargs ) -> str: @@ -170,7 +171,7 @@ class PromptManager: # 优先使用 API 传入的 prompt(正式部署场景) profile = user_prompt timezone = self.config.get("timezone", "Asia/Shanghai") - language = self.config.get("language", "en") + language = language self.logger.bind(tag=TAG).info("使用 API 下发的 profile") else: # API 未提供 prompt,尝试加载本地 role 配置(本地开发场景) diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index c0c88fc57..d999b9c1e 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -21,8 +21,8 @@ class WebSocketServer: self.logger, self.config, "VAD" in self.config["selected_module"], - "ASR" in self.config["selected_module"], - "LLM" in self.config["selected_module"], + False, + False, False, "Memory" in self.config["selected_module"], "Intent" in self.config["selected_module"], @@ -75,6 +75,8 @@ class WebSocketServer: websocket.request.headers["device-id"] = query_params["device-id"][0] if "client-id" in query_params: websocket.request.headers["client-id"] = query_params["client-id"][0] + if "agent-id" in query_params: + websocket.request.headers["agent-id"] = query_params["agent-id"][0] if "authorization" in query_params: websocket.request.headers["authorization"] = query_params[ "authorization" diff --git a/main/xiaozhi-server/custom_config.yaml b/main/xiaozhi-server/custom_config.yaml index 5fbc55f17..65f76b5c4 100644 --- a/main/xiaozhi-server/custom_config.yaml +++ b/main/xiaozhi-server/custom_config.yaml @@ -40,6 +40,9 @@ manager-api: # This secret is used for local development, it will be replaced by the actual secret when the server is deployed secret: 613be043-dc7e-4f5e-b775-e318e5bc87a3 +live-agent-api: + url: http://live-agent-api:8080/api/live_agent/v1 + # MySQL配置(用于聊天记录和记忆关联) mysql: host: localhost @@ -189,11 +192,6 @@ prompt: | # 默认系统提示词模板文件 prompt_template: agent-base-prompt.txt -# Role 配置 -# 指定要加载的 role 配置文件(位于 core/roles/data/目录) -# 如果不指定或加载失败,将使用 prompt 字段的内容作为 profile -role_id: hospital_assistant - # 时区配置(用于系统提示词中的时间显示) # 支持的时区格式:Asia/Shanghai, America/New_York, Europe/London 等 # 默认:Asia/Shanghai @@ -407,7 +405,7 @@ ASR: # 3.模型可以选择gpt-4o-transcribe或GPT-4o mini Transcribe type: openai api_key: 你的OpenAI API密钥 - base_url: https://api.openai.com/v1/audio/transcriptions + base_url: https://api.openai.com/v1 model_name: gpt-4o-mini-transcribe output_dir: tmp/ GroqASR: @@ -417,8 +415,8 @@ ASR: # 2.创建api-key https://console.groq.com/keys # 3.模型可以选择whisper-large-v3-turbo或whisper-large-v3(distil-whisper-large-v3-en仅支持英语转录) type: openai - api_key: 你的Groq API密钥 - base_url: https://api.groq.com/openai/v1/audio/transcriptions + api_key: your groq api key + base_url: https://api.groq.com/openai/v1 model_name: whisper-large-v3-turbo output_dir: tmp/ VoskASR: @@ -534,6 +532,11 @@ LLM: model_name: glm-4-flash url: https://open.bigmodel.cn/api/paas/v4/ api_key: 你的chat-glm web key + GroqLLM: + type: openai + model_name: openai/gpt-oss-20b + base_url: https://api.groq.com/openai/v1 + api_key: your groq api key OllamaLLM: # 定义LLM API类型 type: ollama @@ -759,10 +762,8 @@ TTS: # 参照教程:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/fish-speech-integration.md type: fishspeech output_dir: tmp/ - response_format: wav + response_format: pcm reference_id: null - reference_audio: ["config/assets/wakeup_words.wav",] - reference_text: ["哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",] normalize: true max_new_tokens: 1024 chunk_length: 200 @@ -774,8 +775,8 @@ TTS: seed: null channels: 1 rate: 44100 - api_key: "你的api_key" - api_url: "http://127.0.0.1:8080/v1/tts" + sample_rate: 16000 + api_key: "your fish speech api key" GPT_SOVITS_V2: # 定义TTS API类型 #启动tts方法: @@ -1057,3 +1058,14 @@ TTS: # volume: 50 # 音量:0-100 # speed: 50 # 语速:0-100 # pitch: 50 # 语调:0-100 +# =============================================================================== +# ============================= Module Selection ================================ +# =============================================================================== +selected_module: + VAD: SileroVAD + ASR: GroqASR + LLM: GroqLLM + VLLM: ChatGLMVLLM + TTS: FishSpeech + Memory: memu + Intent: function_call \ No newline at end of file diff --git a/main/xiaozhi-server/docker-compose_local_all.yml b/main/xiaozhi-server/docker-compose_local_all.yml index a89e99119..f69b575b2 100644 --- a/main/xiaozhi-server/docker-compose_local_all.yml +++ b/main/xiaozhi-server/docker-compose_local_all.yml @@ -164,6 +164,71 @@ services: retries: 3 start_period: 10s + # ============================================================================ + # live-agent-api Services + # ============================================================================ + + live-agent-postgres: + image: postgres:16-alpine + container_name: live-agent-postgres + environment: + POSTGRES_DB: live_agent + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + ports: + - "5432:5432" + volumes: + - ../live-agent-api/data/postgres:/var/lib/postgresql/data + - ../live-agent-api/init_db.sql:/docker-entrypoint-initdb.d/init_db.sql + networks: + - xiaozhi-network + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres"] + interval: 5s + timeout: 5s + retries: 5 + + live-agent-minio: + image: minio/minio:latest + container_name: live-agent-minio + command: server /data --console-address ":9001" + environment: + MINIO_ROOT_USER: minioadmin + MINIO_ROOT_PASSWORD: minioadmin + ports: + - "19000:9000" + - "19001:9001" + volumes: + - ../live-agent-api/data/minio:/data + networks: + - xiaozhi-network + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"] + interval: 10s + timeout: 5s + retries: 5 + + live-agent-api: + build: + context: ../live-agent-api + dockerfile: Dockerfile + container_name: live-agent-api + env_file: + - ../live-agent-api/.env + environment: + DATABASE_URL: postgresql+asyncpg://postgres:postgres@live-agent-postgres:5432/live_agent + S3_ENDPOINT_URL: http://live-agent-minio:9000 + DEBUG: "True" + ports: + - "8080:8080" + networks: + - xiaozhi-network + depends_on: + live-agent-postgres: + condition: service_healthy + live-agent-minio: + condition: service_healthy + # ============================================================================ # Networks # ============================================================================ diff --git a/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py b/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py index affa8af2f..b92968ae6 100644 --- a/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py +++ b/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py @@ -29,7 +29,10 @@ handle_exit_intent_function_desc = { def handle_exit_intent(conn, say_goodbye: str | None = None): # 处理退出意图 try: - if say_goodbye is None: + if hasattr(conn, '_voice_closing') and conn._voice_closing: + say_goodbye = conn._voice_closing + else: + # 如果没有自定义结束语,使用默认的 say_goodbye = "再见,祝您生活愉快!" conn.close_after_chat = True logger.bind(tag=TAG).info(f"退出意图已处理:{say_goodbye}") diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt index 18223c1ce..96f3e2678 100644 --- a/main/xiaozhi-server/requirements.txt +++ b/main/xiaozhi-server/requirements.txt @@ -43,4 +43,6 @@ redis>=4.0.0,<5.0.0 elevenlabs>=1.11.0 cartesia>=1.0.0 deepgram-sdk>=3.0.0 -fish-audio-sdk==2025.6.3 \ No newline at end of file +fish-audio-sdk==2025.6.3 + +python-dotenv>=1.0.0 \ No newline at end of file diff --git a/main/xiaozhi-server/test/js/xiaoZhiConnect.js b/main/xiaozhi-server/test/js/xiaoZhiConnect.js index d8fbe7a3b..19b7e7eda 100644 --- a/main/xiaozhi-server/test/js/xiaoZhiConnect.js +++ b/main/xiaozhi-server/test/js/xiaoZhiConnect.js @@ -37,7 +37,7 @@ export async function webSocketConnect(otaUrl, config) { // 添加认证参数(保持原有逻辑) connUrl.searchParams.append('device-id', config.deviceId); connUrl.searchParams.append('client-id', config.clientId); - + connUrl.searchParams.append('agent-id', config.agentId); const wsurl = connUrl.toString() log(`正在连接: ${wsurl}`, 'info'); @@ -82,7 +82,8 @@ async function sendOTA(otaUrl, config) { headers: { 'Content-Type': 'application/json', 'Device-Id': config.deviceId, - 'Client-Id': config.clientId + 'Client-Id': config.clientId, + 'Agent-Id': config.agentId }, body: JSON.stringify({ version: 0, diff --git a/main/xiaozhi-server/test/test_page.html b/main/xiaozhi-server/test/test_page.html index f3183ef2c..6eaf24c08 100644 --- a/main/xiaozhi-server/test/test_page.html +++ b/main/xiaozhi-server/test/test_page.html @@ -275,6 +275,10 @@ +