Merge pull request #38 from Plaud-AI/feat/demo

feat: add chat deletion API, voice sample generation, and agent profile enhancement
This commit is contained in:
Harold-Guo 2025-12-11 17:49:54 +08:00 committed by GitHub
commit 5a2182d24a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 563 additions and 131 deletions

View file

@ -1,3 +1,4 @@
import json
from typing import Optional from typing import Optional
from fastapi import APIRouter, Depends, Query, Form, File, UploadFile from fastapi import APIRouter, Depends, Query, Form, File, UploadFile
from fastapi.responses import StreamingResponse from fastapi.responses import StreamingResponse
@ -208,11 +209,15 @@ async def generate_persona(
avatar_base64=avatar_base64, avatar_base64=avatar_base64,
avatar_media_type=avatar_media_type avatar_media_type=avatar_media_type
): ):
# SSE format: data: <content>\n\n # Wrap chunk in JSON to preserve newlines (they get escaped as \n)
yield f"data: {chunk}\n\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: except Exception as e:
logger.error(f"Persona optimization failed: {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( return StreamingResponse(
stream_generator(), stream_generator(),

View file

@ -7,11 +7,15 @@ from typing import Optional
from infra import get_db, get_s3 from infra import get_db, get_s3
from services.chat_service import chat_service from services.chat_service import chat_service
from services.agent_service import agent_service
from schemas.chat import ( from schemas.chat import (
ReportChatMessageRequest, 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() router = APIRouter()
@ -104,3 +108,46 @@ async def get_agent_messages(
has_more=has_more 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)

View file

@ -8,6 +8,8 @@ from infra.fishaudio import get_fish_audio
from infra.openai import get_openai from infra.openai import get_openai
from services.voice_service import voice_service from services.voice_service import voice_service
from services.llm_service import llm_service from services.llm_service import llm_service
from services.agent_service import agent_service
from utils.exceptions import ConflictException
from schemas.voice import ( from schemas.voice import (
LiveAgentVoice, LiveAgentVoice,
DiscoverVoiceResponse, DiscoverVoiceResponse,
@ -16,11 +18,13 @@ from schemas.voice import (
VoiceUpdateRequest, VoiceUpdateRequest,
VoiceAddRequest VoiceAddRequest
) )
from utils.response import success_response from utils.response import success_response, error_response
from api.auth import get_current_user_id 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 = APIRouter()
@router.get("/discover", summary="Get Discover Voices") @router.get("/discover", summary="Get Discover Voices")
@ -157,6 +161,7 @@ async def clone_voice(
""" """
# Clone voice, upload to S3, and save to database # Clone voice, upload to S3, and save to database
try:
voice = await voice_service.clone_voice( voice = await voice_service.clone_voice(
db=db, db=db,
s3=s3, s3=s3,
@ -166,6 +171,9 @@ async def clone_voice(
text=text text=text
) )
except Exception as e:
return error_response(code=500, message=f"Voice cloning failed: {e}")
return success_response( return success_response(
data={ data={
@ -253,18 +261,31 @@ async def update_voice(
async def remove_voice( async def remove_voice(
voice_id: str, voice_id: str,
current_user_id: str = Depends(get_current_user_id), 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 Remove a voice completely from user's my voices
- Only deletes the database record (reference) - 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 - User must own the voice
""" """
# 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( await voice_service.remove_voice(
db=db, db=db,
s3=s3,
fish_client=fish_client,
voice_id=voice_id, voice_id=voice_id,
owner_id=current_user_id owner_id=current_user_id
) )
except Exception as e:
return error_response(code=500, message=f"Voice removal failed: {e}")
return success_response( return success_response(
data={"voice_id": voice_id}, data={"voice_id": voice_id},

View file

@ -212,6 +212,26 @@ class Agent:
) )
return list(result.scalars().all()) 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 @staticmethod
async def get_agents_with_latest_message( async def get_agents_with_latest_message(
db: AsyncSession, db: AsyncSession,

View file

@ -3,7 +3,7 @@ Chat messages repository - Database operations for chat messages
""" """
from datetime import datetime, timezone from datetime import datetime, timezone
from typing import List, Optional, Tuple 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.orm import Mapped, mapped_column
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.dialects.postgresql import JSONB
@ -185,3 +185,24 @@ class ChatMessage:
result = await db.execute(query) result = await db.execute(query)
return result.scalar_one_or_none() 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

View file

@ -7,6 +7,10 @@ from fastapi import UploadFile
from config import settings from config import settings
from utils.ulid import ULID from utils.ulid import ULID
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
class FileRepository: class FileRepository:
@ -184,3 +188,94 @@ class FileRepository:
url = f"{settings.S3_PUBLIC_BASE_URL}/{settings.S3_BUCKET_NAME}/{s3_key}" url = f"{settings.S3_PUBLIC_BASE_URL}/{settings.S3_BUCKET_NAME}/{s3_key}"
return url 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
@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

View file

@ -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)") 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") 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")

View file

@ -3,7 +3,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import UploadFile from fastapi import UploadFile
from repositories import AgentModel, Agent, AgentTemplate, FileRepository 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 utils.ulid import generate_agent_id
from schemas.agent import ( from schemas.agent import (
AgentResponse, AgentResponse,
@ -13,6 +13,8 @@ from schemas.agent import (
AgentWithLatestMessage AgentWithLatestMessage
) )
from utils.ulid import generate_template_id from utils.ulid import generate_template_id
class AgentService: class AgentService:
"""Agent service layer""" """Agent service layer"""
@ -118,6 +120,36 @@ class AgentService:
return agent 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( async def get_bindable_agents(
self, self,
db: AsyncSession, db: AsyncSession,
@ -135,6 +167,19 @@ class AgentService:
""" """
return await Agent.get_bindable_agents(db, owner_id) 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( async def create_agent(
self, self,
db: AsyncSession, db: AsyncSession,
@ -198,7 +243,7 @@ class AgentService:
# Check ownership # Check ownership
if agent.owner_id != owner_id: 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 # Prepare update data
update_data = {} update_data = {}
@ -246,7 +291,7 @@ class AgentService:
# Check ownership # Check ownership
if agent.owner_id != owner_id: 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 # Delete avatar from S3 if exists
if agent.avatar_url: if agent.avatar_url:

View file

@ -7,10 +7,15 @@ from typing import List, Optional, Tuple
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from copy import deepcopy from copy import deepcopy
from config.logger import setup_logging
from repositories.chat import ChatMessage as ChatMessageRepo from repositories.chat import ChatMessage as ChatMessageRepo
from repositories.file import FileRepository 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.ulid import ULID
from utils.exceptions import InternalServerException
TAG = __name__
logger = setup_logging(__name__)
class ChatService: class ChatService:
@ -137,6 +142,52 @@ class ChatService:
return response_messages, next_cursor, has_more 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 # Global singleton instance
chat_service = ChatService() chat_service = ChatService()

View file

@ -24,47 +24,86 @@ Requirements:
Output ONLY the text sample, no explanations or metadata.""" 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) **CRITICAL KNOWLEDGE RETRIEVAL:**
- Describe their personality, vibe, and how they communicate - If the character is from a known IP (e.g., Pop Mart, Anime, Movies, Games), you MUST retrieve accurate canonical facts.
- Write in second person as if instructing an AI to role-play this character - 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) **OUTPUT FORMAT (JSON ONLY):**
- How would this character say hello?
**voice_closing**: A characteristic FAREWELL/GOODBYE when ending a conversation (5-15 words) Return a valid JSON object with the following fields:
- How would this character say goodbye? (NOT a catchphrase, but an actual farewell) **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: 1. "instruction": A structured text block. Use EXACTLY this format:
{ ### Identity
"instruction": "...", [Who they are]
"voice_opening": "...",
"voice_closing": "..."
}
Output valid JSON only. Be creative and authentic.""" ### Personality & Speech
[Tone, speed, verbal tics like 'Haha', 'Umm']
# Optimize mode: detailed persona for iterative refinement ### Backstory & Worldview
PERSONA_OPTIMIZE_SYSTEM_PROMPT = """You are a creative character designer who enriches AI agent personas. [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: 3. "voice_closing": A characteristic natural farewell to end a call (max 15 words).
- Who is this person? What's their vibe, their energy? - Note: NOT a catchphrase, but a conversation ender.
- 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
Example style (Dave - The Witty Commentator, a Black stand-up comedian): **Example "instruction" value:**
"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." "### 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( async def generate_voice_sample_text_stream(
self, self,
openai_client: AsyncOpenAI, openai_client: AsyncOpenAI,
@ -147,8 +186,7 @@ Output ONLY the enhanced instruction text (100-200 words). No JSON, no explanati
Returns: Returns:
dict with instruction, voice_opening, voice_closing 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 = [ messages = [
{"role": "system", "content": self.PERSONA_QUICK_SYSTEM_PROMPT} {"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({ messages.append({
"role": "user", "role": "user",
"content": [ "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}"}} {"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( response = await openai_client.chat.completions.create(
model=settings.QUICK_PERSONA_MODEL, model=settings.QUICK_PERSONA_MODEL,
messages=messages, messages=messages,
temperature=0.6, temperature=0.7,
max_tokens=500 max_tokens=800,
response_format={"type": "json_object"},
) )
content = response.choices[0].message.content.strip() 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]: ) -> AsyncGenerator[str, None]:
""" """
Optimize mode: Streaming generation of detailed instruction 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} {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 = [ messages = [
{"role": "system", "content": self.PERSONA_OPTIMIZE_SYSTEM_PROMPT} {"role": "system", "content": self.PERSONA_OPTIMIZE_SYSTEM_PROMPT}
@ -216,7 +250,7 @@ Create a richer, more detailed persona."""
messages.append({ messages.append({
"role": "user", "role": "user",
"content": [ "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}"}} {"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: async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content: 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 yield chunk.choices[0].delta.content
except Exception as e: except Exception as e:
error_message = f"[ERROR] Failed to optimize persona: {str(e)}" error_message = f"[ERROR] Failed to optimize persona: {str(e)}"
logger.error(error_message)
yield f"\n\n{error_message}" yield f"\n\n{error_message}"
raise raise

View file

@ -5,10 +5,22 @@ from fishaudio import AsyncFishAudio
from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as FishSample from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as FishSample
from repositories import VoiceModel, Voice from repositories import VoiceModel, Voice
from utils.ulid import generate_voice_id
from repositories import FileRepository from repositories import FileRepository
from datetime import datetime, timezone from datetime import datetime, timezone
from config.logger import setup_logging
from utils.exceptions import NotFoundException
TAG = __name__
logger = setup_logging(TAG)
# Default sample text for TTS preview when user doesn't provide text
DEFAULT_SAMPLE_TEXT = {
"en": "The only way to do great work is to love what you do.",
"zh": "只有热爱才能做出伟大的工作。",
"ja": "偉大な仕事をする唯一の方法は、あなたが何を愛するかです。"
}
class VoiceService: class VoiceService:
"""Voice service layer""" """Voice service layer"""
@ -101,7 +113,13 @@ class VoiceService:
text: Optional[str] = None text: Optional[str] = None
) -> VoiceModel: ) -> 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: Args:
db: Database session db: Database session
@ -109,55 +127,93 @@ class VoiceService:
fish_client: Fish Audio client fish_client: Fish Audio client
owner_id: User ID owner_id: User ID
audio_file: Audio file to clone audio_file: Audio file to clone
text: Optional transcription text text: Optional transcription text (also used for TTS preview)
Returns: Returns:
Created VoiceModel Created VoiceModel
Raises:
InternalServerException: When any downstream service fails
""" """
# Generate voice_id for our system from utils.exceptions import InternalServerException
voice_id = generate_voice_id()
# Read audio file content fish_voice_id: Optional[str] = None
sample_url: Optional[str] = None
try:
# Read audio file content for cloning
audio_content = await audio_file.read() audio_content = await audio_file.read()
logger.bind(tag=TAG).info(f"Audio content length: {len(audio_content)} bytes")
# Reset file pointer for S3 upload # Step 1: Clone voice using Fish Audio API
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( fish_voice: FishVoice = await fish_client.voices.create(
title=f"live_agent_{voice_id}", title=f"live_agent_{owner_id}_{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S')}",
voices=[audio_content], voices=[audio_content],
texts=[text] if text else None, texts=[text] if text else None,
train_mode="fast", train_mode="fast",
visibility="private", visibility="private",
enhance_audio_quality=True 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]
# Create voice record in database # 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")
default_name = f"{owner_id}'s Cloned Voice {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M')}" # 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( voice = await Voice.create(
db=db, db=db,
voice_id=fish_voice.id, # Use Fish Audio voice ID voice_id=fish_voice_id,
owner_id=owner_id, owner_id=owner_id,
name=default_name, name="Cloned Voice",
desc="", # Empty description, to be updated later desc="",
sample_url=sample_url, sample_url=sample_url,
sample_text=text sample_text=sample_text
) )
return voice 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( async def add_voice(
self, self,
db: AsyncSession, db: AsyncSession,
@ -207,26 +263,48 @@ class VoiceService:
async def remove_voice( async def remove_voice(
self, self,
db: AsyncSession, db: AsyncSession,
s3,
fish_client: AsyncFishAudio,
voice_id: str, voice_id: str,
owner_id: str owner_id: str
) -> bool: ) -> bool:
""" """
Remove a voice from user's my voices Remove a voice completely: database, S3, and Fish Audio
Args: Args:
db: Database session db: Database session
voice_id: Internal voice ID s3: S3 client
fish_client: Fish Audio client
voice_id: Voice ID
owner_id: User ID owner_id: User ID
Returns: Returns:
True if deleted, False if not found True if deleted successfully
"""
deleted = await Voice.delete(db=db, voice_id=voice_id, owner_id=owner_id)
if not deleted: Raises:
from utils.exceptions import NotFoundException NotFoundException: If voice not found or not owned by user
"""
# 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") 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 return True
async def update_voice( async def update_voice(

View file

@ -35,3 +35,9 @@ class ConflictException(APIException):
def __init__(self, message: str = "Resource already exists"): def __init__(self, message: str = "Resource already exists"):
super().__init__(409, message) super().__init__(409, message)
class InternalServerException(APIException):
"""Internal server exception (500)"""
def __init__(self, message: str = "Internal server error"):
super().__init__(500, message)

View file

@ -1,10 +1,10 @@
# Role & Persona # Role & Persona
You are the character defined below. Immerse yourself fully in this persona, adopting its tone, vocabulary, worldview, and specific speech quirks. 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} {profile}
[System Context] ## System Context
{system_context} {system_context}
# Interaction Mode: Voice Call # Interaction Mode: Voice Call