From f39547f0823bb05e6b17c4656cb2db085d6fc841 Mon Sep 17 00:00:00 2001 From: Harold Date: Wed, 10 Dec 2025 22:18:52 +0800 Subject: [PATCH 1/7] feat: clear agent's all messages and files --- main/live-agent-api/api/v1/chat.py | 51 ++++++++++++- main/live-agent-api/repositories/chat.py | 23 +++++- main/live-agent-api/repositories/file.py | 72 +++++++++++++++++++ main/live-agent-api/schemas/chat.py | 7 ++ main/live-agent-api/services/agent_service.py | 38 +++++++++- main/live-agent-api/services/chat_service.py | 53 +++++++++++++- main/live-agent-api/utils/exceptions.py | 6 ++ 7 files changed, 243 insertions(+), 7 deletions(-) diff --git a/main/live-agent-api/api/v1/chat.py b/main/live-agent-api/api/v1/chat.py index 93e30d14e..3a6db8c2a 100644 --- a/main/live-agent-api/api/v1/chat.py +++ b/main/live-agent-api/api/v1/chat.py @@ -7,11 +7,15 @@ from typing import Optional from infra import get_db, get_s3 from services.chat_service import chat_service +from services.agent_service import agent_service from schemas.chat import ( ReportChatMessageRequest, - ChatMessagesListResponse + ChatMessagesListResponse, ) -from utils.response import success_response +from api.auth import get_current_user_id +from utils.response import success_response, error_response +from utils.exceptions import ForbiddenException, NotFoundException, InternalServerException + router = APIRouter() @@ -104,3 +108,46 @@ async def get_agent_messages( has_more=has_more )) + +@router.delete("/{agent_id}", summary="Delete all chat data for an agent") +async def clear_agent_chat( + agent_id: str, + db: AsyncSession = Depends(get_db), + s3 = Depends(get_s3), + user_id: str = Depends(get_current_user_id) +): + """ + Clear all chat data for an agent + + Deletes: + - All chat messages in database + - All audio files in S3 (chat-audio/{agent_id}/) + - All chat files in S3 (chat-files/{agent_id}/) + + Requirements: + - User must be authenticated + - User must own the agent + + Returns: + ClearChatResponse with deletion counts + """ + # Verify agent exists and user owns it + try: + await agent_service.verify_ownership(db=db, agent_id=agent_id, owner_id=user_id) + except ForbiddenException as e: + return error_response(code=403, message=e.message) + except NotFoundException as e: + return error_response(code=404, message=e.message) + + # Clear chat data + try: + result = await chat_service.clear_agent_chat( + db=db, + s3=s3, + agent_id=agent_id + ) + except InternalServerException as e: + return error_response(code=500, message=e.message) + + return success_response(data=result) + diff --git a/main/live-agent-api/repositories/chat.py b/main/live-agent-api/repositories/chat.py index d4714a6a6..1e0c41c01 100644 --- a/main/live-agent-api/repositories/chat.py +++ b/main/live-agent-api/repositories/chat.py @@ -3,7 +3,7 @@ Chat messages repository - Database operations for chat messages """ from datetime import datetime, timezone from typing import List, Optional, Tuple -from sqlalchemy import String, SmallInteger, TIMESTAMP, ForeignKey, Index, select, insert +from sqlalchemy import String, SmallInteger, TIMESTAMP, ForeignKey, Index, select, delete from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.dialects.postgresql import JSONB @@ -185,3 +185,24 @@ class ChatMessage: result = await db.execute(query) return result.scalar_one_or_none() + @staticmethod + async def delete_by_agent( + db: AsyncSession, + agent_id: str + ) -> int: + """ + Delete all messages for a specific agent + + Args: + db: Database session + agent_id: Agent ID + + Returns: + Number of deleted messages + """ + result = await db.execute( + delete(ChatMessageModel).where(ChatMessageModel.agent_id == agent_id) + ) + await db.commit() + return result.rowcount + diff --git a/main/live-agent-api/repositories/file.py b/main/live-agent-api/repositories/file.py index ff6312ee3..540af600e 100644 --- a/main/live-agent-api/repositories/file.py +++ b/main/live-agent-api/repositories/file.py @@ -7,6 +7,10 @@ from fastapi import UploadFile from config import settings from utils.ulid import ULID +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging() class FileRepository: @@ -184,3 +188,71 @@ class FileRepository: url = f"{settings.S3_PUBLIC_BASE_URL}/{settings.S3_BUCKET_NAME}/{s3_key}" return url + @staticmethod + async def delete_folder(s3, folder_prefix: str) -> int: + """ + Delete all files under a folder prefix in S3 + + Args: + s3: S3 client + folder_prefix: S3 folder prefix (e.g., "chat-audio/agent_123/") + + Returns: + Number of deleted objects + """ + deleted_count = 0 + try: + # List all objects with the prefix + paginator = s3.get_paginator('list_objects_v2') + async for page in paginator.paginate( + Bucket=settings.S3_BUCKET_NAME, + Prefix=folder_prefix + ): + if 'Contents' not in page: + continue + + # Delete objects in batch + objects_to_delete = [{'Key': obj['Key']} for obj in page['Contents']] + if objects_to_delete: + chunk_size = 1000 + for i in range(0, len(objects_to_delete), chunk_size): + batch = objects_to_delete[i:i + chunk_size] + + response = await s3.delete_objects( + Bucket=settings.S3_BUCKET_NAME, + Delete={'Objects': batch, 'Quiet': True} + ) + + if 'Errors' in response: + for err in response['Errors']: + logger.bind(tag=TAG).error(f"Failed to delete {err.get('Key')}: {err.get('Message')}") + + deleted_count += len(response.get('Deleted', [])) + except Exception as e: + logger.bind(tag=TAG).error(f"Error deleting folder {folder_prefix}: {e}") + pass + + return deleted_count + + @staticmethod + async def delete_agent_chat_files(s3, agent_id: str) -> int: + """ + Delete all chat-related files for an agent (audio and files) + + Args: + s3: S3 client + agent_id: Agent ID + + Returns: + Total number of deleted files + """ + total_deleted = 0 + + # Delete chat audio files + total_deleted += await FileRepository.delete_folder(s3, f"chat-audio/{agent_id}/") + + # Delete chat files (if any other files stored under agent) + total_deleted += await FileRepository.delete_folder(s3, f"chat-files/{agent_id}/") + + return total_deleted + diff --git a/main/live-agent-api/schemas/chat.py b/main/live-agent-api/schemas/chat.py index 8d64702f2..d3644d0c8 100644 --- a/main/live-agent-api/schemas/chat.py +++ b/main/live-agent-api/schemas/chat.py @@ -44,3 +44,10 @@ class ChatMessagesListResponse(BaseModel): next_cursor: Optional[str] = Field(None, description="ISO timestamp to load older messages (pass as cursor for next request)") has_more: bool = Field(False, description="Whether there are more older messages available") + +class ClearChatResponse(BaseModel): + """Response schema for clearing agent chat data""" + agent_id: str = Field(..., description="Agent ID whose chat was cleared") + deleted_messages: int = Field(..., description="Number of deleted messages") + deleted_files: int = Field(..., description="Number of deleted files from storage") + diff --git a/main/live-agent-api/services/agent_service.py b/main/live-agent-api/services/agent_service.py index 48515519d..65298db3d 100644 --- a/main/live-agent-api/services/agent_service.py +++ b/main/live-agent-api/services/agent_service.py @@ -3,7 +3,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from fastapi import UploadFile from repositories import AgentModel, Agent, AgentTemplate, FileRepository -from utils.exceptions import NotFoundException, BadRequestException +from utils.exceptions import NotFoundException, ForbiddenException from utils.ulid import generate_agent_id from schemas.agent import ( AgentResponse, @@ -13,6 +13,8 @@ from schemas.agent import ( AgentWithLatestMessage ) from utils.ulid import generate_template_id + + class AgentService: """Agent service layer""" @@ -117,6 +119,36 @@ class AgentService: raise NotFoundException("Agent not found") return agent + + async def verify_ownership( + self, + db: AsyncSession, + agent_id: str, + owner_id: str + ) -> AgentModel: + """ + Verify agent exists and belongs to user + + Args: + db: Database session + agent_id: Agent ID + owner_id: Expected owner user ID + + Returns: + AgentModel if verification passes + + Raises: + NotFoundException: If agent not found + ForbiddenException: If user doesn't own the agent + """ + agent = await Agent.get_by_id(db, agent_id) + if not agent: + raise NotFoundException("Agent not found") + + if agent.owner_id != owner_id: + raise ForbiddenException("You don't have permission to access this agent") + + return agent async def get_bindable_agents( self, @@ -198,7 +230,7 @@ class AgentService: # Check ownership if agent.owner_id != owner_id: - raise BadRequestException("You don't have permission to update this agent") + raise ForbiddenException("You don't have permission to update this agent") # Prepare update data update_data = {} @@ -246,7 +278,7 @@ class AgentService: # Check ownership if agent.owner_id != owner_id: - raise BadRequestException("You don't have permission to delete this agent") + raise ForbiddenException("You don't have permission to delete this agent") # Delete avatar from S3 if exists if agent.avatar_url: diff --git a/main/live-agent-api/services/chat_service.py b/main/live-agent-api/services/chat_service.py index 4af474135..f81a5af40 100644 --- a/main/live-agent-api/services/chat_service.py +++ b/main/live-agent-api/services/chat_service.py @@ -7,10 +7,15 @@ from typing import List, Optional, Tuple from sqlalchemy.ext.asyncio import AsyncSession from copy import deepcopy +from config.logger import setup_logging from repositories.chat import ChatMessage as ChatMessageRepo from repositories.file import FileRepository -from schemas.chat import ReportChatMessageRequest, ChatMessage as ChatMessageSchema +from schemas.chat import ReportChatMessageRequest, ChatMessage as ChatMessageSchema, ClearChatResponse from utils.ulid import ULID +from utils.exceptions import InternalServerException + +TAG = __name__ +logger = setup_logging(__name__) class ChatService: @@ -137,6 +142,52 @@ class ChatService: return response_messages, next_cursor, has_more + async def clear_agent_chat( + self, + db: AsyncSession, + s3, + agent_id: str + ) -> ClearChatResponse: + """ + Clear all chat data for an agent (messages and files) + + Note: Caller must verify agent ownership before calling this method + + Process: + 1. Delete all chat messages from database + 2. Delete all chat files from S3 + + Args: + db: Database session + s3: S3 client + agent_id: Agent ID + + Returns: + ClearChatResponse with deletion counts + + Raises: + InternalServerException: If database or S3 deletion fails + """ + # Delete all messages from database + try: + deleted_messages = await ChatMessageRepo.delete_by_agent(db, agent_id) + except Exception as e: + logger.bind(tag=TAG).exception(f"Failed to delete chat messages for agent {agent_id}") + raise InternalServerException(f"Failed to delete chat messages: {e}") + + # Delete all chat files from S3 + try: + deleted_files = await FileRepository.delete_agent_chat_files(s3, agent_id) + except Exception as e: + logger.bind(tag=TAG).exception(f"Failed to delete chat files for agent {agent_id}") + raise InternalServerException(f"Failed to delete chat files: {e}") + + return ClearChatResponse( + agent_id=agent_id, + deleted_messages=deleted_messages, + deleted_files=deleted_files + ) + # Global singleton instance chat_service = ChatService() diff --git a/main/live-agent-api/utils/exceptions.py b/main/live-agent-api/utils/exceptions.py index 859f78494..70a3a56c4 100644 --- a/main/live-agent-api/utils/exceptions.py +++ b/main/live-agent-api/utils/exceptions.py @@ -35,3 +35,9 @@ class ConflictException(APIException): def __init__(self, message: str = "Resource already exists"): super().__init__(409, message) + +class InternalServerException(APIException): + """Internal server exception (500)""" + def __init__(self, message: str = "Internal server error"): + super().__init__(500, message) + From e69edfafd2c595b1e3747ddc9b1bb0bd077c0803 Mon Sep 17 00:00:00 2001 From: Harold Date: Wed, 10 Dec 2025 23:43:41 +0800 Subject: [PATCH 2/7] feat: clone voice with new sample url --- main/live-agent-api/api/v1/voices.py | 30 ++-- main/live-agent-api/repositories/file.py | 23 +++ main/live-agent-api/services/voice_service.py | 137 ++++++++++++------ 3 files changed, 134 insertions(+), 56 deletions(-) diff --git a/main/live-agent-api/api/v1/voices.py b/main/live-agent-api/api/v1/voices.py index 4fdcd9076..0aa049fec 100644 --- a/main/live-agent-api/api/v1/voices.py +++ b/main/live-agent-api/api/v1/voices.py @@ -16,11 +16,13 @@ from schemas.voice import ( VoiceUpdateRequest, VoiceAddRequest ) -from utils.response import success_response +from utils.response import success_response, error_response from api.auth import get_current_user_id -from config import get_logger +from config.logger import setup_logging +from utils.exceptions import InternalServerException -logger = get_logger(__name__) +TAG = __name__ +logger = setup_logging(TAG) router = APIRouter() @router.get("/discover", summary="Get Discover Voices") @@ -157,15 +159,19 @@ async def 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 - ) - + try: + 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 + ) + + except Exception as e: + return error_response(code=500, message=f"Voice cloning failed: {e}") + return success_response( data={ diff --git a/main/live-agent-api/repositories/file.py b/main/live-agent-api/repositories/file.py index 540af600e..60a096f3b 100644 --- a/main/live-agent-api/repositories/file.py +++ b/main/live-agent-api/repositories/file.py @@ -256,3 +256,26 @@ class FileRepository: return total_deleted + @staticmethod + async def upload_voice_sample( + s3, + audio_data: bytes, + voice_id: str, + file_ext: str = "mp3" + ) -> str: + """ + Upload TTS-generated voice sample to S3 + ... + """ + filename = f"{voice_id}.{file_ext}" + s3_key = f"voice_samples/{filename}" + + await s3.put_object( + Bucket=settings.S3_BUCKET_NAME, + Key=s3_key, + Body=audio_data, + ContentType=f"audio/{file_ext}", + ) + + url = f"{settings.S3_PUBLIC_BASE_URL}/{settings.S3_BUCKET_NAME}/{s3_key}" + return url diff --git a/main/live-agent-api/services/voice_service.py b/main/live-agent-api/services/voice_service.py index 3a9c02073..10591ab8b 100644 --- a/main/live-agent-api/services/voice_service.py +++ b/main/live-agent-api/services/voice_service.py @@ -1,7 +1,7 @@ from typing import Optional, List, Tuple from sqlalchemy.ext.asyncio import AsyncSession from fastapi import UploadFile -from fishaudio import AsyncFishAudio +from fishaudio import AsyncFishAudio, save from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as FishSample from repositories import VoiceModel, Voice @@ -9,6 +9,13 @@ from utils.ulid import generate_voice_id from repositories import FileRepository from datetime import datetime, timezone +from config.logger import setup_logging + +TAG = __name__ +logger = setup_logging(TAG) + +# Default sample text for TTS preview when user doesn't provide text +DEFAULT_SAMPLE_TEXT = "The only way to do great work is to love what you do." class VoiceService: """Voice service layer""" @@ -101,7 +108,13 @@ class VoiceService: text: Optional[str] = None ) -> VoiceModel: """ - Clone a voice using Fish Audio API, store audio, and save to database + Clone a voice using Fish Audio API, generate TTS preview, and save to database + + Flow: + 1. Clone voice from uploaded audio + optional text + 2. Generate TTS preview audio using the new voice (with provided or default text) + 3. Upload TTS preview to S3 as sample_url + 4. Create voice record in database Args: db: Database session @@ -109,54 +122,90 @@ class VoiceService: fish_client: Fish Audio client owner_id: User ID audio_file: Audio file to clone - text: Optional transcription text + text: Optional transcription text (also used for TTS preview) Returns: Created VoiceModel + + Raises: + InternalServerException: When any downstream service fails """ - # Generate voice_id for our system - voice_id = generate_voice_id() + from utils.exceptions import InternalServerException - # Read audio file content - audio_content = await audio_file.read() + fish_voice_id: Optional[str] = None + sample_url: Optional[str] = None + sample_text = text if text else DEFAULT_SAMPLE_TEXT - # 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}", - voices=[audio_content], - texts=[text] if text else None, - train_mode="fast", - visibility="private", - enhance_audio_quality=True - ) - - # 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 + try: + # Read audio file content for cloning + audio_content = await audio_file.read() + + # Step 1: Clone voice using Fish Audio API + fish_voice: FishVoice = await fish_client.voices.create( + title=f"live_agent_{owner_id}_{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S')}", + voices=[audio_content], + texts=[text] if text else None, + train_mode="fast", + visibility="private", + enhance_audio_quality=True + ) + fish_voice_id = fish_voice.id + + # Step 2: Generate TTS preview using the new voice + logger.bind(tag=TAG).info(f"Generating TTS preview with voice {fish_voice_id}") + audio_bytes = await fish_client.tts.convert( + text=sample_text, + reference_id=fish_voice_id, + format="mp3" + ) + logger.bind(tag=TAG).info(f"TTS preview generated, size: {len(audio_bytes)} bytes") + + # Step 3: Upload TTS preview audio to S3 + sample_url = await FileRepository.upload_voice_sample( + s3=s3, + audio_data=audio_bytes, + voice_id=fish_voice_id, + file_ext="mp3" + ) + logger.bind(tag=TAG).info(f"TTS preview uploaded to S3: {sample_url}") + + # Step 4: Create voice record in database + voice = await Voice.create( + db=db, + voice_id=fish_voice_id, + owner_id=owner_id, + name="Cloned Voice", + desc="", + sample_url=sample_url, + sample_text=sample_text + ) + + return voice + + except Exception as e: + logger.bind(tag=TAG).error(f"Clone voice failed: {e}") + # Cleanup created resources based on what was successfully created + if sample_url: + await self._cleanup_s3_file(s3, sample_url) + if fish_voice_id: + await self._cleanup_fish_voice(fish_client, fish_voice_id) + raise InternalServerException(f"Voice cloning failed: {str(e)}") + + async def _cleanup_fish_voice(self, fish_client: AsyncFishAudio, voice_id: str) -> None: + """Cleanup helper: delete voice from Fish Audio""" + try: + await fish_client.voices.delete(voice_id) + logger.bind(tag=TAG).info(f"Cleanup: deleted Fish Audio voice {voice_id}") + except Exception as e: + logger.bind(tag=TAG).warning(f"Cleanup failed: could not delete Fish Audio voice {voice_id}: {e}") + + async def _cleanup_s3_file(self, s3, url: str) -> None: + """Cleanup helper: delete file from S3""" + try: + await FileRepository.delete(s3, url) + logger.bind(tag=TAG).info(f"Cleanup: deleted S3 file {url}") + except Exception as e: + logger.bind(tag=TAG).warning(f"Cleanup failed: could not delete S3 file {url}: {e}") async def add_voice( self, From 6db8e70cf47dc6d5e2451c8e66b8cd31f895bfad Mon Sep 17 00:00:00 2001 From: Harold Date: Thu, 11 Dec 2025 00:00:40 +0800 Subject: [PATCH 3/7] feat: remove voice --- main/live-agent-api/api/v1/voices.py | 31 +++++++++++---- main/live-agent-api/repositories/agent.py | 20 ++++++++++ main/live-agent-api/services/agent_service.py | 13 +++++++ main/live-agent-api/services/voice_service.py | 39 +++++++++++++++---- 4 files changed, 87 insertions(+), 16 deletions(-) diff --git a/main/live-agent-api/api/v1/voices.py b/main/live-agent-api/api/v1/voices.py index 0aa049fec..75413fa49 100644 --- a/main/live-agent-api/api/v1/voices.py +++ b/main/live-agent-api/api/v1/voices.py @@ -8,6 +8,8 @@ from infra.fishaudio import get_fish_audio from infra.openai import get_openai from services.voice_service import voice_service from services.llm_service import llm_service +from services.agent_service import agent_service +from utils.exceptions import ConflictException from schemas.voice import ( LiveAgentVoice, DiscoverVoiceResponse, @@ -259,19 +261,32 @@ async def update_voice( async def remove_voice( voice_id: str, current_user_id: str = Depends(get_current_user_id), - db: AsyncSession = Depends(get_db) + db: AsyncSession = Depends(get_db), + s3 = Depends(get_s3), + fish_client = Depends(get_fish_audio) ): """ - Remove a voice from user's my voices - - Only deletes the database record (reference) + Remove a voice completely from user's my voices + - Checks if voice is bound to any agent (returns 409 Conflict if bound) + - Deletes from database, S3, and Fish Audio - User must own the voice """ - await voice_service.remove_voice( - db=db, - voice_id=voice_id, - owner_id=current_user_id - ) + # Check if voice is bound to any agent + is_bound = await agent_service.is_voice_bound(db=db, voice_id=voice_id) + if is_bound: + raise ConflictException("Cannot remove voice: it is currently bound to one or more agents") + try: + await voice_service.remove_voice( + db=db, + s3=s3, + fish_client=fish_client, + voice_id=voice_id, + owner_id=current_user_id + ) + except Exception as e: + return error_response(code=500, message=f"Voice removal failed: {e}") + return success_response( data={"voice_id": voice_id}, message="Voice removed successfully" diff --git a/main/live-agent-api/repositories/agent.py b/main/live-agent-api/repositories/agent.py index c4a4d5a91..f13abeb58 100644 --- a/main/live-agent-api/repositories/agent.py +++ b/main/live-agent-api/repositories/agent.py @@ -211,6 +211,26 @@ class Agent: .order_by(AgentModel.created_at.desc()) ) return list(result.scalars().all()) + + @staticmethod + async def is_voice_bound(db: AsyncSession, voice_id: str) -> bool: + """ + Check if a voice is bound to any agent + + Args: + db: Database session + voice_id: Voice ID to check + + Returns: + True if voice is bound to at least one agent + """ + result = await db.execute( + select(func.count()) + .select_from(AgentModel) + .where(AgentModel.voice_id == voice_id) + ) + count = result.scalar_one() + return count > 0 @staticmethod async def get_agents_with_latest_message( diff --git a/main/live-agent-api/services/agent_service.py b/main/live-agent-api/services/agent_service.py index 65298db3d..c6567a581 100644 --- a/main/live-agent-api/services/agent_service.py +++ b/main/live-agent-api/services/agent_service.py @@ -166,6 +166,19 @@ class AgentService: List of agents with wake_word configured """ return await Agent.get_bindable_agents(db, owner_id) + + async def is_voice_bound(self, db: AsyncSession, voice_id: str) -> bool: + """ + Check if a voice is bound to any agent + + Args: + db: Database session + voice_id: Voice ID to check + + Returns: + True if voice is bound to at least one agent + """ + return await Agent.is_voice_bound(db, voice_id) async def create_agent( self, diff --git a/main/live-agent-api/services/voice_service.py b/main/live-agent-api/services/voice_service.py index 10591ab8b..478a7ca0e 100644 --- a/main/live-agent-api/services/voice_service.py +++ b/main/live-agent-api/services/voice_service.py @@ -1,15 +1,16 @@ from typing import Optional, List, Tuple from sqlalchemy.ext.asyncio import AsyncSession from fastapi import UploadFile -from fishaudio import AsyncFishAudio, save +from fishaudio import AsyncFishAudio from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as FishSample from repositories import VoiceModel, Voice -from utils.ulid import generate_voice_id from repositories import FileRepository from datetime import datetime, timezone from config.logger import setup_logging +from utils.exceptions import NotFoundException + TAG = __name__ logger = setup_logging(TAG) @@ -256,26 +257,48 @@ class VoiceService: async def remove_voice( self, db: AsyncSession, + s3, + fish_client: AsyncFishAudio, voice_id: str, owner_id: str ) -> bool: """ - Remove a voice from user's my voices + Remove a voice completely: database, S3, and Fish Audio Args: db: Database session - voice_id: Internal voice ID + s3: S3 client + fish_client: Fish Audio client + voice_id: Voice ID owner_id: User ID Returns: - True if deleted, False if not found + True if deleted successfully + + Raises: + NotFoundException: If voice not found or not owned by user """ - deleted = await Voice.delete(db=db, voice_id=voice_id, owner_id=owner_id) - if not deleted: - from utils.exceptions import NotFoundException + # Get voice record first to get sample_url for S3 cleanup + voice = await Voice.get_by_voice_and_owner(db=db, voice_id=voice_id, owner_id=owner_id) + if not voice: raise NotFoundException(f"Voice {voice_id} not found or not owned by user") + sample_url = voice.sample_url + + # Delete from database first + deleted = await Voice.delete(db=db, voice_id=voice_id, owner_id=owner_id) + if not deleted: + raise NotFoundException(f"Voice {voice_id} not found or not owned by user") + + # Cleanup S3 file (best effort, don't fail if cleanup fails) + try: + if sample_url: + await self._cleanup_s3_file(s3, sample_url) + await self._cleanup_fish_voice(fish_client, voice_id) + except Exception as e: + logger.bind(tag=TAG).warning(f"Cleanup failed: {e}") + return False return True async def update_voice( From a16ce035149156e827f76d1134d7b5736b95696a Mon Sep 17 00:00:00 2001 From: Harold Date: Thu, 11 Dec 2025 01:34:29 +0800 Subject: [PATCH 4/7] feat: optimize character role --- main/live-agent-api/api/v1/agents.py | 11 +- main/live-agent-api/services/llm_service.py | 134 +++++++++++++------- 2 files changed, 93 insertions(+), 52 deletions(-) diff --git a/main/live-agent-api/api/v1/agents.py b/main/live-agent-api/api/v1/agents.py index b8a524748..f90a87412 100644 --- a/main/live-agent-api/api/v1/agents.py +++ b/main/live-agent-api/api/v1/agents.py @@ -1,3 +1,4 @@ +import json from typing import Optional from fastapi import APIRouter, Depends, Query, Form, File, UploadFile from fastapi.responses import StreamingResponse @@ -208,11 +209,15 @@ async def generate_persona( avatar_base64=avatar_base64, avatar_media_type=avatar_media_type ): - # SSE format: data: \n\n - yield f"data: {chunk}\n\n" + # Wrap chunk in JSON to preserve newlines (they get escaped as \n) + event = {"type": "content", "data": chunk} + yield f"data: {json.dumps(event)}\n\n" + # Send done event + yield f"data: {json.dumps({'type': 'done'})}\n\n" except Exception as e: logger.error(f"Persona optimization failed: {e}") - yield f"data: [ERROR] {str(e)}\n\n" + error_event = {"type": "error", "message": str(e)} + yield f"data: {json.dumps(error_event)}\n\n" return StreamingResponse( stream_generator(), diff --git a/main/live-agent-api/services/llm_service.py b/main/live-agent-api/services/llm_service.py index 45afd0bb7..068073f7b 100644 --- a/main/live-agent-api/services/llm_service.py +++ b/main/live-agent-api/services/llm_service.py @@ -24,47 +24,86 @@ Requirements: Output ONLY the text sample, no explanations or metadata.""" - # Quick mode: concise persona for initial creation - PERSONA_QUICK_SYSTEM_PROMPT = """You are a creative character designer. Create a concise persona based on the name and optional image. + # --------------------------------------------------------------------------- + # 1. Quick Mode Prompt (Cold Start) + # Goal: Generate a structured profile + opening/closing from scratch. + # Key Update: Enforce "Relationships" and "Lore" retrieval for IPs. + # --------------------------------------------------------------------------- + PERSONA_QUICK_SYSTEM_PROMPT = """You are an expert Character Designer and Creative Director. +Your goal is to create a vivid, highly engaging, and logically consistent character profile based on the user's input (Name, Image, or Description). -**instruction**: MUST start with "You are [name]..." - a brief role-play instruction (1-2 sentences, 25-40 words) -- Describe their personality, vibe, and how they communicate -- Write in second person as if instructing an AI to role-play this character +**CRITICAL KNOWLEDGE RETRIEVAL:** +- If the character is from a known IP (e.g., Pop Mart, Anime, Movies, Games), you MUST retrieve accurate canonical facts. +- Specifically, you must identify their **official relationships** (friends, rivals, leaders) and **backstory**. +- Example: If the user says "Labubu", you must mention "Zimomo" (Leader) and "Tycoco" (Victim/Friend). -**voice_opening**: A characteristic greeting when starting a conversation (5-15 words) -- How would this character say hello? +**OUTPUT FORMAT (JSON ONLY):** -**voice_closing**: A characteristic FAREWELL/GOODBYE when ending a conversation (5-15 words) -- How would this character say goodbye? (NOT a catchphrase, but an actual farewell) +Return a valid JSON object with the following fields: +**CRITICAL FORMATTING RULE (JSON String):** +- Inside the "instruction" field, you MUST use **double newlines** (`\\n\\n`) before every Markdown Header (`##`). +- Failure to do this will break the UI rendering. +- Example string content: "...end of sentence.\\n\\n## Next Section..." -Example output: -{ - "instruction": "...", - "voice_opening": "...", - "voice_closing": "..." -} +1. "instruction": A structured text block. Use EXACTLY this format: + ### Identity + [Who they are] -Output valid JSON only. Be creative and authentic.""" + ### Personality & Speech + [Tone, speed, verbal tics like 'Haha', 'Umm'] - # Optimize mode: detailed persona for iterative refinement - PERSONA_OPTIMIZE_SYSTEM_PROMPT = """You are a creative character designer who enriches AI agent personas. + ### Backstory & Worldview + [Origins and goals] -Your task: Take the existing instruction and enhance it into a rich, narrative persona. + ### Key Relationships + - [Name] ([Role]): [Dynamic] -DO NOT write like a typical AI prompt. Write like you're describing a REAL PERSON with soul and character. +2. "voice_opening": A catchy, in-character first sentence to start a voice call (max 15 words). + - Note: Can use an emotion tag like (happy) or (curious) at the start. -Expand on these dimensions: -- Who is this person? What's their vibe, their energy? -- How do they talk? Street-smart? Elegant? Nerdy? Chill? -- What's their worldview? What do they care about? -- How do they connect with people? Warm, sarcastic, mysterious? -- Give them a unique angle or perspective on life +3. "voice_closing": A characteristic natural farewell to end a call (max 15 words). + - Note: NOT a catchphrase, but a conversation ender. -Example style (Dave - The Witty Commentator, a Black stand-up comedian): -"You are Dave, a stand-up comedian with a relaxed, soulful vibe and a sharp eye for the absurdities of life. You view the world through a lens of 'real talk' and observational humor, acting as the user's witty friend who loves to chat about pop culture, daily grinds, or random thoughts. Your style is street-smart and medium-sharp—playful enough to roast a situation, but always good-natured and safe, keeping the conversation flowing like a late-night backstage hang." +**Example "instruction" value:** +"### Identity\n Labubu, the mischievous elf.\n\n### Personality & Speech\n Hyperactive, laughs often.\n\n### Key Relationships\n- Zimomo (Leader): Respects but pranks him." +""" -Output ONLY the enhanced instruction text (100-200 words). No JSON, no explanations, no metadata.""" + # --------------------------------------------------------------------------- + # 2. Optimize Mode Prompt (Refinement) + # Goal: Deepen the profile, fix hallucinations, and format for v5.0. + # Key Update: Chain of Thought to fix missing knowledge. + # --------------------------------------------------------------------------- + PERSONA_OPTIMIZE_SYSTEM_PROMPT = """You are a Senior Narrative Designer optimizing an AI Voice Agent. +Your Task: Analyze the input profile and rewrite it into a "Character Bible" format. + +**OPTIMIZATION OBJECTIVES:** +1. **Fact Check (IP Check):** If this is a famous character, verify the lore. Does the draft miss key friends/enemies? (e.g., If Labubu, ensure Zimomo is mentioned). +2. **Deepen Tone:** Add specific "Speech Quirks" suitable for Voice TTS (e.g., pauses, specific interjections, sentence length). +3. **Format:** Use standard Markdown headers (##) so it looks like a document, not code. + +**OUTPUT FORMAT:** +Return ONLY the raw text profile (no JSON, no conversational filler). Use this Markdown format: + +**CRITICAL FORMATTING RULE:** +- You MUST insert **two newlines** (`\\n\\n`) before every Header (e.g., `## Identity`). +- Ensure there is a visible blank line between the end of a paragraph and the next Title. +- Do NOT run text directly into a header (e.g., "text## Header" is FORBIDDEN). + +Example: +### Identity +[Who they are, core drive] + +### Personality & Speech +[Tone, speed, catchphrases, verbal habits] + +### Backstory & Worldview +[Origins, where they live, what they want] + +### Key Relationships +- [Name]: [Connection/Attitude] +- [Name]: [Connection/Attitude] +""" async def generate_voice_sample_text_stream( self, openai_client: AsyncOpenAI, @@ -147,8 +186,7 @@ Output ONLY the enhanced instruction text (100-200 words). No JSON, no explanati Returns: dict with instruction, voice_opening, voice_closing """ - user_prompt = f"Create a persona for: {name}" - + user_prompt = f"Create a deep character profile for: {name}. Retrieve canonical lore if this is a known character." messages = [ {"role": "system", "content": self.PERSONA_QUICK_SYSTEM_PROMPT} ] @@ -157,7 +195,7 @@ Output ONLY the enhanced instruction text (100-200 words). No JSON, no explanati messages.append({ "role": "user", "content": [ - {"type": "text", "text": user_prompt + "\n\nUse the image to inform the persona's character and style."}, + {"type": "text", "text": user_prompt + "\n\nAnalyze the image to determine their species, mood, and visual traits for the profile."}, {"type": "image_url", "image_url": {"url": f"data:{avatar_media_type};base64,{avatar_base64}"}} ] }) @@ -167,8 +205,9 @@ Output ONLY the enhanced instruction text (100-200 words). No JSON, no explanati response = await openai_client.chat.completions.create( model=settings.QUICK_PERSONA_MODEL, messages=messages, - temperature=0.6, - max_tokens=500 + temperature=0.7, + max_tokens=800, + response_format={"type": "json_object"}, ) content = response.choices[0].message.content.strip() @@ -190,23 +229,18 @@ Output ONLY the enhanced instruction text (100-200 words). No JSON, no explanati ) -> AsyncGenerator[str, None]: """ Optimize mode: Streaming generation of detailed instruction - - Args: - openai_client: OpenAI client instance - name: Agent name (required) - instruction: Existing instruction to enhance - avatar_base64: Optional base64-encoded avatar image - avatar_media_type: Optional media type of avatar (e.g., image/jpeg) - - Yields: - Enhanced instruction text chunks """ - user_prompt = f"""Agent name: {name} + # Update: Explicitly ask to fix the input based on the Name + user_prompt = f"""Character Name: {name} -Current instruction to enhance: +Current Draft Profile: {instruction} -Create a richer, more detailed persona.""" +Task: +1. Identify if '{name}' is a known IP/Character. +2. If yes, retrieve their real backstory and friends (e.g., if Labubu, add Zimomo). +3. Rewrite the profile into the [Identity]/[Personality]/[Relationships] format. +""" messages = [ {"role": "system", "content": self.PERSONA_OPTIMIZE_SYSTEM_PROMPT} @@ -216,7 +250,7 @@ Create a richer, more detailed persona.""" messages.append({ "role": "user", "content": [ - {"type": "text", "text": user_prompt + "\n\nAlso consider the visual appearance from the image."}, + {"type": "text", "text": user_prompt + "\n\nUse the image to confirm visual details."}, {"type": "image_url", "image_url": {"url": f"data:{avatar_media_type};base64,{avatar_base64}"}} ] }) @@ -233,11 +267,13 @@ Create a richer, more detailed persona.""" async for chunk in stream: if chunk.choices and chunk.choices[0].delta.content: - logger.info(f"Optimize persona chunk time: {time.time()}") + # Optional: Log timing only on first chunk to reduce spam + # logger.info(f"Optimize persona chunk received") yield chunk.choices[0].delta.content except Exception as e: error_message = f"[ERROR] Failed to optimize persona: {str(e)}" + logger.error(error_message) yield f"\n\n{error_message}" raise From baaba07d56213d3e1513cfb0ea0cad8cb31298aa Mon Sep 17 00:00:00 2001 From: Harold Date: Thu, 11 Dec 2025 01:35:02 +0800 Subject: [PATCH 5/7] feat: fit with new generation format --- main/xiaozhi-server/core/roles/prompts/role.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/main/xiaozhi-server/core/roles/prompts/role.md b/main/xiaozhi-server/core/roles/prompts/role.md index 2dc714db7..e46ff3317 100644 --- a/main/xiaozhi-server/core/roles/prompts/role.md +++ b/main/xiaozhi-server/core/roles/prompts/role.md @@ -1,10 +1,10 @@ # Role & Persona You are the character defined below. Immerse yourself fully in this persona, adopting its tone, vocabulary, worldview, and specific speech quirks. -[User Defined Profile] +## User Defined Profile {profile} -[System Context] +## System Context {system_context} # Interaction Mode: Voice Call From c4da70b2716751ba7830a2ab7771c4c911474fa0 Mon Sep 17 00:00:00 2001 From: Harold Date: Thu, 11 Dec 2025 13:24:33 +0800 Subject: [PATCH 6/7] feat: default sample text based on language --- main/live-agent-api/services/voice_service.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/main/live-agent-api/services/voice_service.py b/main/live-agent-api/services/voice_service.py index 478a7ca0e..44382c8c2 100644 --- a/main/live-agent-api/services/voice_service.py +++ b/main/live-agent-api/services/voice_service.py @@ -16,7 +16,11 @@ TAG = __name__ logger = setup_logging(TAG) # Default sample text for TTS preview when user doesn't provide text -DEFAULT_SAMPLE_TEXT = "The only way to do great work is to love what you do." +DEFAULT_SAMPLE_TEXT = { + "en": "The only way to do great work is to love what you do.", + "zh": "只有热爱才能做出伟大的工作。", + "ja": "偉大な仕事をする唯一の方法は、あなたが何を愛するかです。" +} class VoiceService: """Voice service layer""" @@ -135,7 +139,6 @@ class VoiceService: fish_voice_id: Optional[str] = None sample_url: Optional[str] = None - sample_text = text if text else DEFAULT_SAMPLE_TEXT try: # Read audio file content for cloning @@ -151,6 +154,8 @@ class VoiceService: enhance_audio_quality=True ) fish_voice_id = fish_voice.id + language = fish_voice.languages[0] if len(fish_voice.languages) > 0 else "en" + sample_text = DEFAULT_SAMPLE_TEXT[language] # Step 2: Generate TTS preview using the new voice logger.bind(tag=TAG).info(f"Generating TTS preview with voice {fish_voice_id}") From ff836d81b45931194a3411c83beb2c7bd60cbb60 Mon Sep 17 00:00:00 2001 From: Harold Date: Thu, 11 Dec 2025 17:48:42 +0800 Subject: [PATCH 7/7] feat: default text --- main/live-agent-api/services/voice_service.py | 1 + 1 file changed, 1 insertion(+) diff --git a/main/live-agent-api/services/voice_service.py b/main/live-agent-api/services/voice_service.py index 44382c8c2..e9ea490db 100644 --- a/main/live-agent-api/services/voice_service.py +++ b/main/live-agent-api/services/voice_service.py @@ -143,6 +143,7 @@ class VoiceService: try: # Read audio file content for cloning audio_content = await audio_file.read() + logger.bind(tag=TAG).info(f"Audio content length: {len(audio_content)} bytes") # Step 1: Clone voice using Fish Audio API fish_voice: FishVoice = await fish_client.voices.create(