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

feat: Fit with live-agent-api integration
This commit is contained in:
Harold-Guo 2025-11-24 20:44:18 +08:00 committed by GitHub
commit 68813e59db
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
24 changed files with 446 additions and 141 deletions

View file

@ -6,6 +6,7 @@ from infra import get_db, get_s3
from services.agent_service import agent_service from services.agent_service import agent_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
router = APIRouter() router = APIRouter()
@ -43,7 +44,20 @@ async def get_agent_detail(
): ):
"""Get agent detail""" """Get agent detail"""
agent = await agent_service.get_agent_detail(db=db, agent_id=agent_id) agent = await agent_service.get_agent_detail(db=db, agent_id=agent_id)
return success_response(data=agent.model_dump())
agent_response = AgentResponse(
agent_id=agent.agent_id,
name=agent.name,
avatar_url=agent.avatar_url,
description=agent.description,
voice_id=agent.voice_id,
instruction=agent.instruction,
voice_opening=agent.voice_opening,
voice_closing=agent.voice_closing,
created_at=agent.created_at,
)
return success_response(data=agent_response.model_dump())
@router.post("", summary="Create Agent") @router.post("", summary="Create Agent")

View file

@ -2,18 +2,58 @@ from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from infra import get_db from infra import get_db
from infra.fishaudio import get_fish_audio
from services.agent_service import agent_service from services.agent_service import agent_service
from utils.response import success_response from utils.response import success_response
from schemas.agent import AgentConfigResponse
router = APIRouter() router = APIRouter()
@router.get("/agents/{agent_id}/config", summary="Get a specified agent's config") @router.get("/agents/{agent_id}/config", summary="Get agent config for backend services")
async def get_agent_config( async def get_agent_config(
agent_id: str, agent_id: str,
db: AsyncSession = Depends(get_db) db: AsyncSession = Depends(get_db),
fish_client = Depends(get_fish_audio)
): ):
"""Get agent configuration for xiaozhi-server""" """
config = await agent_service.get_agent_config(db=db, agent_id=agent_id) Get agent runtime configuration for xiaozhi-server
return success_response(data=config.model_dump())
This is an internal API for service-to-service communication:
- No authentication required
- Returns agent config with voice language info from Fish Audio
- Used by xiaozhi-server to drive AI conversations
Flow:
1. Get agent config by agent_id
2. If voice_id exists, fetch voice info from Fish Audio
3. Extract language and merge into response
"""
# Step 1: Get agent config
agent = await agent_service.get_agent_detail(db=db, agent_id=agent_id)
# Step 2: If voice_id exists, fetch language from Fish Audio
language = None
if agent.voice_id:
try:
fish_voice = await fish_client.voices.get(agent.voice_id)
if fish_voice and hasattr(fish_voice, 'languages') and fish_voice.languages:
# Fish Audio returns a list of languages, take the first one
language = fish_voice.languages[0] if isinstance(fish_voice.languages, list) else fish_voice.languages
except Exception as e:
# If Fish Audio API fails, log but don't fail the request
print(f"Warning: Failed to fetch voice language for {agent.voice_id}: {e}")
# Step 3: Merge voice language into response
response = AgentConfigResponse(
agent_id=agent.agent_id,
name=agent.name,
voice_id=agent.voice_id,
language=language,
instruction=agent.instruction,
voice_opening=agent.voice_opening,
voice_closing=agent.voice_closing,
)
return success_response(data=response.model_dump())

View file

