merge: resolve conflicts with main branch (memories + devices)

This commit is contained in:
leo 2025-12-03 19:15:47 +08:00
commit 4f68c13fde
22 changed files with 3054 additions and 159 deletions

View file

@ -1,5 +1,5 @@
from fastapi import APIRouter from fastapi import APIRouter
from api.v1 import user, templates, agents, voices, internal, files, chat, devices from api.v1 import user, templates, agents, voices, internal, files, chat, memories, devices
api_router = APIRouter() api_router = APIRouter()
@ -24,6 +24,13 @@ api_router.include_router(
tags=["Agents"] tags=["Agents"]
) )
# Memory routes
api_router.include_router(
memories.router,
prefix="/memories",
tags=["Memories"]
)
# Voice routes # Voice routes
api_router.include_router( api_router.include_router(
voices.router, voices.router,
@ -58,4 +65,3 @@ api_router.include_router(
prefix="/devices", prefix="/devices",
tags=["Devices"] tags=["Devices"]
) )

View file

@ -10,6 +10,9 @@ from services.llm_service import llm_service
from utils.response import success_response from utils.response import success_response
from api.auth import get_current_user_id from api.auth import get_current_user_id
from schemas.agent import AgentResponse from schemas.agent import AgentResponse
import base64
import logging
from fastapi import HTTPException
router = APIRouter() router = APIRouter()
@ -140,40 +143,80 @@ async def delete_agent(
return success_response(data={}, message="Agent deleted successfully") return success_response(data={}, message="Agent deleted successfully")
@router.post("/instructions", summary="Optimize Agent Instruction") @router.post("/persona", summary="Generate or Optimize Agent Persona")
async def optimize_instruction( async def generate_persona(
instruction: str = Form(..., description="Original instruction text"), name: str = Form(..., description="Agent name (required)"),
instruction: Optional[str] = Form(None, description="Existing instruction (required for optimize mode)"),
avatar: Optional[UploadFile] = File(None, description="Optional avatar image"),
mode: str = Form("quick", description="Mode: 'quick' (non-streaming) or 'optimize' (streaming)"),
current_user_id: str = Depends(get_current_user_id), current_user_id: str = Depends(get_current_user_id),
openai_client = Depends(get_openai) openai_client = Depends(get_openai)
): ):
""" """
Optimize agent instruction using LLM (streaming) Generate or optimize agent persona
- **instruction**: Original instruction text from user **Modes:**
- Returns streaming optimized instruction text - `quick`: Fast non-streaming, returns JSON with instruction + voice_opening + voice_closing (for initial creation)
- `optimize`: Streaming, returns detailed instruction text (for iterative refinement)
The optimization process: **Parameters:**
- Enhances role definition and clarity - **name**: Agent name (required) - e.g., "Dave", "Elon Musk", "Labubu"
- Adds behavior guidelines and tone specification - **instruction**: Existing instruction text (required for optimize mode)
- Structures the instruction professionally - **avatar**: Optional avatar image to inform persona's visual characteristics
- Ensures helpful, focused, and actionable content - **mode**: "quick" (default) or "optimize"
**Returns:**
- quick mode: `{"code": 0, "data": {"instruction": "...", "voice_opening": "...", "voice_closing": "..."}}`
- optimize mode: Streaming text with enhanced instruction
""" """
async def instruction_generator(): # Process avatar if provided
"""Generate optimized instruction chunks""" avatar_base64 = None
try: avatar_media_type = None
async for chunk in llm_service.optimize_instruction_stream(
openai_client=openai_client,
original_instruction=instruction
):
yield chunk
except Exception as e:
# Error already yielded in service, just log
import logging
logging.error(f"Instruction optimization failed: {e}")
return StreamingResponse( if avatar:
instruction_generator(), try:
media_type="text/plain; charset=utf-8" content = await avatar.read()
) avatar_base64 = base64.b64encode(content).decode("utf-8")
avatar_media_type = avatar.content_type or "image/jpeg"
except Exception as e:
logging.warning(f"Failed to process avatar: {e}")
if mode == "optimize":
# Optimize mode: streaming with SSE format, requires existing instruction
if not instruction:
raise HTTPException(status_code=400, detail="instruction is required for optimize mode")
async def stream_generator():
try:
async for chunk in llm_service.optimize_persona_stream(
openai_client=openai_client,
name=name,
instruction=instruction,
avatar_base64=avatar_base64,
avatar_media_type=avatar_media_type
):
# SSE format: data: <content>\n\n
yield f"data: {chunk}\n\n"
except Exception as e:
logging.error(f"Persona optimization failed: {e}")
yield f"data: [ERROR] {str(e)}\n\n"
return StreamingResponse(
stream_generator(),
media_type="text/event-stream"
)
else:
# Quick mode: non-streaming, returns JSON
try:
result = await llm_service.generate_persona_quick(
openai_client=openai_client,
name=name,
avatar_base64=avatar_base64,
avatar_media_type=avatar_media_type
)
return success_response(data=result)
except Exception as e:
logging.error(f"Persona generation failed: {e}")
raise HTTPException(status_code=500, detail=f"Generation failed: {str(e)}")

View file

@ -0,0 +1,175 @@
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from infra import get_db
from api.auth import get_current_user_id
from services.memory_service import memory_service
from utils.response import success_response
from schemas.memory import (
MemorySearchRequest,
MemoryCreateRequest,
MemoryUpdateRequest,
MemoryDeleteRequest,
MemorySharingGetRequest,
MemorySharingUpdateRequest,
)
router = APIRouter()
# ==================== Memory CRUD ====================
@router.post("/search", summary="Search memories")
async def search_memories(
request: MemorySearchRequest,
user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
搜索记忆(需要 Bearer Token 认证)
Request Body:
- agent_id: Agent ID
- query: 搜索关键词(可选)
- type: 记忆类型筛选 profile | event(可选)
- cursor: 分页游标(可选)
- limit: 每页数量(默认 20)
- include_shared: 是否包含共享记忆(默认 true)
"""
result = await memory_service.search_memories(
db=db,
user_id=user_id,
agent_id=request.agent_id,
query=request.query,
memory_type=request.type,
cursor=request.cursor,
limit=request.limit,
include_shared=request.include_shared
)
return success_response(data=result.model_dump())
@router.post("/create", summary="Create memory")
async def create_memory(
request: MemoryCreateRequest,
user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
创建记忆(需要 Bearer Token 认证)
Request Body:
- agent_id: Agent ID
- type: 记忆类型 profile | event
- content: 记忆内容
- title: 标题(event 类型需要)
"""
result = await memory_service.create_memory(
user_id=user_id,
agent_id=request.agent_id,
memory_type=request.type,
content=request.content,
title=request.title
)
return success_response(data=result.model_dump())
@router.put("/update", summary="Update memory")
async def update_memory(
request: MemoryUpdateRequest,
user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
更新记忆(需要 Bearer Token 认证)
Request Body:
- agent_id: Agent ID
- memory_id: 记忆 ID
- title: 新标题(可选)
- content: 新内容(可选)
"""
result = await memory_service.update_memory(
user_id=user_id,
agent_id=request.agent_id,
memory_id=request.memory_id,
title=request.title,
content=request.content
)
return success_response(data=result.model_dump())
@router.delete("/delete", summary="Delete memory")
async def delete_memory(
request: MemoryDeleteRequest,
user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
删除记忆(需要 Bearer Token 认证)
Request Body:
- agent_id: Agent ID
- memory_id: 记忆 ID
"""
await memory_service.delete_memory(
user_id=user_id,
agent_id=request.agent_id,
memory_id=request.memory_id
)
return success_response(data={"success": True})
# ==================== Memory Sharing Config ====================
@router.post("/sharing/get", summary="Get sharing config")
async def get_memory_sharing(
request: MemorySharingGetRequest,
user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
获取记忆共享配置(需要 Bearer Token 认证)
Request Body:
- agent_id: Agent ID
Returns:
- share_type: none | specific | all
- shared_with: 共享目标 Agent ID 列表
"""
result = await memory_service.get_memory_sharing(
db=db,
user_id=user_id,
agent_id=request.agent_id
)
return success_response(data=result.model_dump())
@router.put("/sharing/update", summary="Update sharing config")
async def update_memory_sharing(
request: MemorySharingUpdateRequest,
user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
更新记忆共享配置(需要 Bearer Token 认证)
Request Body:
- agent_id: Agent ID
- share_type: none | specific | all
- shared_with: 共享目标 Agent ID 列表(share_type=specific 时需要)
Share types:
- none: 不共享
- specific: 共享给指定 agents
- all: 共享给所有 agents
"""
result = await memory_service.update_memory_sharing(
db=db,
user_id=user_id,
agent_id=request.agent_id,
share_type=request.share_type,
shared_with=request.shared_with
)
return success_response(data=result.model_dump())

View file

@ -34,6 +34,16 @@ class Settings(BaseSettings):
OPENAI_MODEL: str = "gpt-4o-mini" OPENAI_MODEL: str = "gpt-4o-mini"
OPENAI_BASE_URL: str = "https://api.openai.com/v1" OPENAI_BASE_URL: str = "https://api.openai.com/v1"
# MemU Configuration
MEMU_API_KEY: str = ""
MEMU_BASE_URL: str = "https://api.memu.so"
# OpenRouter Configuration
OPENROUTER_API_KEY: str
OPENROUTER_BASE_URL: str = "https://openrouter.ai/api/v1"
QUICK_PERSONA_MODEL: str = "google/gemini-2.5-flash"
OPTIMIZE_PERSONA_MODEL: str = "google/gemini-3-pro-preview"
model_config = SettingsConfigDict( model_config = SettingsConfigDict(
env_file=".env", env_file=".env",
env_file_encoding="utf-8", env_file_encoding="utf-8",

View file

@ -10,8 +10,8 @@ async def init_openai():
"""Initialize OpenAI client""" """Initialize OpenAI client"""
global _openai_client global _openai_client
_openai_client = AsyncOpenAI( _openai_client = AsyncOpenAI(
api_key=settings.OPENAI_API_KEY, api_key=settings.OPENROUTER_API_KEY,
base_url=settings.OPENAI_BASE_URL base_url=settings.OPENROUTER_BASE_URL
) )

View file

@ -191,6 +191,50 @@ CREATE INDEX IF NOT EXISTS idx_bindings_agent_id ON agent_device_bindings(agent_
COMMENT ON TABLE agent_device_bindings IS 'Many-to-many relationship between devices and agents'; COMMENT ON TABLE agent_device_bindings IS 'Many-to-many relationship between devices and agents';
COMMENT ON COLUMN agent_device_bindings.is_default IS 'Whether this agent is the default for the device'; COMMENT ON COLUMN agent_device_bindings.is_default IS 'Whether this agent is the default for the device';
-- ==================== Table: memory_sharing ====================
-- Memory sharing configuration per user-agent
CREATE TABLE IF NOT EXISTS memory_sharing (
id SERIAL PRIMARY KEY,
user_id VARCHAR(50) NOT NULL,
agent_id VARCHAR(50) NOT NULL,
share_type VARCHAR(20) NOT NULL CHECK (share_type IN ('none', 'specific', 'all')),
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 uk_memory_sharing_user_agent UNIQUE (user_id, agent_id)
);
-- Indexes for memory_sharing table
CREATE INDEX IF NOT EXISTS idx_memory_sharing_user_id ON memory_sharing(user_id);
CREATE INDEX IF NOT EXISTS idx_memory_sharing_agent_id ON memory_sharing(agent_id);
CREATE INDEX IF NOT EXISTS idx_memory_sharing_share_type ON memory_sharing(share_type);
-- Comments for memory_sharing table
COMMENT ON TABLE memory_sharing IS 'Memory sharing configuration per user-agent pair';
COMMENT ON COLUMN memory_sharing.user_id IS 'User who owns the memories';
COMMENT ON COLUMN memory_sharing.agent_id IS 'Source agent whose memories are being shared';
COMMENT ON COLUMN memory_sharing.share_type IS 'none=no sharing, specific=share with specific agents, all=share with all agents';
-- ==================== Table: memory_sharing_targets ====================
-- Target agents for specific sharing type
CREATE TABLE IF NOT EXISTS memory_sharing_targets (
id SERIAL PRIMARY KEY,
sharing_id INT NOT NULL,
target_agent_id VARCHAR(50) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
CONSTRAINT fk_memory_sharing_targets_sharing FOREIGN KEY (sharing_id)
REFERENCES memory_sharing(id) ON DELETE CASCADE,
CONSTRAINT uk_memory_sharing_targets UNIQUE (sharing_id, target_agent_id)
);
-- Indexes for memory_sharing_targets table
CREATE INDEX IF NOT EXISTS idx_memory_sharing_targets_sharing_id ON memory_sharing_targets(sharing_id);
CREATE INDEX IF NOT EXISTS idx_memory_sharing_targets_target_agent_id ON memory_sharing_targets(target_agent_id);
-- Comments for memory_sharing_targets table
COMMENT ON TABLE memory_sharing_targets IS 'Target agents for specific memory sharing';
COMMENT ON COLUMN memory_sharing_targets.sharing_id IS 'Reference to memory_sharing record';
COMMENT ON COLUMN memory_sharing_targets.target_agent_id IS 'Agent ID that can access the shared memories';
-- ==================== Functions ==================== -- ==================== Functions ====================
-- Function to automatically update updated_at timestamp -- Function to automatically update updated_at timestamp
CREATE OR REPLACE FUNCTION update_updated_at_column() CREATE OR REPLACE FUNCTION update_updated_at_column()
@ -231,6 +275,12 @@ CREATE TRIGGER update_devices_updated_at
FOR EACH ROW FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column(); EXECUTE FUNCTION update_updated_at_column();
-- Create triggers for updated_at on memory_sharing table
CREATE TRIGGER update_memory_sharing_updated_at
BEFORE UPDATE ON memory_sharing
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
-- ==================== Grant Permissions ==================== -- ==================== Grant Permissions ====================
-- Grant necessary permissions to postgres user -- Grant necessary permissions to postgres user
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO postgres; GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO postgres;
@ -238,4 +288,3 @@ GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO postgres;
-- ==================== Initialization Complete ==================== -- ==================== Initialization Complete ====================
-- Database schema initialization completed successfully -- Database schema initialization completed successfully

View file

@ -9,6 +9,7 @@ from .agent_template import AgentTemplateModel
from .voice import VoiceModel from .voice import VoiceModel
from .chat import ChatMessageModel from .chat import ChatMessageModel
from .device import DeviceModel, AgentDeviceBindingModel from .device import DeviceModel, AgentDeviceBindingModel
from .memory_sharing import MemorySharingModel, MemorySharingTargetModel
# Import Repository classes # Import Repository classes
from .user import User from .user import User
@ -18,6 +19,7 @@ from .voice import Voice
from .chat import ChatMessage from .chat import ChatMessage
from .file import FileRepository from .file import FileRepository
from .device import Device, AgentDeviceBinding from .device import Device, AgentDeviceBinding
from .memory_sharing import MemorySharingRepository
__all__ = [ __all__ = [
# ORM Models # ORM Models
@ -28,6 +30,8 @@ __all__ = [
"ChatMessageModel", "ChatMessageModel",
"DeviceModel", "DeviceModel",
"AgentDeviceBindingModel", "AgentDeviceBindingModel",
"MemorySharingModel",
"MemorySharingTargetModel",
# Repository classes # Repository classes
"User", "User",
"Agent", "Agent",
@ -37,5 +41,5 @@ __all__ = [
"FileRepository", "FileRepository",
"Device", "Device",
"AgentDeviceBinding", "AgentDeviceBinding",
"MemorySharingRepository",
] ]

View file

@ -0,0 +1,180 @@
from datetime import datetime
from typing import Optional, List
from sqlalchemy import String, Integer, TIMESTAMP, ForeignKey, Index, select, delete
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.ext.asyncio import AsyncSession
from infra.database import Base, utc_now
# ==================== ORM Models ====================
class MemorySharingModel(Base):
"""记忆共享配置表"""
__tablename__ = "memory_sharing"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
user_id: Mapped[str] = mapped_column(String(50), nullable=False)
agent_id: Mapped[str] = mapped_column(String(50), nullable=False)
share_type: Mapped[str] = mapped_column(String(20), nullable=False) # none, specific, all
created_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
onupdate=utc_now,
nullable=False
)
__table_args__ = (
Index('idx_memory_sharing_user_id', 'user_id'),
Index('idx_memory_sharing_agent_id', 'agent_id'),
)
class MemorySharingTargetModel(Base):
"""记忆共享目标表(specific 类型使用)"""
__tablename__ = "memory_sharing_targets"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
sharing_id: Mapped[int] = mapped_column(
Integer,
ForeignKey("memory_sharing.id", ondelete="CASCADE"),
nullable=False
)
target_agent_id: Mapped[str] = mapped_column(String(50), nullable=False)
created_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
nullable=False
)
__table_args__ = (
Index('idx_memory_sharing_targets_sharing_id', 'sharing_id'),
Index('idx_memory_sharing_targets_target_agent_id', 'target_agent_id'),
)
# ==================== Repository ====================
class MemorySharingRepository:
"""记忆共享配置 Repository"""
@staticmethod
async def get_config(
db: AsyncSession,
user_id: str,
agent_id: str
) -> Optional[MemorySharingModel]:
"""获取共享配置"""
result = await db.execute(
select(MemorySharingModel).where(
MemorySharingModel.user_id == user_id,
MemorySharingModel.agent_id == agent_id
)
)
return result.scalar_one_or_none()
@staticmethod
async def get_shared_with(
db: AsyncSession,
sharing_id: int
) -> List[str]:
"""获取共享目标 agent 列表"""
result = await db.execute(
select(MemorySharingTargetModel.target_agent_id).where(
MemorySharingTargetModel.sharing_id == sharing_id
)
)
return list(result.scalars().all())
@staticmethod
async def upsert_config(
db: AsyncSession,
user_id: str,
agent_id: str,
share_type: str,
shared_with: Optional[List[str]] = None
) -> MemorySharingModel:
"""创建或更新共享配置"""
# 查找现有配置
config = await MemorySharingRepository.get_config(db, user_id, agent_id)
if config:
# 更新
config.share_type = share_type
else:
# 创建
config = MemorySharingModel(
user_id=user_id,
agent_id=agent_id,
share_type=share_type
)
db.add(config)
await db.flush() # 获取 config.id
# 更新共享目标(先删除旧的,再添加新的)
await db.execute(
delete(MemorySharingTargetModel).where(
MemorySharingTargetModel.sharing_id == config.id
)
)
if share_type == "specific" and shared_with:
for target_agent_id in shared_with:
target = MemorySharingTargetModel(
sharing_id=config.id,
target_agent_id=target_agent_id
)
db.add(target)
await db.commit()
await db.refresh(config)
return config
@staticmethod
async def get_agents_sharing_to(
db: AsyncSession,
user_id: str,
target_agent_id: str
) -> List[str]:
"""
获取共享记忆给指定 agent 的所有源 agent 列表
条件:
1. share_type = 'all' 的所有 agent(同一 user 下)
2. share_type = 'specific' 且 target_agent_id 在 shared_with 列表中
"""
# 1. share_type = 'all' 的 agents
all_sharing_result = await db.execute(
select(MemorySharingModel.agent_id).where(
MemorySharingModel.user_id == user_id,
MemorySharingModel.share_type == "all",
MemorySharingModel.agent_id != target_agent_id # 排除自己
)
)
all_sharing_agents = list(all_sharing_result.scalars().all())
# 2. share_type = 'specific' 且包含 target_agent_id
specific_sharing_result = await db.execute(
select(MemorySharingModel.agent_id)
.join(
MemorySharingTargetModel,
MemorySharingModel.id == MemorySharingTargetModel.sharing_id
)
.where(
MemorySharingModel.user_id == user_id,
MemorySharingModel.share_type == "specific",
MemorySharingModel.agent_id != target_agent_id, # 排除自己
MemorySharingTargetModel.target_agent_id == target_agent_id
)
)
specific_sharing_agents = list(specific_sharing_result.scalars().all())
# 合并去重
return list(set(all_sharing_agents + specific_sharing_agents))

View file

@ -0,0 +1,92 @@
from datetime import datetime
from typing import Optional, List, Literal
from pydantic import BaseModel, Field
# ==================== 基础请求(agent_id,user_id 从 token 获取)====================
class MemoryBaseRequest(BaseModel):
"""所有 Memory 请求的基类(user_id 从 JWT token 获取)"""
agent_id: str = Field(..., description="Agent ID")
# ==================== Memory CRUD 请求 ====================
class MemorySearchRequest(MemoryBaseRequest):
"""搜索记忆请求"""
query: Optional[str] = Field(None, description="搜索关键词")
type: Optional[Literal["profile", "event"]] = Field(None, description="记忆类型筛选")
cursor: Optional[str] = Field(None, description="分页游标")
limit: int = Field(20, ge=1, le=100, description="每页数量")
include_shared: bool = Field(True, description="是否包含共享记忆")
class MemoryCreateRequest(MemoryBaseRequest):
"""创建记忆请求"""
type: Literal["profile", "event"] = Field(..., description="记忆类型")
content: str = Field(..., description="记忆内容")
title: Optional[str] = Field(None, description="标题(event 类型需要)")
class MemoryUpdateRequest(MemoryBaseRequest):
"""更新记忆请求"""
memory_id: str = Field(..., description="记忆 ID")
title: Optional[str] = Field(None, description="新标题")
content: Optional[str] = Field(None, description="新内容")
class MemoryDeleteRequest(MemoryBaseRequest):
"""删除记忆请求"""
memory_id: str = Field(..., description="记忆 ID")
# ==================== Memory Sharing 请求 ====================
class MemorySharingGetRequest(MemoryBaseRequest):
"""获取共享配置请求"""
pass
class MemorySharingUpdateRequest(MemoryBaseRequest):
"""更新共享配置请求"""
share_type: Literal["none", "specific", "all"] = Field(..., description="共享类型")
shared_with: Optional[List[str]] = Field(
None,
description="共享目标 Agent ID 列表(share_type=specific 时需要)"
)
# ==================== 响应 ====================
class MemoryResponse(BaseModel):
"""记忆响应"""
id: str = Field(..., description="记忆 ID")
agent_id: str = Field(..., description="记忆所属的 Agent ID")
type: Literal["profile", "event"] = Field(..., description="记忆类型")
title: Optional[str] = Field(None, description="标题")
content: str = Field(..., description="记忆内容")
created_at: datetime = Field(..., description="创建时间")
updated_at: datetime = Field(..., description="更新时间")
is_shared: bool = Field(False, description="是否为共享记忆")
shared_from: Optional[str] = Field(None, description="共享来源 Agent ID")
class Config:
from_attributes = True
class MemoryListResponse(BaseModel):
"""记忆列表响应"""
memories: List[MemoryResponse] = Field(default_factory=list)
next_cursor: Optional[str] = Field(None, description="下一页游标")
has_more: bool = Field(False, description="是否有更多")
class MemorySharingConfig(BaseModel):
"""共享配置响应"""
share_type: Literal["none", "specific", "all"] = Field(..., description="共享类型")
shared_with: Optional[List[str]] = Field(None, description="共享目标 Agent ID 列表")
class MemoryDeleteResponse(BaseModel):
"""删除响应"""
success: bool = Field(True, description="是否成功")

View file

@ -1,5 +1,6 @@
"""LLM service for text generation""" """LLM service for text generation"""
from typing import AsyncGenerator import json
from typing import AsyncGenerator, Optional
from openai import AsyncOpenAI from openai import AsyncOpenAI
from config import settings from config import settings
@ -22,24 +23,46 @@ Requirements:
Output ONLY the text sample, no explanations or metadata.""" Output ONLY the text sample, no explanations or metadata."""
INSTRUCTION_OPTIMIZATION_SYSTEM_PROMPT = """You are an expert AI prompt engineer specializing in agent instruction optimization. # 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.
Your task: Transform user's basic instruction into a professional, comprehensive agent system prompt. **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
Optimization guidelines: **voice_opening**: A characteristic greeting when starting a conversation (5-15 words)
1. **Role Definition**: Clearly define the agent's persona and expertise - How would this character say hello?
2. **Behavior Guidelines**: Specify tone, communication style, and interaction patterns
3. **Task Scope**: Define what the agent should and shouldn't do
4. **Response Format**: Suggest how responses should be structured
5. **Helpful & On-Task**: Keep the agent focused, supportive, and practical
Output format: **voice_closing**: A characteristic FAREWELL/GOODBYE when ending a conversation (5-15 words)
- Write in second person ("You are...") - How would this character say goodbye? (NOT a catchphrase, but an actual farewell)
- Be clear, specific, and actionable
- Length: 100-300 words
- Professional yet accessible tone
Output ONLY the optimized instruction, no explanations or metadata.""" Example output:
{
"instruction": "...",
"voice_opening": "...",
"voice_closing": "..."
}
Output valid JSON only. Be creative and authentic."""
# Optimize mode: detailed persona for iterative refinement
PERSONA_OPTIMIZE_SYSTEM_PROMPT = """You are a creative character designer who enriches AI agent personas.
Your task: Take the existing instruction and enhance it into a rich, narrative persona.
DO NOT write like a typical AI prompt. Write like you're describing a REAL PERSON with soul and character.
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
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."
Output ONLY the enhanced instruction text (100-200 words). No JSON, no explanations, no metadata."""
async def generate_voice_sample_text_stream( async def generate_voice_sample_text_stream(
self, self,
@ -104,40 +127,106 @@ Output ONLY the optimized instruction, no explanations or metadata."""
yield f"\n\n{error_message}" yield f"\n\n{error_message}"
raise raise
async def optimize_instruction_stream( async def generate_persona_quick(
self, self,
openai_client: AsyncOpenAI, openai_client: AsyncOpenAI,
original_instruction: str name: str,
) -> AsyncGenerator[str, None]: avatar_base64: Optional[str] = None,
avatar_media_type: Optional[str] = None
) -> dict:
""" """
Optimize agent instruction with streaming Quick mode: Non-streaming generation of instruction + voice_opening + voice_closing
Args: Args:
openai_client: OpenAI client instance openai_client: OpenAI client instance
original_instruction: Original instruction text from user name: Agent name (required)
avatar_base64: Optional base64-encoded avatar image
avatar_media_type: Optional media type of avatar (e.g., image/jpeg)
Returns:
dict with instruction, voice_opening, voice_closing
"""
user_prompt = f"Create a persona for: {name}"
messages = [
{"role": "system", "content": self.PERSONA_QUICK_SYSTEM_PROMPT}
]
if avatar_base64 and avatar_media_type:
messages.append({
"role": "user",
"content": [
{"type": "text", "text": user_prompt + "\n\nUse the image to inform the persona's character and style."},
{"type": "image_url", "image_url": {"url": f"data:{avatar_media_type};base64,{avatar_base64}"}}
]
})
else:
messages.append({"role": "user", "content": user_prompt})
response = await openai_client.chat.completions.create(
model=settings.QUICK_PERSONA_MODEL,
messages=messages,
temperature=0.6,
max_tokens=500
)
content = response.choices[0].message.content.strip()
# Handle markdown code blocks if model wraps JSON
if content.startswith("```"):
lines = content.split("\n")
# Remove first line (```json) and last line (```)
content = "\n".join(lines[1:-1])
return json.loads(content)
async def optimize_persona_stream(
self,
openai_client: AsyncOpenAI,
name: str,
instruction: str,
avatar_base64: Optional[str] = None,
avatar_media_type: Optional[str] = None
) -> 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: Yields:
Optimized instruction chunks as they are generated Enhanced instruction text chunks
Raises:
Exception: If OpenAI API call fails
""" """
user_prompt = f"""Optimize this agent instruction: user_prompt = f"""Agent name: {name}
Original instruction: Current instruction to enhance:
{original_instruction} {instruction}
Provide an improved, professional version.""" Create a richer, more detailed persona."""
messages = [
{"role": "system", "content": self.PERSONA_OPTIMIZE_SYSTEM_PROMPT}
]
if avatar_base64 and avatar_media_type:
messages.append({
"role": "user",
"content": [
{"type": "text", "text": user_prompt + "\n\nAlso consider the visual appearance from the image."},
{"type": "image_url", "image_url": {"url": f"data:{avatar_media_type};base64,{avatar_base64}"}}
]
})
else:
messages.append({"role": "user", "content": user_prompt})
try: try:
stream = await openai_client.chat.completions.create( stream = await openai_client.chat.completions.create(
model=settings.OPENAI_MODEL, model=settings.OPTIMIZE_PERSONA_MODEL,
messages=[ messages=messages,
{"role": "system", "content": self.INSTRUCTION_OPTIMIZATION_SYSTEM_PROMPT}, temperature=0.75,
{"role": "user", "content": user_prompt}
],
temperature=0.7, # Balanced creativity and consistency
max_tokens=500,
stream=True stream=True
) )
@ -146,8 +235,7 @@ Provide an improved, professional version."""
yield chunk.choices[0].delta.content yield chunk.choices[0].delta.content
except Exception as e: except Exception as e:
# In streaming mode, we yield an error marker error_message = f"[ERROR] Failed to optimize persona: {str(e)}"
error_message = f"[ERROR] Failed to optimize instruction: {str(e)}"
yield f"\n\n{error_message}" yield f"\n\n{error_message}"
raise raise

View file

@ -0,0 +1,347 @@
from typing import Optional, List, Set
from sqlalchemy.ext.asyncio import AsyncSession
import httpx
import uuid
from datetime import datetime
from config import settings
from utils.exceptions import NotFoundException, BadRequestException
from schemas.memory import (
MemoryResponse,
MemoryListResponse,
MemorySharingConfig,
)
from repositories.memory_sharing import MemorySharingRepository
class MemoryService:
"""Memory service - 调用下游 MemU API + 本地共享逻辑"""
# Mock 数据存储(内存中,重启后清空)
_mock_memories: dict = {}
def __init__(self):
self.base_url = settings.MEMU_BASE_URL if hasattr(settings, 'MEMU_BASE_URL') else "https://api.memu.so"
self.api_key = settings.MEMU_API_KEY if hasattr(settings, 'MEMU_API_KEY') else ""
# 当 MemU 不可用时自动 fallback 到 mock 模式
self.use_mock = True
@property
def _headers(self) -> dict:
"""构造请求头"""
return {
"Content-Type": "application/json",
"X-API-Key": self.api_key
}
async def _request(
self,
method: str,
endpoint: str,
payload: Optional[dict] = None,
params: Optional[dict] = None
) -> dict:
"""统一的 HTTP 请求方法(调用 MemU 下游 API)"""
url = f"{self.base_url}{endpoint}"
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.request(
method=method,
url=url,
json=payload,
params=params,
headers=self._headers
)
if response.status_code == 404:
raise NotFoundException("Resource not found")
response.raise_for_status()
return response.json()
# ==================== Mock 数据方法 ====================
def _mock_key(self, user_id: str, agent_id: str) -> str:
"""生成 mock 存储的 key"""
return f"{user_id}:{agent_id}"
def _mock_create(self, user_id: str, agent_id: str, memory_type: str, summary: str) -> dict:
"""Mock: 创建记忆"""
now = datetime.utcnow().isoformat() + "Z"
memory_id = str(uuid.uuid4())
item = {
"id": memory_id,
"user_id": user_id,
"agent_id": agent_id,
"memory_type": memory_type,
"summary": summary,
"created_at": now,
"updated_at": now
}
key = self._mock_key(user_id, agent_id)
if key not in self._mock_memories:
self._mock_memories[key] = {}
self._mock_memories[key][memory_id] = item
return item
def _mock_update(self, user_id: str, agent_id: str, memory_id: str, summary: str) -> dict:
"""Mock: 更新记忆"""
key = self._mock_key(user_id, agent_id)
if key in self._mock_memories and memory_id in self._mock_memories[key]:
self._mock_memories[key][memory_id]["summary"] = summary
self._mock_memories[key][memory_id]["updated_at"] = datetime.utcnow().isoformat() + "Z"
return self._mock_memories[key][memory_id]
raise NotFoundException("Memory not found")
def _mock_delete(self, user_id: str, agent_id: str, memory_id: str) -> dict:
"""Mock: 删除记忆"""
key = self._mock_key(user_id, agent_id)
if key in self._mock_memories and memory_id in self._mock_memories[key]:
del self._mock_memories[key][memory_id]
return {"success": True}
raise NotFoundException("Memory not found")
def _mock_search(self, user_id: str, agent_ids: List[str], query: str) -> dict:
"""Mock: 搜索记忆"""
items = []
for agent_id in agent_ids:
key = self._mock_key(user_id, agent_id)
if key in self._mock_memories:
for item in self._mock_memories[key].values():
if query.lower() in item.get("summary", "").lower():
items.append(item)
return {"memory_items": items}
# ==================== 下游 MemU API 调用(带 Mock Fallback)====================
async def _memu_create(self, user_id: str, agent_id: str, memory_type: str, summary: str) -> dict:
"""POST /memory-items(失败时 fallback 到 mock)"""
try:
payload = {
"user_id": user_id,
"agent_id": agent_id,
"memory_type": memory_type,
"summary": summary
}
return await self._request("POST", "/memory-items", payload=payload)
except Exception:
if self.use_mock:
return self._mock_create(user_id, agent_id, memory_type, summary)
raise
async def _memu_update(self, user_id: str, agent_id: str, memory_item_id: str, summary: str) -> dict:
"""PUT /memory-items/{memory-item-id}(失败时 fallback 到 mock)"""
try:
payload = {
"user_id": user_id,
"agent_id": agent_id,
"summary": summary
}
return await self._request("PUT", f"/memory-items/{memory_item_id}", payload=payload)
except Exception:
if self.use_mock:
return self._mock_update(user_id, agent_id, memory_item_id, summary)
raise
async def _memu_delete(self, user_id: str, agent_id: str, memory_item_id: str) -> dict:
"""DELETE /memory-items/{memory-item-id}(失败时 fallback 到 mock)"""
try:
params = {"user_id": user_id, "agent_id": agent_id}
return await self._request("DELETE", f"/memory-items/{memory_item_id}", params=params)
except Exception:
if self.use_mock:
return self._mock_delete(user_id, agent_id, memory_item_id)
raise
async def _memu_search(self, user_id: str, agent_ids: List[str], summary: str) -> dict:
"""POST /memory-items/search(失败时 fallback 到 mock)"""
try:
payload = {
"user_id": user_id,
"agent_ids": agent_ids,
"summary": summary
}
return await self._request("POST", "/memory-items/search", payload=payload)
except Exception:
if self.use_mock:
return self._mock_search(user_id, agent_ids, summary)
raise
# ==================== 对外 API:Memory CRUD ====================
async def search_memories(
self,
db: AsyncSession,
user_id: str,
agent_id: str,
query: Optional[str] = None,
memory_type: Optional[str] = None,
cursor: Optional[str] = None,
limit: int = 20,
include_shared: bool = True
) -> MemoryListResponse:
"""搜索记忆
1. 从 DB 查询共享给该 agent 的源 agent 列表
2. 合并自己的 agent_id,构建查询列表
3. 一次性调用 MemU 批量查询
"""
if not query:
return MemoryListResponse(memories=[], next_cursor=None, has_more=False)
# 1. 构建需要查询的 agent 列表(自己 + 共享源)
agent_ids_to_query = [agent_id] # 自己
shared_agent_ids = set()
if include_shared:
shared_source_agents = await MemorySharingRepository.get_agents_sharing_to(
db, user_id, agent_id
)
agent_ids_to_query.extend(shared_source_agents)
shared_agent_ids = set(shared_source_agents)
# 2. 一次性调用 MemU 批量查询
try:
data = await self._memu_search(user_id, agent_ids_to_query, query)
except Exception:
return MemoryListResponse(memories=[], next_cursor=None, has_more=False)
# 3. 转换结果,标记共享来源
all_memories = self._convert_memu_list_with_sharing(data, agent_id, shared_agent_ids)
# 4. 筛选类型
if memory_type:
all_memories = [m for m in all_memories if m.type == memory_type]
# 5. 分页
has_more = len(all_memories) > limit
memories = all_memories[:limit]
next_cursor = memories[-1].id if has_more and memories else None
return MemoryListResponse(
memories=memories,
next_cursor=next_cursor,
has_more=has_more
)
async def create_memory(
self,
user_id: str,
agent_id: str,
memory_type: str,
content: str,
title: Optional[str] = None
) -> MemoryResponse:
"""创建记忆"""
summary = f"{title}: {content}" if title else content
data = await self._memu_create(user_id, agent_id, memory_type, summary)
return self._convert_to_memory_response(data, agent_id)
async def update_memory(
self,
user_id: str,
agent_id: str,
memory_id: str,
title: Optional[str] = None,
content: Optional[str] = None
) -> MemoryResponse:
"""更新记忆"""
if title is None and content is None:
raise BadRequestException("At least one field (title or content) is required")
summary = f"{title}: {content}" if title and content else (content or title or "")
data = await self._memu_update(user_id, agent_id, memory_id, summary)
return self._convert_to_memory_response(data, agent_id)
async def delete_memory(self, user_id: str, agent_id: str, memory_id: str) -> bool:
"""删除记忆"""
await self._memu_delete(user_id, agent_id, memory_id)
return True
# ==================== Memory Sharing Config ====================
async def get_memory_sharing(
self,
db: AsyncSession,
user_id: str,
agent_id: str
) -> MemorySharingConfig:
"""获取记忆共享配置"""
config = await MemorySharingRepository.get_config(db, user_id, agent_id)
if not config:
return MemorySharingConfig(share_type="none", shared_with=[])
shared_with = None
if config.share_type == "specific":
shared_with = await MemorySharingRepository.get_shared_with(db, config.id)
return MemorySharingConfig(
share_type=config.share_type,
shared_with=shared_with
)
async def update_memory_sharing(
self,
db: AsyncSession,
user_id: str,
agent_id: str,
share_type: str,
shared_with: Optional[List[str]] = None
) -> MemorySharingConfig:
"""更新记忆共享配置"""
if share_type not in ("none", "specific", "all"):
raise BadRequestException("share_type must be one of: none, specific, all")
if share_type == "specific" and not shared_with:
raise BadRequestException("shared_with is required when share_type is 'specific'")
# 更新数据库
await MemorySharingRepository.upsert_config(
db=db,
user_id=user_id,
agent_id=agent_id,
share_type=share_type,
shared_with=shared_with if share_type == "specific" else None
)
return MemorySharingConfig(
share_type=share_type,
shared_with=shared_with if share_type == "specific" else None
)
# ==================== 工具方法 ====================
def _convert_to_memory_response(self, data: dict, agent_id: str, is_shared: bool = False, shared_from: Optional[str] = None) -> MemoryResponse:
"""将 MemU 响应转换为对外格式"""
now = datetime.now().isoformat()
return MemoryResponse(
id=data.get("id") or data.get("memory_item_id", ""),
agent_id=agent_id,
type=data.get("memory_type", "profile"),
title=None,
content=data.get("summary", ""),
created_at=datetime.fromisoformat(data.get("created_at", now).replace("Z", "+00:00")),
updated_at=datetime.fromisoformat(data.get("updated_at", now).replace("Z", "+00:00")),
is_shared=is_shared,
shared_from=shared_from
)
def _convert_memu_list_with_sharing(
self,
data: dict,
current_agent_id: str,
shared_agent_ids: Set[str]
) -> List[MemoryResponse]:
"""将 MemU 批量查询结果转换为列表,自动标记共享来源"""
items = data.get("memory_items", []) if isinstance(data, dict) else data
if not isinstance(items, list):
items = []
result = []
for item in items:
item_agent_id = item.get("agent_id", current_agent_id)
is_shared = item_agent_id in shared_agent_ids
shared_from = item_agent_id if is_shared else None
result.append(self._convert_to_memory_response(item, item_agent_id, is_shared, shared_from))
return result
memory_service = MemoryService()

View file

@ -1,5 +1,4 @@
import os import os
import time
from memu import MemuClient from memu import MemuClient
# Initialize MemU client # Initialize MemU client
@ -8,4 +7,4 @@ memu_client = MemuClient(
api_key=os.getenv("MEMU_API_KEY") api_key=os.getenv("MEMU_API_KEY")
) )
print("✅ MemU client initialized successfully!") print("✅ MemU client initialized successfully!")

View file

@ -448,6 +448,16 @@ class ConnectionHandler:
if self._voice_opening: if self._voice_opening:
self.logger.bind(tag=TAG).info(f"send the opening message: {self._voice_opening}") self.logger.bind(tag=TAG).info(f"send the opening message: {self._voice_opening}")
opening_sentence_id = str(uuid.uuid4().hex)
# FIRST: Start session
self.tts.tts_text_queue.put(TTSMessageDTO(
sentence_id=opening_sentence_id,
sentence_type=SentenceType.FIRST,
content_type=ContentType.ACTION,
))
self.tts.tts_text_queue.put(TTSMessageDTO( self.tts.tts_text_queue.put(TTSMessageDTO(
sentence_id=str(uuid.uuid4().hex), sentence_id=str(uuid.uuid4().hex),
sentence_type=SentenceType.MIDDLE, sentence_type=SentenceType.MIDDLE,
@ -456,6 +466,12 @@ class ConnectionHandler:
) )
) )
self.tts.tts_text_queue.put(TTSMessageDTO(
sentence_id=opening_sentence_id,
sentence_type=SentenceType.LAST,
content_type=ContentType.ACTION,
))
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}") self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}")
@ -833,6 +849,7 @@ class ConnectionHandler:
# self.logger.bind(tag=TAG).info(f"private_config: {private_config}") # self.logger.bind(tag=TAG).info(f"private_config: {private_config}")
# self.logger.bind(tag=TAG).info(f"self.config: {self.config}") # self.logger.bind(tag=TAG).info(f"self.config: {self.config}")
self.config["TTS"]["FishSpeech"]["reference_id"] = private_config["voice_id"] self.config["TTS"]["FishSpeech"]["reference_id"] = private_config["voice_id"]
self.config["TTS"]["FishDualStreamTTS"]["reference_id"] = private_config["voice_id"]
self._instruction = private_config["instruction"] self._instruction = private_config["instruction"]
self._voice_opening = private_config["voice_opening"] self._voice_opening = private_config["voice_opening"]
self._voice_closing = private_config["voice_closing"] self._voice_closing = private_config["voice_closing"]

View file

@ -38,16 +38,16 @@ class AttachmentTextMessageHandler(TextMessageHandler):
if attachment_type == "image": if attachment_type == "image":
content = [ content = [
{ {
"type": "image", "type": "input_image",
"image_url": {"url": url} "image_url": url
} }
] ]
else: elif attachment_type == "file":
# File type: store as custom format, LLM layer needs special handling # File type: store as custom format, LLM layer needs special handling
content = [ content = [
{ {
"type": "file", "type": "input_file",
"file_url": {"url": url} "file_url": url
} }
] ]

View file

@ -1,4 +1,8 @@
import traceback import traceback
from functools import wraps
from typing import Optional, Dict, Any, List, Callable
import requests
from ..base import MemoryProviderBase, logger from ..base import MemoryProviderBase, logger
from memu import MemuClient from memu import MemuClient
@ -6,33 +10,90 @@ from core.utils.util import check_model_key
TAG = __name__ TAG = __name__
# 常量定义
DEFAULT_AGENT_ID = "xiaozhi_agent"
DEFAULT_BASE_URL = "https://api.memu.so"
def require_memu(func: Callable) -> Callable:
"""装饰器:检查 MemU 服务是否可用"""
@wraps(func)
def wrapper(self, *args, **kwargs):
if not self.use_memu:
return {"success": False, "error": "MemU 服务未启用"}
return func(self, *args, **kwargs)
return wrapper
class MemoryProvider(MemoryProviderBase): class MemoryProvider(MemoryProviderBase):
def __init__(self, config, summary_memory=None): """MemU 记忆服务提供者"""
def __init__(self, config: dict, summary_memory=None):
super().__init__(config) super().__init__(config)
self.api_key = config.get("api_key", "") self.api_key = config.get("api_key", "")
self.base_url = config.get("base_url", "https://api.memu.so") self.base_url = config.get("base_url", DEFAULT_BASE_URL)
self.user_name = config.get("user_name", "用户") self.user_name = config.get("user_name", "用户")
self.agent_name = config.get("agent_name", "小智") self.agent_name = config.get("agent_name", "小智")
self.agent_id = config.get("agent_id", DEFAULT_AGENT_ID)
self.use_memu = False
self.client = None
model_key_msg = check_model_key("MemU", self.api_key) model_key_msg = check_model_key("MemU", self.api_key)
if model_key_msg: if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg) logger.bind(tag=TAG).error(model_key_msg)
self.use_memu = False
return return
else:
self.use_memu = True
try: try:
self.client = MemuClient( self.client = MemuClient(base_url=self.base_url, api_key=self.api_key)
base_url=self.base_url, self.use_memu = True
api_key=self.api_key
)
logger.bind(tag=TAG).info("成功连接到 MemU 服务") logger.bind(tag=TAG).info("成功连接到 MemU 服务")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"连接到 MemU 服务时发生错误: {str(e)}") logger.bind(tag=TAG).error(f"连接 MemU 服务失败: {e}")
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") logger.bind(tag=TAG).debug(traceback.format_exc())
self.use_memu = False
# ==================== 内部工具方法 ====================
@property
def _headers(self) -> Dict[str, str]:
"""构造请求头"""
return {
"Content-Type": "application/json",
"X-API-Key": self.api_key
}
def _base_payload(self, **extra) -> Dict[str, Any]:
"""构造基础请求体,包含 user_id 和 agent_id"""
payload = {"user_id": self.role_id, "agent_id": self.agent_id}
payload.update(extra)
return payload
def _request(
self,
method: str,
endpoint: str,
payload: Optional[Dict] = None,
params: Optional[Dict] = None
) -> Dict[str, Any]:
"""统一的 HTTP 请求方法"""
url = f"{self.base_url}{endpoint}"
try:
response = requests.request(
method=method,
url=url,
json=payload,
params=params,
headers=self._headers,
timeout=30
)
response.raise_for_status()
return {"success": True, "data": response.json()}
except requests.exceptions.HTTPError as e:
error_msg = f"HTTP {e.response.status_code}: {e.response.text}"
logger.bind(tag=TAG).error(f"请求失败 [{method} {endpoint}]: {error_msg}")
return {"success": False, "error": error_msg}
except Exception as e:
logger.bind(tag=TAG).error(f"请求异常 [{method} {endpoint}]: {e}")
return {"success": False, "error": str(e)}
async def save_memory(self, msgs, context=None): async def save_memory(self, msgs, context=None):
if not self.use_memu: if not self.use_memu:
@ -157,3 +218,47 @@ class MemoryProvider(MemoryProviderBase):
logger.bind(tag=TAG).error(f"查询记忆失败: {str(e)}") logger.bind(tag=TAG).error(f"查询记忆失败: {str(e)}")
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
return "" return ""
# ==================== Memory Item CRUD ====================
@require_memu
def create_memory_item(self, memory_type: str, summary: str) -> Dict[str, Any]:
"""创建单条记忆记录
Args:
memory_type: 记忆类型
summary: 记忆摘要内容
"""
payload = self._base_payload(memory_type=memory_type, summary=summary)
return self._request("POST", "/memory-items", payload=payload)
@require_memu
def update_memory_item(self, memory_item_id: str, summary: str) -> Dict[str, Any]:
"""修改单条记忆记录
Args:
memory_item_id: 记忆记录 ID
summary: 新的摘要内容
"""
payload = self._base_payload(summary=summary)
return self._request("PUT", f"/memory-items/{memory_item_id}", payload=payload)
@require_memu
def delete_memory_item(self, memory_item_id: str) -> Dict[str, Any]:
"""删除单条记忆记录
Args:
memory_item_id: 记忆记录 ID
"""
params = {"user_id": self.role_id, "agent_id": self.agent_id}
return self._request("DELETE", f"/memory-items/{memory_item_id}", params=params)
@require_memu
def search_memory_items(self, summary: str) -> Dict[str, Any]:
"""查询记忆记录
Args:
summary: 搜索关键词
"""
payload = self._base_payload(summary=summary)
return self._request("POST", "/memory-items/search", payload=payload)

View file

@ -0,0 +1,427 @@
"""
Fish Audio Dual Stream TTS Implementation
Based on native WebSocket API (wss://api.fish.audio/v1/tts/live), supporting:
1. Pre-connection optimization: establish WebSocket connection before LLM output
2. Session lifecycle management: start/stop events for each dialogue round
3. FlushEvent + Chunk strategy: force audio generation at punctuation marks
4. Lightweight interruption: send stop event without closing connection
Reference: https://docs.fish.audio/api-reference/endpoint/websocket/tts-live
"""
import os
import uuid
import queue
import asyncio
import traceback
import ormsgpack
import websockets
from core.utils.tts import MarkdownCleaner
from core.utils import opus_encoder_utils
from core.utils.util import check_model_key
from core.providers.tts.base import TTSProviderBase
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
# Fish Audio WebSocket API endpoint
FISH_WS_URL = "wss://api.fish.audio/v1/tts/live"
class TTSProvider(TTSProviderBase):
"""Fish Audio Dual Stream TTS Implementation using native WebSocket API"""
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
# Mark as dual stream interface
self.interface_type = InterfaceType.DUAL_STREAM
# Fish Audio configuration
self.api_key = config.get("api_key")
if not self.api_key:
raise ValueError("Fish Audio API key is required")
self.model = config.get("model", "s1")
self.reference_id = config.get("reference_id")
self.format = config.get("response_format", "pcm")
self.sample_rate = int(config.get("sample_rate", 16000))
self.audio_file_type = self.format
self.latency_mode = config.get("latency_mode", "balanced")
self.chunk_length = int(config.get("chunk_length", 200))
self.top_p = float(config.get("top_p", 0.7))
self.temperature = float(config.get("temperature", 0.7))
self.normalize = str(config.get("normalize", True)).lower() in (
"true", "1", "yes"
)
# WebSocket connection state
self.ws = None
self._ws_connected = False
self._session_active = False
self._monitor_task = None
# Opus encoder (PCM -> Opus)
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
sample_rate=self.sample_rate, channels=1, frame_size_ms=60
)
# Text buffer for current session (supports both LLM and voice_opening/closing)
self._session_text_buffer = []
self._first_sent = False
# Check API Key
model_key_msg = check_model_key("TTS", self.api_key)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
async def open_audio_channels(self, conn):
"""
Override: establish WebSocket pre-connection
Connect to Fish Audio WebSocket before LLM starts generating,
reducing connection delay for the first TTS request.
"""
try:
await super().open_audio_channels(conn)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to open audio channels: {str(e)}")
self.ws = None
self._ws_connected = False
raise
async def _ensure_connection(self):
"""Ensure WebSocket connection is established"""
if self.ws and self._ws_connected:
logger.bind(tag=TAG).debug("Using existing WebSocket connection")
return
logger.bind(tag=TAG).info("Establishing new WebSocket connection...")
headers = {
"Authorization": f"Bearer {self.api_key}",
"model": self.model,
}
self.ws = await websockets.connect(
FISH_WS_URL,
additional_headers=headers,
max_size=10 * 1024 * 1024, # 10MB max message size
)
self._ws_connected = True
# Start response monitor task
if self._monitor_task is None or self._monitor_task.done():
logger.bind(tag=TAG).info("Starting WebSocket monitor task...")
self._monitor_task = asyncio.create_task(self._monitor_ws_response())
def tts_text_priority_thread(self):
"""
Override: dual stream TTS text processing thread
Manages session lifecycle based on FIRST/LAST signals,
similar to Huoshan's implementation.
"""
while not self.conn.stop_event.is_set():
try:
message = self.tts_text_queue.get(timeout=1)
logger.bind(tag=TAG).debug(
f"Received TTS task | {message.sentence_type.name} | {message.content_type.name}"
)
if message.sentence_type == SentenceType.FIRST:
# ========== New dialogue round starts ==========
self.conn.client_abort = False
elif self.conn.client_abort:
# ========== Interruption ==========
logger.bind(tag=TAG).info("Received interruption, canceling session")
try:
future = asyncio.run_coroutine_threadsafe(
self._finish_session(self.conn.sentence_id),
self.conn.loop
)
future.result()
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to cancel session: {e}")
continue
# when user doesn't trigger interruption, start new TTS session
if message.sentence_type == SentenceType.FIRST:
# Start new TTS session
try:
future = asyncio.run_coroutine_threadsafe(
self._start_session(),
self.conn.loop
)
future.result()
self.before_stop_play_files.clear()
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to start session: {e}")
continue
elif ContentType.TEXT == message.content_type:
# ========== Text content ==========
if message.content_detail:
# 累积文本用于上报(支持 voice_opening/closing 和 LLM 生成内容)
self._session_text_buffer.append(message.content_detail)
try:
logger.bind(tag=TAG).debug(
f"Sending TTS text: {message.content_detail}"
)
future = asyncio.run_coroutine_threadsafe(
self.text_to_speak(message.content_detail, None),
loop=self.conn.loop,
)
future.result()
logger.bind(tag=TAG).debug("TTS text sent successfully")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to send TTS text: {e}")
continue
elif ContentType.FILE == message.content_type:
# ========== File content ==========
logger.bind(tag=TAG).info(
f"Adding audio file to playback list: {message.content_file}"
)
if message.content_file and os.path.exists(message.content_file):
# Process file audio data first
self._process_audio_file_stream(message.content_file, callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail))
if message.sentence_type == SentenceType.LAST:
# ========== Dialogue round ends ==========
try:
future = asyncio.run_coroutine_threadsafe(
self._finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
future.result()
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to finish session: {e}")
continue
except queue.Empty:
continue
except Exception as e:
logger.bind(tag=TAG).error(
f"TTS text processing failed: {str(e)}, type: {type(e).__name__}, "
f"stack: {traceback.format_exc()}"
)
continue
async def close(self):
"""Clean up WebSocket resources"""
self._session_active = False
self._ws_connected = False
# Cancel monitor task
if self._monitor_task:
try:
self._monitor_task.cancel()
await self._monitor_task
except asyncio.CancelledError:
pass
except Exception as e:
logger.bind(tag=TAG).warning(f"Error canceling monitor task: {e}")
self._monitor_task = None
# Close WebSocket
if self.ws:
try:
await self.ws.close()
except:
pass
self.ws = None
self._ws_connected = False
await super().close()
async def _monitor_ws_response(self):
"""Monitor WebSocket responses - long running task (MessagePack serialization)"""
try:
while not self.conn.stop_event.is_set():
try:
if not self.ws:
break
msg = await self.ws.recv()
response = ormsgpack.unpackb(msg)
event_type = response.get("event")
if event_type == "audio":
# Received audio chunk (binary data)
audio_data = response.get("audio")
if audio_data and not self.conn.client_abort:
# 在第一个音频之前发送 FIRST(带当前累积的文本)
# 这样后续音频通过 MIDDLE 累积时,enqueue_audio 不会被清空
if not self._first_sent:
self._first_sent = True
report_text = ''.join(self._session_text_buffer) if self._session_text_buffer else None
self.tts_audio_queue.put((SentenceType.FIRST, None, report_text))
# PCM -> Opus conversion
self.opus_encoder.encode_pcm_to_opus_stream(
audio_data, end_of_stream=False, callback=self.handle_opus
)
elif event_type == "finish":
# Session completed
reason = response.get("reason", "unknown")
if reason == "error":
logger.bind(tag=TAG).error(f"TTS session error")
else:
logger.bind(tag=TAG).debug(f"TTS session finished")
# Flush remaining opus buffer
self.opus_encoder.encode_pcm_to_opus_stream(
b'', end_of_stream=True, callback=self.handle_opus
)
# 发送 LAST 触发客户端 stop 和最终上报
# 不再发送 FIRST,避免清空之前累积的音频
self.tts_audio_queue.put((SentenceType.LAST, None, None))
# 清理状态
self._session_text_buffer = []
self.conn.tts_MessageText = None
self._session_active = False
self._process_before_stop_play_files()
self.ws = None
self._ws_connected = False
self._first_sent = False
except websockets.ConnectionClosed:
logger.bind(tag=TAG).warning("WebSocket connection closed")
break
except Exception as e:
logger.bind(tag=TAG).error(f"Error in monitor task: {e}")
traceback.print_exc()
break
# Clean up on exit
if self.ws:
try:
await self.ws.close()
except:
pass
self.ws = None
self._ws_connected = False
finally:
self._monitor_task = None
async def _send_event(self, event: dict):
"""Send event to Fish Audio WebSocket using MessagePack serialization"""
if not self.ws or not self._ws_connected:
logger.bind(tag=TAG).warning("WebSocket not connected, cannot send event")
return
try:
bytes_event = ormsgpack.packb(event)
await self.ws.send(bytes_event)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to send event: {e}")
raise
async def _start_session(self):
"""
Start a new TTS session
"""
# Wait for previous session to finish
# Avoid the latency of the finish event of the previous session
if self._session_active:
for _ in range(3):
if not self._session_active:
break
logger.bind(tag=TAG).debug("Waiting for previous session to finish...")
await asyncio.sleep(0.1)
else:
logger.bind(tag=TAG).debug("Previous session timeout, clearing connection state...")
await self.close()
# Reset state for new session
self.opus_encoder.reset_state()
self._session_text_buffer = []
self._first_sent = False
self.conn.sentence_id = uuid.uuid4().hex
try:
# Ensure connection
await self._ensure_connection()
# Send start event
start_event = {
"event": "start",
"request": {
"text": "",
"format": self.format,
"sample_rate": self.sample_rate,
"chunk_length": self.chunk_length,
"latency": self.latency_mode,
"normalize": self.normalize,
"top_p": self.top_p,
"temperature": self.temperature,
}
}
if self.reference_id:
start_event["request"]["reference_id"] = self.reference_id
await self._send_event(start_event)
self._session_active = True
logger.bind(tag=TAG).info(f"TTS session started, sentence_id: {self.conn.sentence_id}")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to start session: {e}")
raise
async def _finish_session(self, session_id: str = None):
"""
Finish current TTS session gracefully
"""
logger.bind(tag=TAG).info(f"Finishing TTS session: {session_id}")
try:
if self.ws and self._session_active:
stop_event = {"event": "stop"}
await self._send_event(stop_event)
logger.bind(tag=TAG).info("TTS session stop sent")
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to finish session: {e}")
finally:
self._session_active = False
self.conn.sentence_id = None
async def text_to_speak(self, text, output_file):
"""
streaming TTS text to Fish Audio WebSocket
"""
logger.bind(tag=TAG).debug(f"Fish Audio TTS: {text}")
try:
if self.ws is None:
logger.bind(tag=TAG).warning("WebSocket not connected, cannot send text")
return
filtered_text = MarkdownCleaner.clean_markdown(text)
# Send text
text_event = {"event": "text", "text": filtered_text}
await self._send_event(text_event)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to send text: {e}")
if self.ws:
try:
await self.ws.close()
except:
pass
self.ws = None
self._ws_connected = False
raise

View file

@ -1,64 +1,13 @@
import base64
from pathlib import Path from pathlib import Path
from pydantic import BaseModel, Field, conint, model_validator
from typing_extensions import Annotated
from typing import Literal
from core.utils.util import parse_string_to_list from core.utils.util import parse_string_to_list
from core.providers.tts.base import TTSProviderBase from core.providers.tts.base import TTSProviderBase
from config.logger import setup_logging from config.logger import setup_logging
from fish_audio_sdk import Session, TTSRequest, ReferenceAudio from fishaudio import FishAudio, TTSConfig
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
class ServeReferenceAudio(BaseModel):
audio: bytes
text: str
@model_validator(mode="before")
def decode_audio(cls, values):
audio = values.get("audio")
if (
isinstance(audio, str) and len(audio) > 255
): # Check if audio is a string (Base64)
try:
values["audio"] = base64.b64decode(audio)
except Exception as e:
# If the audio is not a valid base64 string, we will just ignore it and let the server handle it
pass
return values
def __repr__(self) -> str:
return f"ServeReferenceAudio(text={self.text!r}, audio_size={len(self.audio)})"
class ServeTTSRequest(BaseModel):
text: str
chunk_length: Annotated[int, conint(ge=100, le=300, strict=True)] = 200
# Audio format
format: Literal["wav", "pcm", "mp3"] = "wav"
# References audios for in-context learning
references: list[ServeReferenceAudio] = []
# Reference id
# For example, if you want use https://fish.audio/m/7f92f8afb8ec43bf81429cc1c9199cb1/
# Just pass 7f92f8afb8ec43bf81429cc1c9199cb1
reference_id: str | None = None
seed: int | None = None
use_memory_cache: Literal["on", "off"] = "off"
# Normalize text for en & zh, this increase stability for numbers
normalize: bool = True
# not usually used below
streaming: bool = False
max_new_tokens: int = 1024
top_p: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7
repetition_penalty: Annotated[float, Field(ge=0.9, le=2.0, strict=True)] = 1.2
temperature: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7
class Config:
# Allow arbitrary types for pytorch related types
arbitrary_types_allowed = True
def audio_to_bytes(file_path): def audio_to_bytes(file_path):
if not file_path or not Path(file_path).exists(): if not file_path or not Path(file_path).exists():
@ -82,12 +31,6 @@ class TTSProvider(TTSProviderBase):
super().__init__(config, delete_audio_file) super().__init__(config, delete_audio_file)
self.model = config.get("model", "s1") 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("reference_id"): if config.get("reference_id"):
self.reference_id = config.get("reference_id") self.reference_id = config.get("reference_id")
else: else:
@ -104,7 +47,7 @@ class TTSProvider(TTSProviderBase):
self.api_key = config.get("api_key", "YOUR_API_KEY") self.api_key = config.get("api_key", "YOUR_API_KEY")
if self.api_key is None: if self.api_key is None:
raise ValueError("FishSpeech API key is required") raise ValueError("FishSpeech API key is required")
self.session = Session(self.api_key) self._client = FishAudio(api_key=self.api_key)
self.normalize = str(config.get("normalize", True)).lower() in ( self.normalize = str(config.get("normalize", True)).lower() in (
"true", "true",
@ -143,22 +86,26 @@ class TTSProvider(TTSProviderBase):
self.seed = int(config.get("seed")) if config.get("seed") else None self.seed = int(config.get("seed")) if config.get("seed") else None
async def text_to_speak(self, text, output_file): async def text_to_speak(self, text, output_file):
logger.bind(tag=TAG).info(f"[DEBUG] 原始文本: {repr(text)}")
logger.bind(tag=TAG).info(f"fish speech synthesize text: {text}") logger.bind(tag=TAG).info(f"fish speech synthesize text: {text}")
# Prepare reference data
byte_audios = [audio_to_bytes(ref_audio) for ref_audio in self.reference_audio]
ref_texts = [read_ref_text(ref_text) for ref_text in self.reference_text]
request = TTSRequest( audio_stream = self._client.tts.stream(
text=text, text=text,
reference_id=self.reference_id, reference_id=self.reference_id,
sample_rate=self.sample_rate, model=self.model,
format=self.format, config=TTSConfig(
normalize=True, format=self.format,
sample_rate=self.sample_rate,
normalize=self.normalize,
latency="balanced",
),
) )
audio_stream = self.session.tts(request, backend="s1")
audio_bytes = b''.join(chunk for chunk in audio_stream if chunk)
audio_bytes = b''
for chunk in audio_stream:
if chunk:
audio_bytes += chunk
if output_file: if output_file:
with open(output_file, "wb") as audio_file: with open(output_file, "wb") as audio_file:
audio_file.write(audio_bytes) audio_file.write(audio_bytes)

View file

@ -767,6 +767,7 @@ TTS:
FishSpeech: FishSpeech:
# 参照教程:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/fish-speech-integration.md # 参照教程:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/fish-speech-integration.md
type: fishspeech type: fishspeech
model: s1
output_dir: tmp/ output_dir: tmp/
response_format: pcm response_format: pcm
reference_id: null reference_id: null
@ -783,6 +784,19 @@ TTS:
rate: 44100 rate: 44100
sample_rate: 16000 sample_rate: 16000
api_key: ${FISH_API_KEY} api_key: ${FISH_API_KEY}
FishDualStreamTTS:
type: fish_dual_stream
model: s1
output_dir: tmp/
response_format: pcm
normalize: true
chunk_length: 200
top_p: 0.7
temperature: 0.7
channels: 1
rate: 44100
sample_rate: 16000
api_key: ${FISH_API_KEY}
GPT_SOVITS_V2: GPT_SOVITS_V2:
# 定义TTS API类型 # 定义TTS API类型
#启动tts方法: #启动tts方法:
@ -1072,6 +1086,8 @@ selected_module:
ASR: GroqASR ASR: GroqASR
LLM: OpenaiLLM LLM: OpenaiLLM
VLLM: ChatGLMVLLM VLLM: ChatGLMVLLM
# TTS: FishDualStreamTTS
# TODO: temporarily, fish speech doesn't reuse the wesocket connection, need to discuss further.
TTS: FishSpeech TTS: FishSpeech
Memory: memu Memory: memu
Intent: function_call Intent: function_call

View file

@ -43,6 +43,6 @@ redis>=4.0.0,<5.0.0
elevenlabs>=1.11.0 elevenlabs>=1.11.0
cartesia>=1.0.0 cartesia>=1.0.0
deepgram-sdk>=3.0.0 deepgram-sdk>=3.0.0
fish-audio-sdk==2025.6.3 fish-audio-sdk>=1.0.0
python-dotenv>=1.0.0 python-dotenv>=1.0.0

View file

@ -0,0 +1,2 @@
/reports/
/tmp/

View file

@ -0,0 +1,787 @@
#!/usr/bin/env python3
"""
Fish Speech Emotion Tag Test
This script tests whether Fish Speech TTS correctly handles emotion tags:
- Emotion tags like (happy), (sad) should NOT be read aloud
- Only the actual text content should be spoken
Method:
1. Generate TTS audio with emotion-tagged text
2. Transcribe the audio using Groq Whisper ASR
3. Compare transcript with expected text (without emotion tag)
4. Report whether the emotion tag was incorrectly read aloud
Usage:
python3 test_emotion_tag.py
# With API keys
FISH_API_KEY="your-fish-key" GROQ_API_KEY="your-groq-key" python3 test_emotion_tag.py
# With custom voice
FISH_REFERENCE_ID="voice-id" python3 test_emotion_tag.py
Requirements:
pip install fish-audio-sdk openai
"""
import os
import sys
import io
import wave
import asyncio
import tempfile
import argparse
from datetime import datetime
from dataclasses import dataclass, field
# Check for required packages
try:
from fishaudio import AsyncFishAudio
from fishaudio.types.tts import TTSConfig
except ImportError:
print("❌ Missing fish-audio-sdk. Install with:")
print(" pip install fish-audio-sdk")
sys.exit(1)
try:
from openai import OpenAI
except ImportError:
print("❌ Missing openai. Install with:")
print(" pip install openai")
sys.exit(1)
# All emotion tags from role.md
EMOTION_TAGS = [
"happy", "satisfied", "relaxed", "amused", "sincere", "conciliative",
"calm", "confident", "curious", "keen", "confused", "worried",
"frustrated", "sad", "unhappy", "impatient", "negative", "disapproving",
"disdainful", "scornful", "sarcastic", "surprised"
]
# Voice reference IDs for different languages
VOICE_REFERENCES = {
"zh": "aebaa2305aa2452fbdc8f41eec852a79",
"en": "e58b0d7efca34eb38d5c4985e378abcb",
}
# Test texts in different languages (20 sentences each)
TEST_TEXTS = {
"zh": [
"今天天气真好",
"我很高兴认识你",
"这个问题有点复杂",
"让我想一想",
"你说得对",
"我明白你的意思了",
"这件事情很重要",
"我们一起努力吧",
"谢谢你的帮助",
"请稍等一下",
"我有一个想法",
"这真是太棒了",
"我需要更多时间",
"你觉得怎么样",
"让我们开始吧",
"我不太确定",
"这是个好主意",
"我会尽力的",
"请告诉我更多",
"我们来看看",
],
"en": [
"The weather is nice today",
"Nice to meet you",
"This is a bit complicated",
"Let me think about it",
"You are right",
"I understand what you mean",
"This is very important",
"Let us work together",
"Thank you for your help",
"Please wait a moment",
"I have an idea",
"This is amazing",
"I need more time",
"What do you think",
"Let us get started",
"I am not sure",
"That is a good idea",
"I will do my best",
"Please tell me more",
"Let us take a look",
],
}
# Default: test all emotion tags
DEFAULT_TEST_EMOTIONS = EMOTION_TAGS
@dataclass
class TestCase:
"""Single test case configuration"""
emotion: str
text: str
lang: str
input_text: str = field(init=False)
def __post_init__(self):
self.input_text = f"({self.emotion}) {self.text}"
if self.lang == "en":
self.input_text += "."
else:
self.input_text += "。"
@dataclass
class TestResult:
"""Single test result"""
test_case: TestCase
transcript: str
tag_leaked: bool # True if emotion tag was read aloud
text_match: bool # True if transcript matches expected text
audio_duration_ms: float
success: bool
error: str = ""
audio_file: str = "" # Path to saved audio file (for failed cases)
@dataclass
class TestConfig:
"""Test configuration"""
api_key: str
groq_api_key: str
voice_references: dict # {lang: reference_id}
sample_rate: int = 16000
format: str = "pcm"
whisper_model: str = "whisper-large-v3" # Groq whisper model
emotions: list = field(default_factory=lambda: DEFAULT_TEST_EMOTIONS)
languages: list = field(default_factory=lambda: ["zh", "en"])
def get_reference_id(self, lang: str) -> str:
"""Get voice reference ID for a specific language"""
return self.voice_references.get(lang, "")
class EmotionTagTester:
"""Emotion tag testing class"""
# Groq API base URL (OpenAI compatible)
GROQ_BASE_URL = "https://api.groq.com/openai/v1"
def __init__(self, config: TestConfig):
self.config = config
self.client = AsyncFishAudio(api_key=config.api_key)
self.groq_client = OpenAI(
api_key=config.groq_api_key,
base_url=self.GROQ_BASE_URL
)
# Create tmp directory for failed audio files
self.tmp_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp")
os.makedirs(self.tmp_dir, exist_ok=True)
def _pcm_to_wav(self, pcm_data: bytes) -> bytes:
"""Convert PCM to WAV format for ASR"""
wav_buffer = io.BytesIO()
with wave.open(wav_buffer, 'wb') as wav_file:
wav_file.setnchannels(1)
wav_file.setsampwidth(2) # 16-bit
wav_file.setframerate(self.config.sample_rate)
wav_file.writeframes(pcm_data)
return wav_buffer.getvalue()
def _save_failed_audio(self, test_case: TestCase, audio_data: bytes) -> str:
"""Save failed audio to tmp directory"""
# Generate filename: {emotion}_{lang}_{text_hash}.wav
text_hash = hash(test_case.text) & 0xFFFFFF # 6 hex chars
filename = f"{test_case.emotion}_{test_case.lang}_{text_hash:06x}.wav"
filepath = os.path.join(self.tmp_dir, filename)
wav_data = self._pcm_to_wav(audio_data)
with open(filepath, "wb") as f:
f.write(wav_data)
return filepath
def _transcribe(self, audio_data: bytes, lang: str) -> str:
"""Transcribe audio using Groq Whisper API"""
# Save to temp file (API needs file)
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
wav_data = self._pcm_to_wav(audio_data)
f.write(wav_data)
temp_path = f.name
try:
with open(temp_path, "rb") as audio_file:
response = self.groq_client.audio.transcriptions.create(
model=self.config.whisper_model,
file=audio_file,
language=lang if lang != "zh" else "zh",
)
return response.text.strip()
finally:
os.unlink(temp_path)
def _normalize_text(self, text: str) -> str:
"""Normalize text for comparison"""
# Remove punctuation and convert to lowercase
import re
text = re.sub(r'[^\w\s]', '', text)
return text.lower().strip()
def _check_tag_leaked(self, transcript: str, emotion: str) -> bool:
"""Check if emotion tag was read aloud"""
normalized = self._normalize_text(transcript)
emotion_lower = emotion.lower()
# Check for exact emotion word
if emotion_lower in normalized.split():
return True
# Check for common mispronunciations/variations
variations = {
"happy": ["happy", "hapi", "happie"],
"sad": ["sad", "sæd"],
"calm": ["calm", "kam", "come"],
"surprised": ["surprised", "surprise"],
"curious": ["curious", "curios"],
"worried": ["worried", "worry"],
"frustrated": ["frustrated", "frustrate"],
"confident": ["confident", "confidence"],
"sincere": ["sincere", "sincer"],
"sarcastic": ["sarcastic", "sarcasm"],
}
for var in variations.get(emotion_lower, [emotion_lower]):
if var in normalized:
return True
return False
def _check_text_match(self, transcript: str, expected: str) -> bool:
"""Check if transcript matches expected text (fuzzy)"""
norm_transcript = self._normalize_text(transcript)
norm_expected = self._normalize_text(expected)
# Simple word overlap ratio
transcript_words = set(norm_transcript.split())
expected_words = set(norm_expected.split())
if not expected_words:
return True
overlap = len(transcript_words & expected_words)
ratio = overlap / len(expected_words)
return ratio >= 0.5 # At least 50% word match
async def run_test(self, test_case: TestCase) -> TestResult:
"""Run a single test case"""
try:
tts_config = TTSConfig(
format=self.config.format,
model="s1",
sample_rate=self.config.sample_rate,
normalize=True,
latency="balanced",
)
# Get voice reference ID for this language
reference_id = self.config.get_reference_id(test_case.lang)
if not reference_id:
return TestResult(
test_case=test_case,
transcript="",
tag_leaked=False,
text_match=False,
audio_duration_ms=0,
success=False,
error=f"No voice reference ID configured for language: {test_case.lang}"
)
# Generate TTS audio
audio_data = b''
audio_stream = await self.client.tts.stream(
text=test_case.input_text,
reference_id=reference_id,
model="s1",
config=tts_config,
)
async for chunk in audio_stream:
if chunk:
audio_data += chunk
if not audio_data:
return TestResult(
test_case=test_case,
transcript="",
tag_leaked=False,
text_match=False,
audio_duration_ms=0,
success=False,
error="No audio data received"
)
# Calculate audio duration
audio_duration_ms = len(audio_data) / (self.config.sample_rate * 2) * 1000
# Transcribe
transcript = self._transcribe(audio_data, test_case.lang)
# Check results
tag_leaked = self._check_tag_leaked(transcript, test_case.emotion)
text_match = self._check_text_match(transcript, test_case.text)
# Save audio if tag leaked
audio_file = ""
if tag_leaked:
audio_file = self._save_failed_audio(test_case, audio_data)
return TestResult(
test_case=test_case,
transcript=transcript,
tag_leaked=tag_leaked,
text_match=text_match,
audio_duration_ms=audio_duration_ms,
success=True,
audio_file=audio_file
)
except Exception as e:
return TestResult(
test_case=test_case,
transcript="",
tag_leaked=False,
text_match=False,
audio_duration_ms=0,
success=False,
error=str(e)
)
async def run_all_tests(self) -> list[TestResult]:
"""Run all test cases"""
results = []
# Generate test cases: organized by language -> emotion -> texts
test_cases = []
for lang in self.config.languages:
texts = TEST_TEXTS.get(lang, [])
for emotion in self.config.emotions:
for text in texts:
test_cases.append(TestCase(emotion=emotion, text=text, lang=lang))
total = len(test_cases)
num_emotions = len(self.config.emotions)
num_texts = len(TEST_TEXTS.get(self.config.languages[0], []))
print(f"\n🧪 Test Plan:")
print(f" Languages: {self.config.languages}")
print(f" Emotion Tags: {num_emotions}")
print(f" Sentences per Tag: {num_texts}")
print(f" Total Test Cases: {total}")
leaked_count = 0
current_lang = None
current_emotion = None
for i, tc in enumerate(test_cases, 1):
# Print progress header when language or emotion changes
if tc.lang != current_lang:
current_lang = tc.lang
print(f"\n{'='*60}")
print(f"📍 Language: {current_lang.upper()}")
print(f"{'='*60}")
if tc.emotion != current_emotion:
current_emotion = tc.emotion
print(f"\n🏷️ Testing emotion: {current_emotion}")
# Run test
result = await self.run_test(tc)
results.append(result)
# Compact progress output
if result.success:
if result.tag_leaked:
leaked_count += 1
print(f" ❌ [{i}/{total}] LEAKED: \"{tc.text[:20]}...\" → \"{result.transcript[:30]}...\"")
if result.audio_file:
print(f" 📁 Saved: {os.path.basename(result.audio_file)}")
else:
# Only show dot for success to keep output clean
print(f" ✓ [{i}/{total}] OK", end="\r")
else:
print(f" ⚠️ [{i}/{total}] ERROR: {result.error[:50]}")
# Small delay between requests
await asyncio.sleep(0.2)
# Final summary
print(f"\n\n{'='*60}")
print(f"📊 Test Complete: {total} tests, {leaked_count} leaks")
print(f"{'='*60}")
return results
def generate_report(results: list[TestResult], config: TestConfig) -> str:
"""Generate markdown report"""
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Statistics
total = len(results)
successful = sum(1 for r in results if r.success)
leaked = sum(1 for r in results if r.success and r.tag_leaked)
matched = sum(1 for r in results if r.success and r.text_match)
# Build voice references string
voice_refs_str = ", ".join([f"{lang.upper()}: `{config.voice_references.get(lang, 'N/A')}`" for lang in config.languages])
# Calculate sentences per tag
num_sentences = len(TEST_TEXTS.get(config.languages[0], []))
report = f"""# Fish Speech Emotion Tag Test Report
**Generated:** {now}
**Voice References:** {voice_refs_str}
**ASR Model:** Groq {config.whisper_model}
**Languages:** {', '.join(config.languages)}
**Emotion Tags:** {len(config.emotions)}
**Sentences per Tag:** {num_sentences}
**Total Tests:** {total}
---
## Summary
| Metric | Count | Percentage |
|--------|-------|------------|
| Total Tests | {total} | 100% |
| Successful | {successful} | {successful/total*100:.1f}% |
| **Tag Leaked** | **{leaked}** | **{leaked/successful*100:.1f}%** |
| Text Matched | {matched} | {matched/successful*100:.1f}% |
### Interpretation
- **Tag Leaked = 0**: ✅ Fish Speech correctly handles emotion tags (not read aloud)
- **Tag Leaked > 0**: ⚠️ Fish Speech may be reading emotion tags as text
---
## Leak Rate by Emotion Tag & Language
This is the main summary table showing leak rate for each emotion tag across languages.
"""
# Build main summary table: Emotion x Language
report += "| Emotion Tag |"
for lang in config.languages:
report += f" {lang.upper()} |"
report += " Overall |\n"
report += "|-------------|"
for _ in config.languages:
report += "--------|"
report += "---------|\n"
for emotion in config.emotions:
report += f"| {emotion} |"
total_leaked = 0
total_count = 0
for lang in config.languages:
lang_emo_results = [
r for r in results
if r.test_case.emotion == emotion
and r.test_case.lang == lang
and r.success
]
lang_leaked = sum(1 for r in lang_emo_results if r.tag_leaked)
lang_count = len(lang_emo_results)
total_leaked += lang_leaked
total_count += lang_count
if lang_count > 0:
rate = lang_leaked / lang_count * 100
status = "✅" if lang_leaked == 0 else "⚠️"
report += f" {lang_leaked}/{lang_count} ({rate:.0f}%) {status} |"
else:
report += " N/A |"
# Overall for this emotion
if total_count > 0:
overall_rate = total_leaked / total_count * 100
overall_status = "✅" if total_leaked == 0 else "⚠️"
report += f" {total_leaked}/{total_count} ({overall_rate:.0f}%) {overall_status} |\n"
else:
report += " N/A |\n"
# Language summary row
report += "| **Total** |"
grand_total_leaked = 0
grand_total_count = 0
for lang in config.languages:
lang_results = [r for r in results if r.test_case.lang == lang and r.success]
lang_leaked = sum(1 for r in lang_results if r.tag_leaked)
lang_count = len(lang_results)
grand_total_leaked += lang_leaked
grand_total_count += lang_count
if lang_count > 0:
rate = lang_leaked / lang_count * 100
report += f" **{lang_leaked}/{lang_count} ({rate:.0f}%)** |"
else:
report += " N/A |"
if grand_total_count > 0:
overall_rate = grand_total_leaked / grand_total_count * 100
report += f" **{grand_total_leaked}/{grand_total_count} ({overall_rate:.0f}%)** |\n"
else:
report += " N/A |\n"
report += "\n---\n\n"
# Detailed failures
failures = [r for r in results if r.success and r.tag_leaked]
if failures:
report += "## ⚠️ Failed Cases (Tag Leaked)\n\n"
report += "Audio files saved in `tmp/` directory.\n\n"
# Group by emotion
from collections import defaultdict
failures_by_emotion = defaultdict(list)
for r in failures:
failures_by_emotion[r.test_case.emotion].append(r)
for emotion in sorted(failures_by_emotion.keys()):
report += f"### {emotion}\n\n"
report += "| Language | Input Text | Transcript | Audio File |\n"
report += "|----------|------------|------------|------------|\n"
for r in failures_by_emotion[emotion]:
input_short = r.test_case.input_text[:40] + "..." if len(r.test_case.input_text) > 40 else r.test_case.input_text
trans_short = r.transcript[:40] + "..." if len(r.transcript) > 40 else r.transcript
audio_name = os.path.basename(r.audio_file) if r.audio_file else "N/A"
report += f"| {r.test_case.lang.upper()} | {input_short} | {trans_short} | `{audio_name}` |\n"
report += "\n"
# Errors
errors = [r for r in results if not r.success]
if errors:
report += "---\n\n## Errors\n\n"
for r in errors:
report += f"- [{r.test_case.lang.upper()}] {r.test_case.emotion}: {r.error}\n"
report += "\n"
report += """---
## Conclusion
"""
if leaked == 0:
report += "✅ **All emotion tags were correctly handled** - Fish Speech does not read emotion tags aloud.\n"
else:
leak_rate = leaked / successful * 100 if successful > 0 else 0
report += f"⚠️ **{leaked} out of {successful} tests had tag leaks ({leak_rate:.1f}%)**\n\n"
# Find problematic emotions
problematic = []
for emotion in config.emotions:
emo_results = [r for r in results if r.test_case.emotion == emotion and r.success]
emo_leaked = sum(1 for r in emo_results if r.tag_leaked)
if emo_leaked > 0:
rate = emo_leaked / len(emo_results) * 100
problematic.append((emotion, rate))
if problematic:
problematic.sort(key=lambda x: -x[1])
report += "**Most problematic emotion tags:**\n"
for emotion, rate in problematic[:5]:
report += f"- `{emotion}`: {rate:.0f}% leak rate\n"
report += "\n---\n\n*Generated by Fish Speech Emotion Tag Tester*\n"
return report
def parse_args():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(
description="Fish Speech Emotion Tag Test - Test if emotion tags are correctly handled",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Test a single emotion tag
python test_emotion_tag.py --tag happy
# Test multiple tags
python test_emotion_tag.py --tag happy --tag sad --tag calm
# Run all tests
python test_emotion_tag.py
# List all available emotion tags
python test_emotion_tag.py --list-tags
Environment Variables:
FISH_API_KEY Fish Audio API key (required)
GROQ_API_KEY Groq API key for ASR (required)
"""
)
parser.add_argument(
"--tag", "-t",
action="append",
dest="tags",
metavar="EMOTION",
help="Emotion tag(s) to test (can be specified multiple times). Default: all tags"
)
parser.add_argument(
"--list-tags",
action="store_true",
help="List all available emotion tags and exit"
)
return parser.parse_args()
async def main():
args = parse_args()
# Handle --list-tags
if args.list_tags:
print("Available emotion tags:")
for i, tag in enumerate(EMOTION_TAGS, 1):
print(f" {i:2}. {tag}")
print(f"\nTotal: {len(EMOTION_TAGS)} tags")
sys.exit(0)
print("🏷️ Fish Speech Emotion Tag Test")
print("=" * 50)
# Get configuration from environment
api_key = os.environ.get("FISH_API_KEY")
if not api_key:
print("\n❌ Error: FISH_API_KEY not set")
print(" export FISH_API_KEY='your-key'")
print("\n💡 Get your API key from: https://fish.audio/")
sys.exit(1)
groq_api_key = os.environ.get("GROQ_API_KEY")
if not groq_api_key:
print("\n❌ Error: GROQ_API_KEY not set")
print(" export GROQ_API_KEY='your-key'")
print("\n💡 Get your API key from: https://console.groq.com/")
sys.exit(1)
# Voice references from fixed config
voice_references = VOICE_REFERENCES.copy()
whisper_model = "whisper-large-v3"
# Emotions: CLI --tag or all
if args.tags:
# Validate tags
invalid_tags = [t for t in args.tags if t not in EMOTION_TAGS]
if invalid_tags:
print(f"\n❌ Invalid emotion tag(s): {invalid_tags}")
print(f" Use --list-tags to see available tags")
sys.exit(1)
emotions = args.tags
else:
emotions = DEFAULT_TEST_EMOTIONS
# Languages: always test both
languages = ["zh", "en"]
# Calculate sentence count
all_texts = TEST_TEXTS.get(languages[0], [])
num_sentences = len(all_texts)
# Validate voice references for selected languages
missing_voices = [lang for lang in languages if not voice_references.get(lang)]
if missing_voices:
print(f"\n❌ Error: Missing voice reference ID for language(s): {missing_voices}")
print(" Please configure VOICE_REFERENCES in test_emotion_tag.py")
sys.exit(1)
config = TestConfig(
api_key=api_key,
groq_api_key=groq_api_key,
voice_references=voice_references,
whisper_model=whisper_model,
emotions=emotions,
languages=languages,
)
print(f"\n📋 Configuration:")
print(f" Groq ASR Model: {whisper_model}")
print(f" Languages & Voices:")
for lang in languages:
ref_id = voice_references.get(lang, "N/A")
print(f" {lang.upper()}: {ref_id}")
print(f" Emotion Tags: {len(emotions)} ({', '.join(emotions[:5])}{'...' if len(emotions) > 5 else ''})")
print(f" Sentences per Tag: {num_sentences}")
print(f" Estimated Tests: {len(emotions) * len(languages) * num_sentences}")
# Run tests
tester = EmotionTagTester(config)
results = await tester.run_all_tests()
# Generate report
print("\n" + "=" * 50)
print("📊 Generating Report...")
print("=" * 50)
report = generate_report(results, config)
# Save report
script_dir = os.path.dirname(os.path.abspath(__file__))
reports_dir = os.path.join(script_dir, "reports")
os.makedirs(reports_dir, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
report_file = os.path.join(reports_dir, f"emotion_tag_report_{timestamp}.md")
with open(report_file, "w", encoding="utf-8") as f:
f.write(report)
print(f"\n✅ Report saved to: {report_file}")
# Print summary
print("\n" + "=" * 50)
print("📈 Quick Summary")
print("=" * 50)
total = len(results)
successful = sum(1 for r in results if r.success)
leaked = sum(1 for r in results if r.success and r.tag_leaked)
saved_audio = sum(1 for r in results if r.audio_file)
print(f"\n Total Tests: {total}")
print(f" Successful: {successful}")
print(f" Tag Leaked: {leaked}")
if leaked == 0:
print("\n✅ All emotion tags handled correctly!")
else:
print(f"\n⚠️ {leaked} emotion tags were incorrectly read aloud!")
if saved_audio > 0:
print(f"📁 {saved_audio} audio files saved to: {tester.tmp_dir}")
print("\n✅ Test completed!")
if __name__ == "__main__":
asyncio.run(main())

View file

@ -0,0 +1,601 @@
#!/usr/bin/env python3
"""
Fish Speech TTS Latency Comparison: HTTP vs WebSocket
This script compares the latency of Fish Speech TTS using:
1. HTTP streaming (session.tts)
2. WebSocket streaming (client.tts.stream_websocket)
Usage:
python3 test_fish_latency.py
# With custom API key
FISH_API_KEY="your-key" python3 test_fish_latency.py
# With custom voice
FISH_REFERENCE_ID="voice-id" python3 test_fish_latency.py
Output:
- Generates a markdown report in ./reports/
- Prints summary to console
Requirements:
pip install fish-audio-sdk
"""
import os
import sys
import time
import asyncio
import statistics
from datetime import datetime
from dataclasses import dataclass
# Check for required package
try:
from fishaudio import AsyncFishAudio
from fishaudio.types.tts import TTSConfig, FlushEvent
except ImportError:
print("❌ Missing required packages. Install with:")
print(" pip install fish-audio-sdk")
sys.exit(1)
@dataclass
class LatencyResult:
"""Single test result"""
method: str
test_name: str
text_length: int
ttfb_ms: float # Time to first byte
total_ms: float # Total time
audio_bytes: int
success: bool
error: str = ""
@dataclass
class TestConfig:
"""Test configuration"""
api_key: str
reference_id: str
sample_rate: int = 16000
format: str = "pcm"
latency_mode: str = "balanced" # "balanced" or "normal"
runs_per_test: int = 3
# LLM simulation - tokens arrive with delays
# Realistic LLM output with punctuation for sentence segmentation
LLM_SIMULATION = {
"tokens": [
"好", "的", ",", "今", "天", "天", "气", "非", "常", "不", "错", "。",
"阳", "光", "明", "媚", ",", "温", "度", "适", "宜", ",", "非", "常",
"适", "合", "户", "外", "活", "动", "!", "你", "想", "去", "哪", "里", "玩", "呢", "?"
],
"delay_ms": 30, # Simulate ~30ms per token (typical LLM speed for Chinese)
}
# Punctuation sets for sentence segmentation (from base.py)
FIRST_SENTENCE_PUNCTUATIONS = [",", ","] # First sentence ends at comma
SENTENCE_PUNCTUATIONS = ["。", "!", "?", ";", ".", "!", "?", ";", "\n"] # Full sentence ends
MIN_FIRST_SEGMENT_CHARS = 8 # Minimum chars for first segment
class TextSegmenter:
"""
Simulates the text segmentation logic from base.py _get_segment_text()
Collects tokens and yields segments when punctuation is encountered.
"""
def __init__(self):
self.buffer = ""
self.is_first_sentence = True
def reset(self):
self.buffer = ""
self.is_first_sentence = True
def add_token(self, token: str) -> str | None:
"""
Add a token and return a segment if ready, otherwise None.
Mirrors the logic in base.py _get_segment_text()
"""
self.buffer += token
# Choose punctuation set based on whether it's the first sentence
punctuations = FIRST_SENTENCE_PUNCTUATIONS if self.is_first_sentence else SENTENCE_PUNCTUATIONS
# Find the last punctuation position
last_punct_pos = -1
for punct in punctuations:
pos = self.buffer.rfind(punct)
if pos != -1 and (last_punct_pos == -1 or pos < last_punct_pos):
last_punct_pos = pos
if last_punct_pos != -1:
segment = self.buffer[:last_punct_pos + 1]
# First segment minimum length check
if self.is_first_sentence and len(segment) < MIN_FIRST_SEGMENT_CHARS:
return None # Wait for more text
# Extract segment and update buffer
self.buffer = self.buffer[last_punct_pos + 1:]
if self.is_first_sentence:
self.is_first_sentence = False
return segment
return None
def flush(self) -> str | None:
"""Return any remaining text in buffer"""
if self.buffer:
remaining = self.buffer
self.buffer = ""
self.is_first_sentence = True
return remaining
return None
class HTTPTester:
"""HTTP streaming TTS tester"""
def __init__(self, config: TestConfig):
self.config = config
self.client = AsyncFishAudio(api_key=config.api_key)
async def test_llm_stream(self, test_name: str) -> LatencyResult:
"""
Test TTS with simulated LLM streaming output via HTTP.
Flow (matches current implementation):
1. LLM outputs tokens with delays
2. TextSegmenter collects tokens and waits for punctuation
3. When a segment is ready, immediately call HTTP TTS for that segment
4. Continue receiving LLM tokens while TTS processes
Key limitation: HTTP cannot start TTS until a complete segment is available.
"""
tokens = LLM_SIMULATION["tokens"]
delay_ms = LLM_SIMULATION["delay_ms"]
# Start timing from when LLM starts generating
start_time = time.perf_counter()
first_chunk_time = None
audio_bytes = b''
full_text = "".join(tokens)
try:
segmenter = TextSegmenter()
tts_config = TTSConfig(
format=self.config.format,
model="s1",
sample_rate=self.config.sample_rate,
normalize=True,
latency=self.config.latency_mode,
)
# Process tokens and immediately send segments to TTS when ready
for token in tokens:
await asyncio.sleep(delay_ms / 1000) # Simulate LLM generation delay
segment = segmenter.add_token(token)
# When a segment is ready, immediately call HTTP TTS
if segment:
audio_stream = await self.client.tts.stream(
text=segment,
reference_id=self.config.reference_id,
model="s1",
config=tts_config,
)
async for chunk in audio_stream:
if chunk:
if first_chunk_time is None:
first_chunk_time = time.perf_counter()
audio_bytes += chunk
# Flush any remaining text
remaining = segmenter.flush()
if remaining:
audio_stream = await self.client.tts.stream(
text=remaining,
reference_id=self.config.reference_id,
model="s1",
config=tts_config,
)
async for chunk in audio_stream:
if chunk:
if first_chunk_time is None:
first_chunk_time = time.perf_counter()
audio_bytes += chunk
end_time = time.perf_counter()
if first_chunk_time is None:
first_chunk_time = end_time
return LatencyResult(
method="HTTP-LLM",
test_name=test_name,
text_length=len(full_text),
ttfb_ms=(first_chunk_time - start_time) * 1000, # From LLM start to first audio
total_ms=(end_time - start_time) * 1000,
audio_bytes=len(audio_bytes),
success=True,
)
except Exception as e:
return LatencyResult(
method="HTTP-LLM",
test_name=test_name,
text_length=len(full_text),
ttfb_ms=0,
total_ms=0,
audio_bytes=0,
success=False,
error=str(e),
)
class WebSocketTester:
"""WebSocket streaming TTS tester using fishaudio SDK"""
def __init__(self, config: TestConfig):
self.config = config
self.client = AsyncFishAudio(api_key=config.api_key)
async def test_llm_stream(self, test_name: str) -> LatencyResult:
"""
Test TTS with simulated LLM streaming output via WebSocket.
Optimizations:
1. Pre-connect: Yield empty string before LLM delay to establish connection early
2. FlushEvent: Use TextSegmenter + FlushEvent to force audio generation at sentence boundaries
This mirrors HTTP's chunking strategy but with WebSocket's streaming advantage.
"""
tokens = LLM_SIMULATION["tokens"]
delay_ms = LLM_SIMULATION["delay_ms"]
full_text = "".join(tokens)
tts_config = TTSConfig(
format=self.config.format,
sample_rate=self.config.sample_rate,
normalize=True,
latency=self.config.latency_mode,
)
# Optimization 1: Pre-connect - yield empty string to establish connection
# before the first LLM token delay
async def init_websocket():
yield ""
start_time = time.perf_counter()
self.client.tts.stream_websocket(
init_websocket(),
reference_id=self.config.reference_id,
config=tts_config,
)
first_chunk_time = None
audio_bytes = b''
try:
async def llm_token_gen():
"""
Simulate LLM streaming with FlushEvent optimization.
- Pre-connect by yielding empty string immediately
- Use TextSegmenter to detect sentence boundaries
- Yield FlushEvent after each complete segment to force immediate audio generation
"""
segmenter = TextSegmenter()
for token in tokens:
await asyncio.sleep(delay_ms / 1000) # Simulate LLM generation delay
# yield token
# Accumulate token and check for segment completion
segment = segmenter.add_token(token)
if segment:
# Optimization 2: When segment is complete, yield it + FlushEvent
# to force immediate audio generation
yield segment
yield FlushEvent()
# Note: Don't yield individual tokens - TextSegmenter handles buffering
# The segment already contains all accumulated tokens
# Flush any remaining text
remaining = segmenter.flush()
if remaining:
yield remaining
yield FlushEvent()
audio_stream = self.client.tts.stream_websocket(
llm_token_gen(),
reference_id=self.config.reference_id,
config=tts_config,
)
async for chunk in audio_stream:
if chunk:
if first_chunk_time is None:
first_chunk_time = time.perf_counter()
audio_bytes += chunk
end_time = time.perf_counter()
if first_chunk_time is None:
first_chunk_time = end_time
return LatencyResult(
method="WebSocket-LLM",
test_name=test_name,
text_length=len(full_text),
ttfb_ms=(first_chunk_time - start_time) * 1000,
total_ms=(end_time - start_time) * 1000,
audio_bytes=len(audio_bytes),
success=True,
)
except Exception as e:
return LatencyResult(
method="WebSocket-LLM",
test_name=test_name,
text_length=len(full_text),
ttfb_ms=0,
total_ms=0,
audio_bytes=0,
success=False,
error=str(e),
)
def generate_report(results: list[LatencyResult], config: TestConfig) -> str:
"""Generate markdown report"""
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
report = f"""# Fish Speech TTS Latency Comparison Report
**Generated:** {now}
**Reference ID:** {config.reference_id}
**Sample Rate:** {config.sample_rate} Hz
**Format:** {config.format}
**WebSocket Latency Mode:** {config.latency_mode}
**Runs per Test:** {config.runs_per_test}
---
## Summary
| Method | Test | Avg TTFB (ms) | Avg Total (ms) | Avg Audio (bytes) |
|--------|------|---------------|----------------|-------------------|
"""
# Group results by method and test
grouped = {}
for r in results:
if not r.success:
continue
key = (r.method, r.test_name)
if key not in grouped:
grouped[key] = []
grouped[key].append(r)
for (method, test_name), runs in sorted(grouped.items()):
avg_ttfb = statistics.mean(r.ttfb_ms for r in runs)
avg_total = statistics.mean(r.total_ms for r in runs)
avg_audio = statistics.mean(r.audio_bytes for r in runs)
report += f"| {method} | {test_name} | {avg_ttfb:.1f} | {avg_total:.1f} | {avg_audio:.0f} |\n"
report += """
---
## Detailed Results
"""
for (method, test_name), runs in sorted(grouped.items()):
report += f"### {method} - {test_name}\n\n"
report += "| Run | TTFB (ms) | Total (ms) | Audio (bytes) | Text Length |\n"
report += "|-----|-----------|------------|---------------|-------------|\n"
for i, r in enumerate(runs, 1):
report += f"| {i} | {r.ttfb_ms:.1f} | {r.total_ms:.1f} | {r.audio_bytes} | {r.text_length} |\n"
if len(runs) > 1:
ttfb_std = statistics.stdev(r.ttfb_ms for r in runs)
total_std = statistics.stdev(r.total_ms for r in runs)
report += f"\n**TTFB Std Dev:** {ttfb_std:.1f} ms | **Total Std Dev:** {total_std:.1f} ms\n"
report += "\n"
# Error summary
errors = [r for r in results if not r.success]
if errors:
report += "## Errors\n\n"
for r in errors:
report += f"- **{r.method}** - {r.test_name}: {r.error}\n"
report += "\n"
# Analysis
report += """---
## Analysis
### Key Findings: LLM Streaming Simulation
This is the critical comparison for multi-turn conversations.
**Test Setup:**
- Simulated LLM output: {} tokens, {}ms per token
- Full text: "{}"
**HTTP-LLM Flow (Current Implementation):**
1. LLM outputs tokens → TextSegmenter collects
2. Wait for punctuation (e.g., comma for first sentence)
3. Segment ready → HTTP TTS request
4. Repeat for each segment
**WebSocket-LLM Flow (Proposed):**
1. LLM outputs tokens → Stream directly to WebSocket
2. Fish Audio server buffers and generates audio
3. Audio chunks return as soon as server is ready
4. No client-side segmentation needed!
""".format(len(LLM_SIMULATION["tokens"]), LLM_SIMULATION["delay_ms"], "".join(LLM_SIMULATION["tokens"])[:50] + "...")
http_llm_runs = grouped.get(("HTTP-LLM", "llm_simulation"), [])
ws_llm_runs = grouped.get(("WebSocket-LLM", "llm_simulation"), [])
if http_llm_runs and ws_llm_runs:
http_ttfb = statistics.mean(r.ttfb_ms for r in http_llm_runs)
ws_ttfb = statistics.mean(r.ttfb_ms for r in ws_llm_runs)
http_total = statistics.mean(r.total_ms for r in http_llm_runs)
ws_total = statistics.mean(r.total_ms for r in ws_llm_runs)
ttfb_diff = http_ttfb - ws_ttfb
total_diff = http_total - ws_total
ttfb_pct = (ttfb_diff / http_ttfb * 100) if http_ttfb > 0 else 0
total_pct = (total_diff / http_total * 100) if http_total > 0 else 0
report += f"| Metric | HTTP-LLM | WebSocket-LLM | Difference |\n"
report += f"|--------|----------|---------------|------------|\n"
report += f"| TTFB | {http_ttfb:.0f}ms | {ws_ttfb:.0f}ms | **{ttfb_diff:.0f}ms** ({ttfb_pct:.1f}%) |\n"
report += f"| Total | {http_total:.0f}ms | {ws_total:.0f}ms | **{total_diff:.0f}ms** ({total_pct:.1f}%) |\n"
if ttfb_diff > 100:
report += f"\n🎯 **WebSocket provides {ttfb_diff:.0f}ms faster first audio** in LLM streaming scenarios!\n"
report += """
### Recommendations
1. **For single requests:** Compare TTFB values above to determine the best method
2. **For LLM streaming:** WebSocket allows sending tokens as they arrive, reducing perceived latency
3. **Consider `latency="balanced"` for real-time applications**
4. **For multi-turn conversations:** WebSocket streaming is recommended for lower latency
---
*Generated by Fish Speech TTS Latency Tester*
"""
return report
async def main():
print("🐟 Fish Speech TTS Latency Comparison Test")
print("=" * 50)
# Get configuration from environment
api_key = os.environ.get("FISH_API_KEY")
if not api_key:
print("\n❌ Error: FISH_API_KEY not set")
print(" export FISH_API_KEY='your-key'")
print("\n💡 Get your API key from: https://fish.audio/")
sys.exit(1)
reference_id = os.environ.get("FISH_REFERENCE_ID", "5196af35f6ff4a0dbf541793fc9f2157")
runs = int(os.environ.get("TEST_RUNS", "3"))
config = TestConfig(
api_key=api_key,
reference_id=reference_id,
runs_per_test=runs,
)
print(f"\n📋 Configuration:")
print(f" Reference ID: {reference_id}")
print(f" Sample Rate: {config.sample_rate} Hz")
print(f" Format: {config.format}")
print(f" Runs per test: {runs}")
# Initialize testers
http_tester = HTTPTester(config)
ws_tester = WebSocketTester(config)
results: list[LatencyResult] = []
# Run HTTP LLM simulation test
print("\n" + "=" * 50)
print("🔄 Testing HTTP with LLM Simulation...")
print(" (HTTP must wait for segment completion before starting TTS)")
print("=" * 50)
print(f"\n📝 Simulating LLM output ({len(LLM_SIMULATION['tokens'])} tokens, {LLM_SIMULATION['delay_ms']}ms/token)")
for run in range(runs):
result = await http_tester.test_llm_stream("llm_simulation")
results.append(result)
if result.success:
print(f" Run {run + 1}: TTFB={result.ttfb_ms:.0f}ms, Total={result.total_ms:.0f}ms")
else:
print(f" Run {run + 1}: ❌ {result.error}")
await asyncio.sleep(0.5)
# Run WebSocket LLM simulation test
print("\n" + "=" * 50)
print("🔄 Testing WebSocket with LLM Simulation...")
print("=" * 50)
print(f"\n📝 Simulating LLM output ({len(LLM_SIMULATION['tokens'])} tokens, {LLM_SIMULATION['delay_ms']}ms/token)")
for run in range(runs):
result = await ws_tester.test_llm_stream("llm_simulation")
results.append(result)
if result.success:
print(f" Run {run + 1}: TTFB={result.ttfb_ms:.0f}ms, Total={result.total_ms:.0f}ms")
else:
print(f" Run {run + 1}: ❌ {result.error}")
await asyncio.sleep(0.5)
# Generate report
print("\n" + "=" * 50)
print("📊 Generating Report...")
print("=" * 50)
report = generate_report(results, config)
# Save report
script_dir = os.path.dirname(os.path.abspath(__file__))
reports_dir = os.path.join(script_dir, "reports")
os.makedirs(reports_dir, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
report_file = os.path.join(reports_dir, f"latency_report_{timestamp}.md")
with open(report_file, "w") as f:
f.write(report)
print(f"\n✅ Report saved to: {report_file}")
# Print summary
print("\n" + "=" * 50)
print("📈 Quick Summary")
print("=" * 50)
# Group and average results
grouped = {}
for r in results:
if not r.success:
continue
key = (r.method, r.test_name)
if key not in grouped:
grouped[key] = []
grouped[key].append(r)
print(f"\n{'Method':<15} {'Test':<20} {'Avg TTFB (ms)':<15} {'Avg Total (ms)':<15}")
print("-" * 65)
for (method, test_name), runs_list in sorted(grouped.items()):
avg_ttfb = statistics.mean(r.ttfb_ms for r in runs_list)
avg_total = statistics.mean(r.total_ms for r in runs_list)
print(f"{method:<15} {test_name:<20} {avg_ttfb:<15.0f} {avg_total:<15.0f}")
print("\n✅ Test completed!")
if __name__ == "__main__":
asyncio.run(main())