From fc715cc00ec62c487cebd8daccec97960f0a5a4a Mon Sep 17 00:00:00 2001 From: Harold Date: Wed, 17 Dec 2025 11:29:57 +0800 Subject: [PATCH 1/3] feat: send greeting message to users only when user first chat with this character firstly today --- main/live-agent-api/api/v1/internal.py | 73 ++++++++++++++++---- main/live-agent-api/repositories/chat.py | 38 ++++++++++ main/live-agent-api/schemas/agent.py | 2 + main/live-agent-api/services/chat_service.py | 21 ++++++ 4 files changed, 122 insertions(+), 12 deletions(-) diff --git a/main/live-agent-api/api/v1/internal.py b/main/live-agent-api/api/v1/internal.py index f83ad43db..8330c761b 100644 --- a/main/live-agent-api/api/v1/internal.py +++ b/main/live-agent-api/api/v1/internal.py @@ -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,25 +59,42 @@ 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, @@ -56,9 +103,11 @@ async def get_agent_config( 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") diff --git a/main/live-agent-api/repositories/chat.py b/main/live-agent-api/repositories/chat.py index 1e0c41c01..6125f7c32 100644 --- a/main/live-agent-api/repositories/chat.py +++ b/main/live-agent-api/repositories/chat.py @@ -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 + diff --git a/main/live-agent-api/schemas/agent.py b/main/live-agent-api/schemas/agent.py index 7dc8f0dfc..0c4b500c6 100644 --- a/main/live-agent-api/schemas/agent.py +++ b/main/live-agent-api/schemas/agent.py @@ -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) diff --git a/main/live-agent-api/services/chat_service.py b/main/live-agent-api/services/chat_service.py index f81a5af40..c4cf0e500 100644 --- a/main/live-agent-api/services/chat_service.py +++ b/main/live-agent-api/services/chat_service.py @@ -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() From 4116c3475876c29f04127ea33271ac4d057ee817 Mon Sep 17 00:00:00 2001 From: Harold Date: Wed, 17 Dec 2025 13:51:09 +0800 Subject: [PATCH 2/3] feat: create agent with template_id && filter template that has been created --- main/live-agent-api/api/v1/agents.py | 14 +++++-- main/live-agent-api/api/v1/templates.py | 10 ++++- main/live-agent-api/infra/database.py | 7 +++- ...sage_time.sql => 001_add_message_time.sql} | 0 .../002_add_template_id_to_agents.sql | 20 ++++++++++ main/live-agent-api/repositories/agent.py | 10 ++++- .../repositories/agent_template.py | 40 +++++++++++++++++++ main/live-agent-api/services/agent_service.py | 20 +++++++--- 8 files changed, 107 insertions(+), 14 deletions(-) rename main/live-agent-api/migrations/{add_message_time.sql => 001_add_message_time.sql} (100%) create mode 100644 main/live-agent-api/migrations/002_add_template_id_to_agents.sql diff --git a/main/live-agent-api/api/v1/agents.py b/main/live-agent-api/api/v1/agents.py index f90a87412..273a6b4aa 100644 --- a/main/live-agent-api/api/v1/agents.py +++ b/main/live-agent-api/api/v1/agents.py @@ -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()) diff --git a/main/live-agent-api/api/v1/templates.py b/main/live-agent-api/api/v1/templates.py index c31041f3d..0b77a2fc0 100644 --- a/main/live-agent-api/api/v1/templates.py +++ b/main/live-agent-api/api/v1/templates.py @@ -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]}) diff --git a/main/live-agent-api/infra/database.py b/main/live-agent-api/infra/database.py index fbf1e0ecc..3354d98c0 100644 --- a/main/live-agent-api/infra/database.py +++ b/main/live-agent-api/infra/database.py @@ -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, diff --git a/main/live-agent-api/migrations/add_message_time.sql b/main/live-agent-api/migrations/001_add_message_time.sql similarity index 100% rename from main/live-agent-api/migrations/add_message_time.sql rename to main/live-agent-api/migrations/001_add_message_time.sql diff --git a/main/live-agent-api/migrations/002_add_template_id_to_agents.sql b/main/live-agent-api/migrations/002_add_template_id_to_agents.sql new file mode 100644 index 000000000..a59c2b207 --- /dev/null +++ b/main/live-agent-api/migrations/002_add_template_id_to_agents.sql @@ -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 + diff --git a/main/live-agent-api/repositories/agent.py b/main/live-agent-api/repositories/agent.py index f13abeb58..f1453bc2e 100644 --- a/main/live-agent-api/repositories/agent.py +++ b/main/live-agent-api/repositories/agent.py @@ -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() diff --git a/main/live-agent-api/repositories/agent_template.py b/main/live-agent-api/repositories/agent_template.py index 0fffa7c37..8545ec56a 100644 --- a/main/live-agent-api/repositories/agent_template.py +++ b/main/live-agent-api/repositories/agent_template.py @@ -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() + diff --git a/main/live-agent-api/services/agent_service.py b/main/live-agent-api/services/agent_service.py index c6567a581..d9eedbb4d 100644 --- a/main/live-agent-api/services/agent_service.py +++ b/main/live-agent-api/services/agent_service.py @@ -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) From be7b9ff4482222bcb7289255530b0c478ecc5d58 Mon Sep 17 00:00:00 2001 From: Harold Date: Wed, 17 Dec 2025 17:37:15 +0800 Subject: [PATCH 3/3] feat: filter greeting --- main/live-agent-api/api/v1/internal.py | 1 - main/xiaozhi-server/core/connection.py | 15 ++++++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/main/live-agent-api/api/v1/internal.py b/main/live-agent-api/api/v1/internal.py index 8330c761b..9d386f816 100644 --- a/main/live-agent-api/api/v1/internal.py +++ b/main/live-agent-api/api/v1/internal.py @@ -101,7 +101,6 @@ async def get_agent_config( 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, diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 6b6d89e46..68b696363 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -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)