@ -3,7 +3,7 @@ from botocore.args import logger
from fastapi import APIRouter, Depends, Query, Form, File, UploadFile from fastapi import APIRouter, Depends, Query, Form, File, UploadFile
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from infra import get_db from infra import get_db, get_s3
from infra.fishaudio import get_fish_audio from infra.fishaudio import get_fish_audio
from services.voice_service import voice_service from services.voice_service import voice_service
from schemas.voice import ( from schemas.voice import (
@ -138,36 +138,36 @@ async def get_my_voices(
async def clone_voice( async def clone_voice(
audio_file: UploadFile = File(..., description="Audio file for cloning"), audio_file: UploadFile = File(..., description="Audio file for cloning"),
text: Optional[str] = Form(None, description="Optional transcription text"), text: Optional[str] = Form(None, description="Optional transcription text"),
fish_client = Depends(get_fish_audio) current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db),
fish_client = Depends(get_fish_audio),
s3 = Depends(get_s3)
): ):
""" """
Clone a voice from uploaded audio file Clone a voice from uploaded audio file
- Supports both direct audio upload and recorded audio - Requires authentication
- Text parameter is optional (required for recorded audio) - Stores the original audio in S3
- Creates voice record in database with default name
- Use PUT /{voice_id} to update name and description later
- Uses Fish Audio's fast training mode (typically 30s-2min) - Uses Fish Audio's fast training mode (typically 30s-2min)
""" """
# Clone voice # Clone voice, upload to S3, and save to database
voice_id, samples = await voice_service.clone_voice( voice = await voice_service.clone_voice(
db=db,
s3=s3,
fish_client=fish_client, fish_client=fish_client,
owner_id=current_user_id,
audio_file=audio_file, audio_file=audio_file,
text=text text=text
) )
# Build response
if samples:
sample = AudioSample(
title=samples[0].title,
text=samples[0].text,
audio=samples[0].audio
)
else:
sample = None
return success_response( return success_response(
data={ data={
"voice_id": voice_id, "voice_id": voice.voice_id,
"sample": sample, "sample_url": voice.sample_url, # S3 URL of stored audio
"sample_text": voice.sample_text # Transcription text
}, },
message="Voice cloned successfully" message="Voice cloned successfully"
) )
@ -185,6 +185,7 @@ async def add_voice(
Add a Fish Audio voice to user's my voices Add a Fish Audio voice to user's my voices
- Creates a reference to the Fish Audio voice - Creates a reference to the Fish Audio voice
- Name is provided by client (from Fish voice title) - Name is provided by client (from Fish voice title)
- For cloned voices, can include sample_url and sample_text
""" """
voice = await voice_service.add_voice( voice = await voice_service.add_voice(
db=db, db=db,
@ -192,7 +193,9 @@ async def add_voice(
owner_id=current_user_id, owner_id=current_user_id,
voice_id=voice_id, voice_id=voice_id,
name=request.name, name=request.name,
desc=request.desc desc=request.desc,
sample_url=request.sample_url,
sample_text=request.sample_text
) )
# Build response # Build response
@ -200,6 +203,8 @@ async def add_voice(
data=LiveAgentVoice( data=LiveAgentVoice(
voice_id=voice.voice_id, voice_id=voice.voice_id,
name=voice.name, name=voice.name,
desc=voice.desc,
created_at=voice.created_at,
).model_dump(exclude_none=True), ).model_dump(exclude_none=True),
message="Voice added successfully" message="Voice added successfully"
) )

View file

@ -66,6 +66,8 @@ CREATE TABLE IF NOT EXISTS voices (
owner_id VARCHAR(50) NOT NULL, owner_id VARCHAR(50) NOT NULL,
name VARCHAR(100) NOT NULL, name VARCHAR(100) NOT NULL,
"desc" TEXT NOT NULL DEFAULT '', "desc" TEXT NOT NULL DEFAULT '',
sample_url TEXT,
sample_text TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
updated_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), updated_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
CONSTRAINT fk_voices_owner FOREIGN KEY (owner_id) CONSTRAINT fk_voices_owner FOREIGN KEY (owner_id)
@ -84,6 +86,8 @@ COMMENT ON COLUMN voices.voice_id IS 'Fish Audio voice ID';
COMMENT ON COLUMN voices.owner_id IS 'User ID of voice owner'; COMMENT ON COLUMN voices.owner_id IS 'User ID of voice owner';
COMMENT ON COLUMN voices.name IS 'Voice display name'; COMMENT ON COLUMN voices.name IS 'Voice display name';
COMMENT ON COLUMN voices."desc" IS 'Voice description'; COMMENT ON COLUMN voices."desc" IS 'Voice description';
COMMENT ON COLUMN voices.sample_url IS 'S3 URL of the original audio sample (for cloned voices)';
COMMENT ON COLUMN voices.sample_text IS 'Transcription text of the audio sample (for cloned voices)';
-- ==================== Table: agent_templates ==================== -- ==================== Table: agent_templates ====================
-- Pre-configured agent templates -- Pre-configured agent templates

View file

@ -29,6 +29,10 @@ class VoiceModel(Base):
name: Mapped[str] = mapped_column(String(100), nullable=False) name: Mapped[str] = mapped_column(String(100), nullable=False)
desc: Mapped[str] = mapped_column(Text, nullable=False) desc: Mapped[str] = mapped_column(Text, nullable=False)
# Audio sample information (for cloned voices)
sample_url: Mapped[str | None] = mapped_column(Text, nullable=True)
sample_text: Mapped[str | None] = mapped_column(Text, nullable=True)
# Timestamps # Timestamps
created_at: Mapped[datetime] = mapped_column( created_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True), TIMESTAMP(timezone=True),
@ -161,14 +165,18 @@ class Voice:
voice_id: str, voice_id: str,
owner_id: str, owner_id: str,
name: str, name: str,
desc: str desc: str,
sample_url: Optional[str] = None,
sample_text: Optional[str] = None
) -> VoiceModel: ) -> VoiceModel:
"""Create a new voice""" """Create a new voice"""
voice = VoiceModel( voice = VoiceModel(
voice_id=voice_id, voice_id=voice_id,
owner_id=owner_id, owner_id=owner_id,
name=name, name=name,
desc=desc desc=desc,
sample_url=sample_url,
sample_text=sample_text
) )
db.add(voice) db.add(voice)
await db.commit() await db.commit()
@ -180,18 +188,30 @@ class Voice:
db: AsyncSession, db: AsyncSession,
voice_id: str, voice_id: str,
owner_id: str, owner_id: str,
name: str, name: Optional[str] = None,
desc: str desc: Optional[str] = None
) -> VoiceModel: ) -> VoiceModel:
"""Update a voice""" """Update a voice (only updates provided fields)"""
# Build update values dict with only non-None values
update_values = {}
if name is not None:
update_values['name'] = name
if desc is not None:
update_values['desc'] = desc
# If no fields to update, just return the existing voice
if not update_values:
voice = await Voice.get_by_voice_and_owner(db, voice_id, owner_id)
return voice
stmt = ( stmt = (
update(VoiceModel) update(VoiceModel)
.where(VoiceModel.voice_id == voice_id) .where(VoiceModel.voice_id == voice_id)
.where(VoiceModel.owner_id == owner_id) .where(VoiceModel.owner_id == owner_id)
.values(name=name, desc=desc) .values(**update_values)
.returning(VoiceModel) .returning(VoiceModel)
) )
result =await db.execute(stmt) result = await db.execute(stmt)
await db.commit() await db.commit()
return result.scalar_one() return result.scalar_one()

View file

