mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge pull request #52 from Plaud-AI/feat/demo
feat: filter template agent from list && control the greeting only once per day
This commit is contained in:
commit
6ea069c983
13 changed files with 239 additions and 32 deletions
|
|
@ -15,7 +15,8 @@ from config import get_logger
|
|||
import base64
|
||||
from fastapi import HTTPException
|
||||
|
||||
logger = get_logger(__name__)
|
||||
TAG = __name__
|
||||
logger = get_logger(TAG)
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
|
|
@ -84,12 +85,18 @@ async def create_agent(
|
|||
voice_opening: Optional[str] = Form(None),
|
||||
voice_closing: Optional[str] = Form(None),
|
||||
wake_word: Optional[str] = Form(None),
|
||||
template_id: Optional[str] = Form(None),
|
||||
avatar: Optional[UploadFile] = File(None),
|
||||
current_user_id: str = Depends(get_current_user_id),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
s3 = Depends(get_s3)
|
||||
):
|
||||
"""Create a new agent"""
|
||||
"""
|
||||
Create a new agent.
|
||||
|
||||
If creating from a template, pass the template_id to track the source template.
|
||||
"""
|
||||
logger.bind(tag=TAG).debug(f"Creating agent from template: {template_id}")
|
||||
agent = await agent_service.create_agent(
|
||||
db=db,
|
||||
s3=s3,
|
||||
|
|
@ -101,7 +108,8 @@ async def create_agent(
|
|||
voice_opening=voice_opening,
|
||||
voice_closing=voice_closing,
|
||||
wake_word=wake_word,
|
||||
avatar=avatar
|
||||
avatar=avatar,
|
||||
template_id=template_id
|
||||
)
|
||||
return success_response(data=agent.model_dump())
|
||||
|
||||
|
|
|
|||
|
|
@ -1,21 +1,51 @@
|
|||
from fastapi import APIRouter, Depends
|
||||
import asyncio
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from infra import get_db
|
||||
from infra.fishaudio import get_fish_audio
|
||||
from services.agent_service import agent_service
|
||||
from services.device_service import device_service
|
||||
from services.chat_service import chat_service
|
||||
from utils.response import success_response
|
||||
from schemas.agent import AgentConfigResponse
|
||||
from schemas.device import DefaultAgentResponse, DeviceAgentResolveResponse
|
||||
from fastapi import Query
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _parse_tz_offset(tz_offset: str) -> int:
|
||||
"""
|
||||
Parse timezone offset string to hours
|
||||
|
||||
Supports formats: "UTC+8", "UTC-7", "+8", "-5", "0"
|
||||
|
||||
Returns:
|
||||
Offset hours (positive for east, negative for west)
|
||||
"""
|
||||
if not tz_offset:
|
||||
return 0
|
||||
|
||||
tz_str = tz_offset.strip().upper()
|
||||
|
||||
# Remove "UTC" prefix if present
|
||||
if tz_str.startswith("UTC"):
|
||||
tz_str = tz_str[3:]
|
||||
|
||||
if not tz_str or tz_str in ("+0", "-0", "0"):
|
||||
return 0
|
||||
|
||||
try:
|
||||
return int(tz_str)
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
|
||||
@router.get("/agents/{agent_id}/config", summary="Get agent config for backend services")
|
||||
async def get_agent_config(
|
||||
agent_id: str,
|
||||
tz_offset: str = Query(default="UTC+0", description="Client timezone offset, e.g. UTC+8, UTC-7"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
fish_client = Depends(get_fish_audio)
|
||||
):
|
||||
|
|
@ -29,36 +59,54 @@ async def get_agent_config(
|
|||
|
||||
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
|
||||
2. Parallel fetch: Fish Audio voice language + today's message check
|
||||
3. Enable greeting only if no messages today (reduce user annoyance)
|
||||
"""
|
||||
# Parse timezone offset at API layer
|
||||
tz_offset_hours = _parse_tz_offset(tz_offset)
|
||||
|
||||
# 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:
|
||||
# Step 2: Parallel fetch - Fish Audio language and today's message check
|
||||
async def fetch_language():
|
||||
if not agent.voice_id:
|
||||
return None
|
||||
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
|
||||
return 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}")
|
||||
return None
|
||||
|
||||
# Step 3: Merge voice language into response
|
||||
async def check_has_messages_today():
|
||||
return await chat_service.has_messages_today(db=db, agent_id=agent_id, tz_offset_hours=tz_offset_hours)
|
||||
|
||||
# Execute both tasks in parallel
|
||||
language, has_messages_today = await asyncio.gather(
|
||||
fetch_language(),
|
||||
check_has_messages_today()
|
||||
)
|
||||
|
||||
# Step 3: Determine greeting behavior
|
||||
# Only enable greeting if no messages today (reduce repeated greeting annoyance)
|
||||
enable_greeting = not has_messages_today
|
||||
greeting = agent.voice_opening if enable_greeting else None
|
||||
|
||||
# Step 4: Build 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,
|
||||
enable_greeting=enable_greeting,
|
||||
greeting=greeting,
|
||||
)
|
||||
|
||||
return success_response(data=response.model_dump())
|
||||
return success_response(data=response.model_dump(exclude_none=True))
|
||||
|
||||
|
||||
@router.get("/devices/{device_id}/agent-by-wake", summary="Resolve agent by wake word or default")
|
||||
|
|
|
|||
|
|
@ -4,16 +4,22 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
from infra import get_db, get_s3
|
||||
from services.agent_service import agent_service
|
||||
from utils.response import success_response
|
||||
from api.auth import get_current_user_id
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("", summary="Get Agent Templates")
|
||||
async def get_templates(
|
||||
current_user_id: str = Depends(get_current_user_id),
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Get all agent templates"""
|
||||
templates = await agent_service.get_templates(db)
|
||||
"""
|
||||
Get available agent templates for the current user.
|
||||
|
||||
Templates that the user has already created agents from will be filtered out.
|
||||
"""
|
||||
templates = await agent_service.get_templates(db, user_id=current_user_id)
|
||||
return success_response(data={"templates": [t.model_dump() for t in templates]})
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,22 +1,25 @@
|
|||
"""
|
||||
Database infrastructure - MySQL connection and session management
|
||||
"""
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
||||
from sqlalchemy.orm import declarative_base
|
||||
|
||||
from config import settings
|
||||
|
||||
# Suppress SQLAlchemy engine logs (keep echo=True but only show WARNING+)
|
||||
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
"""Return current UTC time as timezone-aware datetime"""
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
# Create async engine with connection pool
|
||||
engine = create_async_engine(
|
||||
settings.DATABASE_URL,
|
||||
echo=settings.DEBUG,
|
||||
echo=True,
|
||||
pool_pre_ping=True,
|
||||
pool_size=10,
|
||||
max_overflow=20,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,20 @@
|
|||
-- Migration: Add template_id to agents table
|
||||
-- Purpose: Track which template an agent was created from, enabling template filtering
|
||||
|
||||
-- Step 1: Add template_id column to agents table
|
||||
ALTER TABLE agents ADD COLUMN IF NOT EXISTS template_id VARCHAR(50);
|
||||
|
||||
-- Step 2: Add index for efficient querying
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_template_id ON agents(template_id);
|
||||
|
||||
-- Step 3: Backfill historical data by matching agent name with template name
|
||||
-- This updates existing agents that were created from templates
|
||||
UPDATE agents a
|
||||
SET template_id = t.template_id
|
||||
FROM agent_templates t
|
||||
WHERE a.name = t.name
|
||||
AND a.template_id IS NULL;
|
||||
|
||||
-- Note: Foreign key constraint is intentionally omitted
|
||||
-- This allows templates to be deleted without affecting agents
|
||||
|
||||
|
|
@ -38,6 +38,9 @@ class AgentModel(Base):
|
|||
voice_closing: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
wake_word: Mapped[str | None] = mapped_column(String(50), nullable=True) # Required for device binding
|
||||
|
||||
# Template reference (nullable - not all agents come from templates)
|
||||
template_id: Mapped[str | None] = mapped_column(String(50), nullable=True)
|
||||
|
||||
# Timestamps
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
TIMESTAMP(timezone=True),
|
||||
|
|
@ -54,6 +57,7 @@ class AgentModel(Base):
|
|||
__table_args__ = (
|
||||
Index('idx_agents_agent_id', 'agent_id', unique=True),
|
||||
Index('idx_agents_owner_id', 'owner_id'),
|
||||
Index('idx_agents_template_id', 'template_id'),
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
|
|
@ -138,7 +142,8 @@ class Agent:
|
|||
voice_id: Optional[str] = None,
|
||||
voice_opening: Optional[str] = None,
|
||||
voice_closing: Optional[str] = None,
|
||||
wake_word: Optional[str] = None
|
||||
wake_word: Optional[str] = None,
|
||||
template_id: Optional[str] = None
|
||||
) -> AgentModel:
|
||||
"""Create a new agent"""
|
||||
agent = AgentModel(
|
||||
|
|
@ -151,7 +156,8 @@ class Agent:
|
|||
instruction=instruction,
|
||||
voice_opening=voice_opening,
|
||||
voice_closing=voice_closing,
|
||||
wake_word=wake_word
|
||||
wake_word=wake_word,
|
||||
template_id=template_id
|
||||
)
|
||||
db.add(agent)
|
||||
await db.commit()
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ from sqlalchemy.orm import Mapped, mapped_column
|
|||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from infra.database import Base, utc_now
|
||||
from repositories.agent import AgentModel
|
||||
|
||||
|
||||
# ==================== ORM Model ====================
|
||||
|
|
@ -99,3 +100,42 @@ class AgentTemplate:
|
|||
await db.refresh(template)
|
||||
return template
|
||||
|
||||
@staticmethod
|
||||
async def get_available_for_user(
|
||||
db: AsyncSession,
|
||||
user_id: str,
|
||||
limit: int = 10
|
||||
) -> List[AgentTemplateModel]:
|
||||
"""
|
||||
Get templates that haven't been used by the user yet.
|
||||
|
||||
Filters out templates where the user has already created an agent from.
|
||||
|
||||
Args:
|
||||
db: AsyncSession
|
||||
user_id: User ID to check against
|
||||
limit: Maximum number of templates to return
|
||||
|
||||
Returns:
|
||||
List of available templates for the user
|
||||
"""
|
||||
# Subquery: get template_ids that user has already used
|
||||
used_template_ids = (
|
||||
select(AgentModel.template_id)
|
||||
.where(
|
||||
AgentModel.owner_id == user_id,
|
||||
AgentModel.template_id.isnot(None)
|
||||
)
|
||||
.scalar_subquery()
|
||||
)
|
||||
|
||||
# Main query: get templates not in user's used list
|
||||
stmt = (
|
||||
select(AgentTemplateModel)
|
||||
.where(AgentTemplateModel.template_id.notin_(used_template_ids))
|
||||
.limit(limit)
|
||||
)
|
||||
|
||||
result = await db.execute(stmt)
|
||||
return result.scalars().all()
|
||||
|
||||
|
|
|
|||
|
|
@ -206,3 +206,41 @@ class ChatMessage:
|
|||
await db.commit()
|
||||
return result.rowcount
|
||||
|
||||
@staticmethod
|
||||
async def has_messages_today(
|
||||
db: AsyncSession,
|
||||
agent_id: str,
|
||||
tz_offset_hours: int = 0
|
||||
) -> bool:
|
||||
"""
|
||||
Check if agent has any messages today in user's local timezone
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
agent_id: Agent ID
|
||||
tz_offset_hours: Timezone offset in hours (e.g. 8 for UTC+8, -7 for UTC-7)
|
||||
|
||||
Returns:
|
||||
True if there are messages today (in user's local time)
|
||||
"""
|
||||
from sqlalchemy import func
|
||||
from datetime import timedelta
|
||||
|
||||
user_tz = timezone(timedelta(hours=tz_offset_hours))
|
||||
|
||||
# Get current time in user's timezone, then find start of their "today"
|
||||
now_user_local = datetime.now(user_tz)
|
||||
today_start_local = now_user_local.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
# Convert back to UTC for database query
|
||||
today_start_utc = today_start_local.astimezone(timezone.utc)
|
||||
|
||||
query = select(func.count()).select_from(ChatMessageModel).where(
|
||||
ChatMessageModel.agent_id == agent_id,
|
||||
ChatMessageModel.message_time >= today_start_utc
|
||||
)
|
||||
|
||||
result = await db.execute(query)
|
||||
count = result.scalar_one()
|
||||
return count > 0
|
||||
|
||||
|
|
|
|||
|
|
@ -80,4 +80,6 @@ class AgentConfigResponse(BaseModel):
|
|||
instruction: str
|
||||
voice_opening: Optional[str] = None
|
||||
voice_closing: Optional[str] = None
|
||||
enable_greeting: bool = True # Whether to play greeting (false if already chatted today)
|
||||
greeting: Optional[str] = None # Greeting text (same as voice_opening, only set when enabled)
|
||||
|
||||
|
|
|
|||
|
|
@ -18,9 +18,17 @@ from utils.ulid import generate_template_id
|
|||
class AgentService:
|
||||
"""Agent service layer"""
|
||||
|
||||
async def get_templates(self, db: AsyncSession) -> List[AgentTemplateResponse]:
|
||||
"""Get all agent templates"""
|
||||
templates = await AgentTemplate.get_all(db)
|
||||
async def get_templates(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
user_id: str
|
||||
) -> List[AgentTemplateResponse]:
|
||||
"""
|
||||
Get available agent templates for user.
|
||||
|
||||
Filters out templates that the user has already created agents from.
|
||||
"""
|
||||
templates = await AgentTemplate.get_available_for_user(db, user_id)
|
||||
return [AgentTemplateResponse.model_validate(t) for t in templates]
|
||||
|
||||
async def create_template(
|
||||
|
|
@ -192,7 +200,8 @@ class AgentService:
|
|||
voice_opening: Optional[str] = None,
|
||||
voice_closing: Optional[str] = None,
|
||||
wake_word: Optional[str] = None,
|
||||
avatar: Optional[UploadFile] = None
|
||||
avatar: Optional[UploadFile] = None,
|
||||
template_id: Optional[str] = None
|
||||
) -> AgentResponse:
|
||||
"""Create a new agent"""
|
||||
# Generate agent_id first
|
||||
|
|
@ -215,7 +224,8 @@ class AgentService:
|
|||
voice_id=voice_id,
|
||||
voice_opening=voice_opening,
|
||||
voice_closing=voice_closing,
|
||||
wake_word=wake_word
|
||||
wake_word=wake_word,
|
||||
template_id=template_id
|
||||
)
|
||||
|
||||
return AgentResponse.model_validate(agent)
|
||||
|
|
|
|||
|
|
@ -188,6 +188,27 @@ class ChatService:
|
|||
deleted_files=deleted_files
|
||||
)
|
||||
|
||||
async def has_messages_today(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
agent_id: str,
|
||||
tz_offset_hours: int = 0
|
||||
) -> bool:
|
||||
"""
|
||||
Check if agent has any messages today in user's local timezone
|
||||
|
||||
Used for greeting logic: skip greeting if user already chatted today
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
agent_id: Agent ID
|
||||
tz_offset_hours: Timezone offset in hours (e.g. 8 for UTC+8, -7 for UTC-7)
|
||||
|
||||
Returns:
|
||||
True if there are messages today (in user's local time)
|
||||
"""
|
||||
return await ChatMessageRepo.has_messages_today(db=db, agent_id=agent_id, tz_offset_hours=tz_offset_hours)
|
||||
|
||||
|
||||
# Global singleton instance
|
||||
chat_service = ChatService()
|
||||
|
|
|
|||
|
|
@ -181,7 +181,9 @@ class ConnectionHandler:
|
|||
|
||||
# agent-related configs
|
||||
self._instruction = None
|
||||
self._voice_opening = None
|
||||
self._greeting_config = {
|
||||
"enable_greeting": False,
|
||||
}
|
||||
self._voice_closing = None
|
||||
self._language = None
|
||||
|
||||
|
|
@ -511,8 +513,9 @@ class ConnectionHandler:
|
|||
if init_tts or init_llm:
|
||||
self._init_report_threads()
|
||||
|
||||
if self._voice_opening and self.tts:
|
||||
self.logger.bind(tag=TAG).info(f"send the opening message: {self._voice_opening}")
|
||||
if self.tts and self._greeting_config["enable_greeting"]:
|
||||
greeting = self._greeting_config["greeting"]
|
||||
self.logger.bind(tag=TAG).debug(f"send the opening message: {greeting}")
|
||||
|
||||
opening_sentence_id = str(uuid.uuid4().hex)
|
||||
message_tag = MessageTag.OPENING
|
||||
|
|
@ -528,7 +531,7 @@ class ConnectionHandler:
|
|||
sentence_id=str(uuid.uuid4().hex),
|
||||
sentence_type=SentenceType.MIDDLE,
|
||||
content_type=ContentType.TEXT,
|
||||
content_detail=self._voice_opening,
|
||||
content_detail=greeting,
|
||||
message_tag=message_tag,
|
||||
)
|
||||
)
|
||||
|
|
@ -1016,7 +1019,9 @@ class ConnectionHandler:
|
|||
if "TTS" in self.config and "FishDualStreamTTS" in self.config.get("TTS", {}):
|
||||
self.config["TTS"]["FishDualStreamTTS"]["reference_id"] = voice_id
|
||||
self._instruction = private_config.get("instruction", self._instruction)
|
||||
self._voice_opening = private_config.get("voice_opening", self._voice_opening)
|
||||
# greeting config
|
||||
self._greeting_config["enable_greeting"] = private_config.get("enable_greeting", False)
|
||||
self._greeting_config["greeting"] = private_config.get("greeting", None)
|
||||
self._voice_closing = private_config.get("voice_closing", self._voice_closing)
|
||||
self._language = private_config.get("language", self._language)
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue