From fc715cc00ec62c487cebd8daccec97960f0a5a4a Mon Sep 17 00:00:00 2001 From: Harold Date: Wed, 17 Dec 2025 11:29:57 +0800 Subject: [PATCH] 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()