@ -35,7 +35,6 @@ class AgentResponse(BaseModel):
voice_opening: Optional[str] = None voice_opening: Optional[str] = None
voice_closing: Optional[str] = None voice_closing: Optional[str] = None
created_at: datetime created_at: datetime
updated_at: datetime
class Config: class Config:
from_attributes = True from_attributes = True
@ -53,10 +52,8 @@ class AgentConfigResponse(BaseModel):
agent_id: str agent_id: str
name: str name: str
voice_id: Optional[str] = None voice_id: Optional[str] = None
language: Optional[str] = None # Voice language from Fish Audio
instruction: str instruction: str
voice_opening: Optional[str] = None voice_opening: Optional[str] = None
voice_closing: Optional[str] = None voice_closing: Optional[str] = None
class Config:
from_attributes = True

View file

@ -23,6 +23,8 @@ class VoiceAddRequest(BaseModel):
"""Voice add request""" """Voice add request"""
name: str = Field(..., min_length=1, max_length=100, description="Voice name") name: str = Field(..., min_length=1, max_length=100, description="Voice name")
desc: str = Field(..., max_length=500, description="Voice description") desc: str = Field(..., max_length=500, description="Voice description")
sample_url: Optional[str] = Field(None, description="URL of stored audio sample (for cloned voices)")
sample_text: Optional[str] = Field(None, description="Transcription text (for cloned voices)")
# ==================== Response Schemas ==================== # ==================== Response Schemas ====================
@ -40,7 +42,7 @@ class LiveAgentVoice(BaseModel):
samples: Optional[List[AudioSample]] = None samples: Optional[List[AudioSample]] = None
created_at: datetime created_at: Optional[datetime] = None

View file

@ -40,7 +40,7 @@ class AgentService:
""" """
agents, next_cursor, has_more = await Agent.get_agents_by_owner( agents, next_cursor, has_more = await Agent.get_agents_by_owner(
db, db,
owner_id=owner_id, owner_id=owner_id,
cursor=cursor, cursor=cursor,
limit=page_size limit=page_size
) )
@ -56,13 +56,13 @@ class AgentService:
self, self,
db: AsyncSession, db: AsyncSession,
agent_id: str agent_id: str
) -> AgentResponse: ) -> AgentModel:
"""Get agent detail""" """Get agent detail"""
agent = await Agent.get_by_id(db, agent_id) agent = await Agent.get_by_id(db, agent_id)
if not agent: if not agent:
raise NotFoundException("Agent not found") raise NotFoundException("Agent not found")
return AgentResponse.model_validate(agent) return agent
async def create_agent( async def create_agent(
self, self,
@ -178,18 +178,7 @@ class AgentService:
# Delete agent # Delete agent
await Agent.delete(db, agent_id) await Agent.delete(db, agent_id)
async def get_agent_config(
self,
db: AsyncSession,
agent_id: str
) -> AgentConfigResponse:
"""Get agent configuration for xiaozhi-server"""
agent = await Agent.get_by_id(db, agent_id)
if not agent:
raise NotFoundException("Agent not found")
return AgentConfigResponse.model_validate(agent)
agent_service = AgentService() agent_service = AgentService()

View file

@ -6,6 +6,9 @@ from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as Fis
from repositories import VoiceModel, Voice from repositories import VoiceModel, Voice
from utils.ulid import generate_voice_id from utils.ulid import generate_voice_id
from repositories import FileRepository
from datetime import datetime, timezone
class VoiceService: class VoiceService:
"""Voice service layer""" """Voice service layer"""
@ -90,28 +93,45 @@ class VoiceService:
async def clone_voice( async def clone_voice(
self, self,
db: AsyncSession,
s3, # S3 client for storing audio
fish_client: AsyncFishAudio, fish_client: AsyncFishAudio,
owner_id: str,
audio_file: UploadFile, audio_file: UploadFile,
text: Optional[str] = None text: Optional[str] = None
) -> Tuple[str, List[FishSample]]: ) -> VoiceModel:
""" """
Clone a voice using Fish Audio API Clone a voice using Fish Audio API, store audio, and save to database
Args: Args:
db: Database session db: Database session
s3: S3 client for storing audio
fish_client: Fish Audio client fish_client: Fish Audio client
name: Voice name
owner_id: User ID owner_id: User ID
name: Voice name
audio_file: Audio file to clone audio_file: Audio file to clone
text: Optional transcription text text: Optional transcription text
Returns: Returns:
Created VoiceModel Created VoiceModel
""" """
# Generate voice_id for our system
voice_id = generate_voice_id()
# Read audio file content # Read audio file content
audio_content = await audio_file.read() audio_content = await audio_file.read()
voice_id = generate_voice_id()
# Reset file pointer for S3 upload
await audio_file.seek(0)
# Upload audio to S3 for storage (using voice_id as filename)
sample_url = await FileRepository.upload(
s3=s3,
file=audio_file,
folder="voice_samples",
custom_filename=voice_id
)
# Call Fish Audio API to clone voice # Call Fish Audio API to clone voice
fish_voice: FishVoice = await fish_client.voices.create( fish_voice: FishVoice = await fish_client.voices.create(
title=f"live_agent_{voice_id}", title=f"live_agent_{voice_id}",
@ -121,7 +141,22 @@ class VoiceService:
visibility="private", visibility="private",
enhance_audio_quality=True enhance_audio_quality=True
) )
return fish_voice.id, fish_voice.samples
# Create voice record in database
default_name = f"{owner_id}'s Cloned Voice {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M')}"
voice = await Voice.create(
db=db,
voice_id=fish_voice.id, # Use Fish Audio voice ID
owner_id=owner_id,
name=default_name,
desc="", # Empty description, to be updated later
sample_url=sample_url,
sample_text=text
)
return voice
async def add_voice( async def add_voice(
self, self,
@ -131,6 +166,8 @@ class VoiceService:
voice_id: str, voice_id: str,
name: str, name: str,
desc: str, desc: str,
sample_url: Optional[str] = None,
sample_text: Optional[str] = None
) -> VoiceModel: ) -> VoiceModel:
""" """
Add a Fish Audio voice to user's my voices Add a Fish Audio voice to user's my voices
@ -142,6 +179,8 @@ class VoiceService:
voice_id: Audio voice ID voice_id: Audio voice ID
name: Voice name name: Voice name
desc: Voice description desc: Voice description
sample_url: Optional URL of stored audio sample (for cloned voices)
sample_text: Optional transcription text (for cloned voices)
Returns: Returns:
Created VoiceModel Created VoiceModel
@ -158,7 +197,9 @@ class VoiceService:
voice_id=voice_id, # Use Fish Audio voice ID directly voice_id=voice_id, # Use Fish Audio voice ID directly
owner_id=owner_id, owner_id=owner_id,
name=name, name=name,
desc=desc desc=desc,
sample_url=sample_url,
sample_text=sample_text
) )
return voice return voice
@ -193,8 +234,8 @@ class VoiceService:
db: AsyncSession, db: AsyncSession,
voice_id: str, voice_id: str,
owner_id: str, owner_id: str,
name: str, name: Optional[str] = None,
desc: str desc: Optional[str] = None
) -> VoiceModel: ) -> VoiceModel:
""" """
Update voice name and/or description Update voice name and/or description
@ -203,13 +244,13 @@ class VoiceService:
db: Database session db: Database session
voice_id: Voice ID voice_id: Voice ID
owner_id: User ID owner_id: User ID
name: New voice name name: New voice name (optional)
desc: New voice description desc: New voice description (optional)
Returns: Returns:
Updated VoiceModel Updated VoiceModel
""" """
# Get existing voice # Get existing voice to verify ownership
voice = await Voice.get_by_voice_and_owner( voice = await Voice.get_by_voice_and_owner(
db=db, db=db,
voice_id=voice_id, voice_id=voice_id,
@ -221,7 +262,7 @@ class VoiceService:
raise NotFoundException(f"Voice {voice_id} not found or not owned by user") raise NotFoundException(f"Voice {voice_id} not found or not owned by user")
# Update only provided fields # Update only provided fields
new_voice = await Voice.update( updated_voice = await Voice.update(
db=db, db=db,
voice_id=voice_id, voice_id=voice_id,
owner_id=owner_id, owner_id=owner_id,
@ -229,7 +270,7 @@ class VoiceService:
desc=desc desc=desc
) )
return new_voice return updated_voice
voice_service = VoiceService() voice_service = VoiceService()

View file

@ -2,7 +2,7 @@ import os
import yaml import yaml
from collections.abc import Mapping from collections.abc import Mapping
from config.manage_api_client import init_service, get_server_config, get_agent_models from config.manage_api_client import init_service, get_server_config, get_agent_models
from dotenv import load_dotenv
def get_project_dir(): def get_project_dir():
"""获取项目根目录""" """获取项目根目录"""
@ -29,10 +29,24 @@ def load_config():
# 加载默认配置 # 加载默认配置
# default_config = read_config(default_config_path) # default_config = read_config(default_config_path)
custom_config = read_config(custom_config_path) config = read_config(custom_config_path)
config["read_config_from_live_agent_api"] = True
if custom_config.get("manager-api", {}).get("url"): # load environment variables
config = get_config_from_api(custom_config) load_dotenv()
# tts
select_tts_module = config["selected_module"]["TTS"]
if os.environ.get("REGION") == "LOCAL" and select_tts_module == "FishSpeech":
config["TTS"][select_tts_module]["api_key"] = os.environ.get("FISH_API_KEY")
# asr
select_asr_module = config["selected_module"]["ASR"]
if os.environ.get("REGION") == "LOCAL" and select_asr_module == "GroqASR":
config["ASR"][select_asr_module]["api_key"] = os.environ.get("GROQ_API_KEY")
# llm
select_llm_module = config["selected_module"]["LLM"]
if os.environ.get("REGION") == "LOCAL" and select_llm_module == "GroqLLM":
config["LLM"][select_llm_module]["api_key"] = os.environ.get("GROQ_API_KEY")
# if custom_config.get("manager-api", {}).get("url"):
# config = get_config_from_api(custom_config)
# else: # else:
# # 合并配置 # # 合并配置
# config = merge_configs(default_config, custom_config) # config = merge_configs(default_config, custom_config)

View file

@ -0,0 +1,49 @@
import httpx
from config.logger import setup_logging
from typing import Optional
logger = setup_logging()
def get_agent_config_from_api(agent_id: str, config: dict) -> Optional[dict]:
"""
Get agent configuration from live-agent-api
Args:
agent_id: Agent ID
config: System config containing live-agent-api URL
Returns:
Agent config dict or None if failed
"""
live_api_config = config.get("live-agent-api", {})
base_url = live_api_config.get("url", "http://live-agent-api:8080/api/live_agent/v1")
timeout = live_api_config.get("timeout", 10)
url = f"{base_url}/internal/agents/{agent_id}/config"
try:
with httpx.Client(timeout=timeout) as client:
response = client.request("GET", url)
response.raise_for_status()
result = response.json()
# Extract data from success_response format
if result.get("code") == 200 and "data" in result:
agent_config = result["data"]
logger.info(f"Successfully fetched agent config for agent_id={agent_id}")
return agent_config
else:
logger.error(f"Invalid response format from live-agent-api: {result}")
return None
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
logger.error(f"Agent not found: agent_id={agent_id}")
else:
logger.error(f"HTTP error fetching agent config: {e}")
return None
except Exception as e:
logger.error(f"Failed to fetch agent config for {agent_id}: {e}")
return None

View file

@ -80,7 +80,7 @@ class OTAHandler(BaseHandler):
self.logger.bind(tag=TAG).info(f"OTA请求ClientID: {client_id}") self.logger.bind(tag=TAG).info(f"OTA请求ClientID: {client_id}")
else: else:
raise Exception("OTA请求ClientID为空") raise Exception("OTA请求ClientID为空")
data_json = json.loads(data) data_json = json.loads(data)
server_config = self.config["server"] server_config = self.config["server"]

View file

@ -41,9 +41,9 @@ from config.manage_api_client import DeviceNotFoundException, DeviceBindExceptio
from core.utils.prompt_manager import PromptManager from core.utils.prompt_manager import PromptManager
from core.utils.voiceprint_provider import VoiceprintProvider from core.utils.voiceprint_provider import VoiceprintProvider
from core.utils import textUtils from core.utils import textUtils
from config.live_agent_api_client import get_agent_config_from_api
TAG = __name__ TAG = __name__
auto_import_modules("plugins_func.functions") auto_import_modules("plugins_func.functions")
@ -71,6 +71,7 @@ class ConnectionHandler:
self.need_bind = False self.need_bind = False
self.bind_code = None self.bind_code = None
self.read_config_from_api = self.config.get("read_config_from_api", False) self.read_config_from_api = self.config.get("read_config_from_api", False)
self.read_config_from_live_agent_api = self.config.get("read_config_from_live_agent_api", False)
self.websocket = None self.websocket = None
self.headers = None self.headers = None
@ -160,6 +161,12 @@ class ConnectionHandler:
# 初始化提示词管理器 # 初始化提示词管理器
self.prompt_manager = PromptManager(config, self.logger) self.prompt_manager = PromptManager(config, self.logger)
# agent-related configs
self._instruction = None
self._voice_opening = None
self._voice_closing = None
self._language = None
async def handle_connection(self, ws): async def handle_connection(self, ws):
try: try:
# 获取并验证headers # 获取并验证headers
@ -176,6 +183,7 @@ class ConnectionHandler:
) )
self.device_id = self.headers.get("device-id", None) self.device_id = self.headers.get("device-id", None)
self.agent_id = self.headers.get("agent-id", None)
# 认证通过,继续处理 # 认证通过,继续处理
self.websocket = ws self.websocket = ws
@ -192,11 +200,12 @@ class ConnectionHandler:
# 启动超时检查任务 # 启动超时检查任务
self.timeout_task = asyncio.create_task(self._check_timeout()) self.timeout_task = asyncio.create_task(self._check_timeout())
# todo: welcome message need to be set after private config is loaded
self.welcome_msg = self.config["xiaozhi"] self.welcome_msg = self.config["xiaozhi"]
self.welcome_msg["session_id"] = self.session_id self.welcome_msg["session_id"] = self.session_id
# 获取差异化配置 # 获取差异化配置
self._initialize_private_config() self._initialize_agent_config()
# 异步初始化 # 异步初始化
self.executor.submit(self._initialize_components) self.executor.submit(self._initialize_components)
@ -404,16 +413,6 @@ class ConnectionHandler:
) )
self.logger = create_connection_logger(self.selected_module_str) self.logger = create_connection_logger(self.selected_module_str)
"""初始化组件"""
if self.config.get("prompt") is not None:
user_prompt = self.config["prompt"]
# 使用快速提示词进行初始化
prompt = self.prompt_manager.get_quick_prompt(user_prompt)
self.change_system_prompt(prompt)
self.logger.bind(tag=TAG).info(
f"快速初始化组件: prompt成功 {prompt[:50]}..."
)
"""初始化本地组件""" """初始化本地组件"""
if self.vad is None: if self.vad is None:
self.vad = self._vad self.vad = self._vad
@ -446,6 +445,16 @@ class ConnectionHandler:
"""初始化上报线程""" """初始化上报线程"""
self._init_report_threads() self._init_report_threads()
if self._voice_opening:
self.logger.bind(tag=TAG).info(f"send the opening message: {self._voice_opening}")
self.tts.tts_text_queue.put(TTSMessageDTO(
sentence_id=str(uuid.uuid4().hex),
sentence_type=SentenceType.MIDDLE,
content_type=ContentType.TEXT,
content_detail=self._voice_opening,
)
)
except Exception as e: except Exception as e:
self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}") self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}")
@ -466,9 +475,10 @@ class ConnectionHandler:
# 构建增强的系统提示词(返回 (enhanced_prompt, role_tts_config)) # 构建增强的系统提示词(返回 (enhanced_prompt, role_tts_config))
result = self.prompt_manager.build_enhanced_prompt( result = self.prompt_manager.build_enhanced_prompt(
self.config["prompt"], user_prompt=self._instruction,
self.device_id, device_id=self.device_id,
self.client_ip, client_ip=self.client_ip,
language=self._language,
user_persona=user_persona, user_persona=user_persona,
) )
@ -655,35 +665,6 @@ class ConnectionHandler:
init_vad = check_vad_update(self.common_config, private_config) init_vad = check_vad_update(self.common_config, private_config)
init_asr = check_asr_update(self.common_config, private_config) init_asr = check_asr_update(self.common_config, private_config)
if init_vad:
self.config["VAD"] = private_config["VAD"]
self.config["selected_module"]["VAD"] = private_config["selected_module"][
"VAD"
]
if init_asr:
self.config["ASR"] = private_config["ASR"]
self.config["selected_module"]["ASR"] = private_config["selected_module"][
"ASR"
]
if private_config.get("TTS", None) is not None:
init_tts = True
self.config["TTS"] = private_config["TTS"]
self.config["selected_module"]["TTS"] = private_config["selected_module"][
"TTS"
]
# 标记 API 已设置 TTS 配置(优先级1)
self.config["_api_tts_applied"] = True
if private_config.get("LLM", None) is not None:
init_llm = True
self.config["LLM"] = private_config["LLM"]
self.config["selected_module"]["LLM"] = private_config["selected_module"][
"LLM"
]
if private_config.get("VLLM", None) is not None:
self.config["VLLM"] = private_config["VLLM"]
self.config["selected_module"]["VLLM"] = private_config["selected_module"][
"VLLM"
]
if private_config.get("Memory", None) is not None: if private_config.get("Memory", None) is not None:
init_memory = True init_memory = True
self.config["Memory"] = private_config["Memory"] self.config["Memory"] = private_config["Memory"]
@ -835,6 +816,56 @@ class ConnectionHandler:
if hasattr(self, "loop") and self.loop: if hasattr(self, "loop") and self.loop:
asyncio.run_coroutine_threadsafe(self.func_handler._initialize(), self.loop) asyncio.run_coroutine_threadsafe(self.func_handler._initialize(), self.loop)
def _initialize_agent_config(self):
"""initialize agent config"""
if not self.read_config_from_live_agent_api:
return
private_config = get_agent_config_from_api(self.agent_id, self.config)
# self.logger.bind(tag=TAG).info(f"private_config: {private_config}")
# self.logger.bind(tag=TAG).info(f"self.config: {self.config}")
self.config["TTS"]["FishSpeech"]["reference_id"] = private_config["voice_id"]
self._instruction = private_config["instruction"]
self._voice_opening = private_config["voice_opening"]
self._voice_closing = private_config["voice_closing"]
self._language = private_config["language"]
init_llm, init_tts, init_memory, init_intent = (
True,
True,
False,
False,
)
init_vad = False
init_asr = True
try:
modules = initialize_modules(
self.logger,
self.config,
init_vad,
init_asr,
init_llm,
init_tts,
init_memory,
init_intent,
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}")
modules = {}
if modules.get("tts", None) is not None:
self.tts = modules["tts"]
if modules.get("vad", None) is not None:
self.vad = modules["vad"]
if modules.get("asr", None) is not None:
self.asr = modules["asr"]
if modules.get("llm", None) is not None:
self.llm = modules["llm"]
if modules.get("intent", None) is not None:
self.intent = modules["intent"]
if modules.get("memory", None) is not None:
self.memory = modules["memory"]
def change_system_prompt(self, prompt): def change_system_prompt(self, prompt):
self.prompt = prompt self.prompt = prompt
# 更新系统prompt至上下文 # 更新系统prompt至上下文

View file

@ -6,6 +6,7 @@ from core.handle.abortHandle import handleAbortMessage
from core.handle.intentHandler import handle_user_intent from core.handle.intentHandler import handle_user_intent
from core.utils.output_counter import check_device_output_limit from core.utils.output_counter import check_device_output_limit
from core.handle.sendAudioHandle import send_stt_message, SentenceType from core.handle.sendAudioHandle import send_stt_message, SentenceType
from core.providers.tts.dto.dto import SentenceType, ContentType, TTSMessageDTO
TAG = __name__ TAG = __name__

View file

@ -82,12 +82,16 @@ 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"): # if config.get("private_voice"):
self.reference_id = config.get("private_voice") # self.reference_id = config.get("private_voice")
else: # else:
self.reference_id = ( # self.reference_id = (
None if not config.get("reference_id") else config.get("reference_id") # None if not config.get("reference_id") else config.get("reference_id")
) # )
if config.get("reference_id"):
self.reference_id = config.get("reference_id")
else:
self.reference_id = None
self.reference_audio = parse_string_to_list( self.reference_audio = parse_string_to_list(
config.get('ref_audio')if config.get('ref_audio') else config.get("reference_audio") config.get('ref_audio')if config.get('ref_audio') else config.get("reference_audio")
) )

View file

@ -1,6 +1,8 @@
from typing import Dict, Any from typing import Dict, Any
from config.logger import setup_logging from config.logger import setup_logging
from core.utils import tts, llm, intent, memory, vad, asr from core.utils import tts, llm, intent, memory, vad, asr
from dotenv import load_dotenv
import os
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()

View file

@ -156,6 +156,7 @@ class PromptManager:
device_id: str, device_id: str,
client_ip: str = None, client_ip: str = None,
user_persona: str = None, user_persona: str = None,
language: str = None,
*args, *args,
**kwargs **kwargs
) -> str: ) -> str:
@ -170,7 +171,7 @@ class PromptManager:
# 优先使用 API 传入的 prompt(正式部署场景) # 优先使用 API 传入的 prompt(正式部署场景)
profile = user_prompt profile = user_prompt
timezone = self.config.get("timezone", "Asia/Shanghai") timezone = self.config.get("timezone", "Asia/Shanghai")
language = self.config.get("language", "en") language = language
self.logger.bind(tag=TAG).info("使用 API 下发的 profile") self.logger.bind(tag=TAG).info("使用 API 下发的 profile")
else: else:
# API 未提供 prompt,尝试加载本地 role 配置(本地开发场景) # API 未提供 prompt,尝试加载本地 role 配置(本地开发场景)

View file

@ -21,8 +21,8 @@ class WebSocketServer:
self.logger, self.logger,
self.config, self.config,
"VAD" in self.config["selected_module"], "VAD" in self.config["selected_module"],
"ASR" in self.config["selected_module"], False,
"LLM" in self.config["selected_module"], False,
False, False,
"Memory" in self.config["selected_module"], "Memory" in self.config["selected_module"],
"Intent" in self.config["selected_module"], "Intent" in self.config["selected_module"],
@ -75,6 +75,8 @@ class WebSocketServer:
websocket.request.headers["device-id"] = query_params["device-id"][0] websocket.request.headers["device-id"] = query_params["device-id"][0]
if "client-id" in query_params: if "client-id" in query_params:
websocket.request.headers["client-id"] = query_params["client-id"][0] websocket.request.headers["client-id"] = query_params["client-id"][0]
if "agent-id" in query_params:
websocket.request.headers["agent-id"] = query_params["agent-id"][0]
if "authorization" in query_params: if "authorization" in query_params:
websocket.request.headers["authorization"] = query_params[ websocket.request.headers["authorization"] = query_params[
"authorization" "authorization"

View file

@ -40,6 +40,9 @@ manager-api:
# This secret is used for local development, it will be replaced by the actual secret when the server is deployed # This secret is used for local development, it will be replaced by the actual secret when the server is deployed
secret: 613be043-dc7e-4f5e-b775-e318e5bc87a3 secret: 613be043-dc7e-4f5e-b775-e318e5bc87a3
live-agent-api:
url: http://live-agent-api:8080/api/live_agent/v1
# MySQL配置(用于聊天记录和记忆关联) # MySQL配置(用于聊天记录和记忆关联)
mysql: mysql:
host: localhost host: localhost
@ -189,11 +192,6 @@ prompt: |
# 默认系统提示词模板文件 # 默认系统提示词模板文件
prompt_template: agent-base-prompt.txt prompt_template: agent-base-prompt.txt
# Role 配置
# 指定要加载的 role 配置文件(位于 core/roles/data/目录)
# 如果不指定或加载失败,将使用 prompt 字段的内容作为 profile
role_id: hospital_assistant
# 时区配置(用于系统提示词中的时间显示) # 时区配置(用于系统提示词中的时间显示)
# 支持的时区格式:Asia/Shanghai, America/New_York, Europe/London 等 # 支持的时区格式:Asia/Shanghai, America/New_York, Europe/London 等
# 默认:Asia/Shanghai # 默认:Asia/Shanghai
@ -407,7 +405,7 @@ ASR:
# 3.模型可以选择gpt-4o-transcribe或GPT-4o mini Transcribe # 3.模型可以选择gpt-4o-transcribe或GPT-4o mini Transcribe
type: openai type: openai
api_key: 你的OpenAI API密钥 api_key: 你的OpenAI API密钥
base_url: https://api.openai.com/v1/audio/transcriptions base_url: https://api.openai.com/v1
model_name: gpt-4o-mini-transcribe model_name: gpt-4o-mini-transcribe
output_dir: tmp/ output_dir: tmp/
GroqASR: GroqASR:
@ -417,8 +415,8 @@ ASR:
# 2.创建api-key https://console.groq.com/keys # 2.创建api-key https://console.groq.com/keys
# 3.模型可以选择whisper-large-v3-turbo或whisper-large-v3(distil-whisper-large-v3-en仅支持英语转录) # 3.模型可以选择whisper-large-v3-turbo或whisper-large-v3(distil-whisper-large-v3-en仅支持英语转录)
type: openai type: openai
api_key: 你的Groq API密钥 api_key: your groq api key
base_url: https://api.groq.com/openai/v1/audio/transcriptions base_url: https://api.groq.com/openai/v1
model_name: whisper-large-v3-turbo model_name: whisper-large-v3-turbo
output_dir: tmp/ output_dir: tmp/
VoskASR: VoskASR:
@ -534,6 +532,11 @@ LLM:
model_name: glm-4-flash model_name: glm-4-flash
url: https://open.bigmodel.cn/api/paas/v4/ url: https://open.bigmodel.cn/api/paas/v4/
api_key: 你的chat-glm web key api_key: 你的chat-glm web key
GroqLLM:
type: openai
model_name: openai/gpt-oss-20b
base_url: https://api.groq.com/openai/v1
api_key: your groq api key
OllamaLLM: OllamaLLM:
# 定义LLM API类型 # 定义LLM API类型
type: ollama type: ollama
@ -759,10 +762,8 @@ TTS:
# 参照教程: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
output_dir: tmp/ output_dir: tmp/
response_format: wav response_format: pcm
reference_id: null reference_id: null
reference_audio: ["config/assets/wakeup_words.wav",]
reference_text: ["哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",]
normalize: true normalize: true
max_new_tokens: 1024 max_new_tokens: 1024
chunk_length: 200 chunk_length: 200
@ -774,8 +775,8 @@ TTS:
seed: null seed: null
channels: 1 channels: 1
rate: 44100 rate: 44100
api_key: "你的api_key" sample_rate: 16000
api_url: "http://127.0.0.1:8080/v1/tts" api_key: "your fish speech api key"
GPT_SOVITS_V2: GPT_SOVITS_V2:
# 定义TTS API类型 # 定义TTS API类型
#启动tts方法: #启动tts方法:
@ -1057,3 +1058,14 @@ TTS:
# volume: 50 # 音量:0-100 # volume: 50 # 音量:0-100
# speed: 50 # 语速:0-100 # speed: 50 # 语速:0-100
# pitch: 50 # 语调:0-100 # pitch: 50 # 语调:0-100
# ===============================================================================
# ============================= Module Selection ================================
# ===============================================================================
selected_module:
VAD: SileroVAD
ASR: GroqASR
LLM: GroqLLM
VLLM: ChatGLMVLLM
TTS: FishSpeech
Memory: memu
Intent: function_call

View file

@ -164,6 +164,71 @@ services:
retries: 3 retries: 3
start_period: 10s start_period: 10s
# ============================================================================
# live-agent-api Services
# ============================================================================
live-agent-postgres:
image: postgres:16-alpine
container_name: live-agent-postgres
environment:
POSTGRES_DB: live_agent
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
ports:
- "5432:5432"
volumes:
- ../live-agent-api/data/postgres:/var/lib/postgresql/data
- ../live-agent-api/init_db.sql:/docker-entrypoint-initdb.d/init_db.sql
networks:
- xiaozhi-network
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5
live-agent-minio:
image: minio/minio:latest
container_name: live-agent-minio
command: server /data --console-address ":9001"
environment:
MINIO_ROOT_USER: minioadmin
MINIO_ROOT_PASSWORD: minioadmin
ports:
- "19000:9000"
- "19001:9001"
volumes:
- ../live-agent-api/data/minio:/data
networks:
- xiaozhi-network
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
interval: 10s
timeout: 5s
retries: 5
live-agent-api:
build:
context: ../live-agent-api
dockerfile: Dockerfile
container_name: live-agent-api
env_file:
- ../live-agent-api/.env
environment:
DATABASE_URL: postgresql+asyncpg://postgres:postgres@live-agent-postgres:5432/live_agent
S3_ENDPOINT_URL: http://live-agent-minio:9000
DEBUG: "True"
ports:
- "8080:8080"
networks:
- xiaozhi-network
depends_on:
live-agent-postgres:
condition: service_healthy
live-agent-minio:
condition: service_healthy
# ============================================================================ # ============================================================================
# Networks # Networks
# ============================================================================ # ============================================================================

View file

@ -29,7 +29,10 @@ handle_exit_intent_function_desc = {
def handle_exit_intent(conn, say_goodbye: str | None = None): def handle_exit_intent(conn, say_goodbye: str | None = None):
# 处理退出意图 # 处理退出意图
try: try:
if say_goodbye is None: if hasattr(conn, '_voice_closing') and conn._voice_closing:
say_goodbye = conn._voice_closing
else:
# 如果没有自定义结束语,使用默认的
say_goodbye = "再见,祝您生活愉快!" say_goodbye = "再见,祝您生活愉快!"
conn.close_after_chat = True conn.close_after_chat = True
logger.bind(tag=TAG).info(f"退出意图已处理:{say_goodbye}") logger.bind(tag=TAG).info(f"退出意图已处理:{say_goodbye}")

View file

@ -43,4 +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==2025.6.3
python-dotenv>=1.0.0

View file

@ -37,7 +37,7 @@ export async function webSocketConnect(otaUrl, config) {
// 添加认证参数(保持原有逻辑) // 添加认证参数(保持原有逻辑)
connUrl.searchParams.append('device-id', config.deviceId); connUrl.searchParams.append('device-id', config.deviceId);
connUrl.searchParams.append('client-id', config.clientId); connUrl.searchParams.append('client-id', config.clientId);
connUrl.searchParams.append('agent-id', config.agentId);
const wsurl = connUrl.toString() const wsurl = connUrl.toString()
log(`正在连接: ${wsurl}`, 'info'); log(`正在连接: ${wsurl}`, 'info');
@ -82,7 +82,8 @@ async function sendOTA(otaUrl, config) {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Device-Id': config.deviceId, 'Device-Id': config.deviceId,
'Client-Id': config.clientId 'Client-Id': config.clientId,
'Agent-Id': config.agentId
}, },
body: JSON.stringify({ body: JSON.stringify({
version: 0, version: 0,

View file

@ -275,6 +275,10 @@
<label for="token">认证Token:</label> <label for="token">认证Token:</label>
<input type="text" id="token" value="your-token1" placeholder="认证Token"> <input type="text" id="token" value="your-token1" placeholder="认证Token">
</div> </div>
<div class="config-item">
<label for="agentId">Agent ID:</label>
<input type="text" id="agentId" value="agent_01KAGYH1ABYDV5JME6WEN45FBY" placeholder="Agent ID">
</div>
</div> </div>
</div> </div>
</div> </div>
@ -1791,12 +1795,14 @@
// 获取配置值 // 获取配置值
function getConfig() { function getConfig() {
const deviceMac = document.getElementById('deviceMac').value.trim(); const deviceMac = document.getElementById('deviceMac').value.trim();
log(`AgentID: ${document.getElementById('agentId').value.trim()}`, 'info');
return { return {
deviceId: deviceMac, // 使用MAC地址作为deviceId deviceId: deviceMac, // 使用MAC地址作为deviceId
deviceName: document.getElementById('deviceName').value.trim(), deviceName: document.getElementById('deviceName').value.trim(),
deviceMac: deviceMac, deviceMac: deviceMac,
clientId: document.getElementById('clientId').value.trim(), clientId: document.getElementById('clientId').value.trim(),
token: document.getElementById('token').value.trim() token: document.getElementById('token').value.trim(),
agentId: document.getElementById('agentId').value.trim()
}; };
} }