feat: send greeting message to users only when user first chat with this character firstly today

This commit is contained in:
Harold 2025-12-17 11:29:57 +08:00
parent 5dbdc26171
commit fc715cc00e
4 changed files with 122 additions and 12 deletions

View file

@ -1,21 +1,51 @@
from fastapi import APIRouter, Depends import asyncio
from fastapi import APIRouter, Depends, Query
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 infra.fishaudio import get_fish_audio
from services.agent_service import agent_service from services.agent_service import agent_service
from services.device_service import device_service from services.device_service import device_service
from services.chat_service import chat_service
from utils.response import success_response from utils.response import success_response
from schemas.agent import AgentConfigResponse from schemas.agent import AgentConfigResponse
from schemas.device import DefaultAgentResponse, DeviceAgentResolveResponse from schemas.device import DefaultAgentResponse, DeviceAgentResolveResponse
from fastapi import Query
router = APIRouter() 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") @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,
tz_offset: str = Query(default="UTC+0", description="Client timezone offset, e.g. UTC+8, UTC-7"),
db: AsyncSession = Depends(get_db), db: AsyncSession = Depends(get_db),
fish_client = Depends(get_fish_audio) fish_client = Depends(get_fish_audio)
): ):
@ -29,25 +59,42 @@ async def get_agent_config(
Flow: Flow:
1. Get agent config by agent_id 1. Get agent config by agent_id
2. If voice_id exists, fetch voice info from Fish Audio 2. Parallel fetch: Fish Audio voice language + today's message check
3. Extract language and merge into response 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 # Step 1: Get agent config
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)
# Step 2: If voice_id exists, fetch language from Fish Audio # Step 2: Parallel fetch - Fish Audio language and today's message check
language = None async def fetch_language():
if agent.voice_id: if not agent.voice_id:
return None
try: try:
fish_voice = await fish_client.voices.get(agent.voice_id) fish_voice = await fish_client.voices.get(agent.voice_id)
if fish_voice and hasattr(fish_voice, 'languages') and fish_voice.languages: if fish_voice and hasattr(fish_voice, 'languages') and fish_voice.languages:
# Fish Audio returns a list of languages, take the first one return fish_voice.languages[0] if isinstance(fish_voice.languages, list) else fish_voice.languages
language = fish_voice.languages[0] if isinstance(fish_voice.languages, list) else fish_voice.languages
except Exception as e: 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}") 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( response = AgentConfigResponse(
agent_id=agent.agent_id, agent_id=agent.agent_id,
name=agent.name, name=agent.name,
@ -56,9 +103,11 @@ async def get_agent_config(
instruction=agent.instruction, instruction=agent.instruction,
voice_opening=agent.voice_opening, voice_opening=agent.voice_opening,
voice_closing=agent.voice_closing, 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") @router.get("/devices/{device_id}/agent-by-wake", summary="Resolve agent by wake word or default")

View file

@ -206,3 +206,41 @@ class ChatMessage:
await db.commit() await db.commit()
return result.rowcount 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

View file

@ -80,4 +80,6 @@ class AgentConfigResponse(BaseModel):
instruction: str instruction: str
voice_opening: Optional[str] = None voice_opening: Optional[str] = None
voice_closing: 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)

View file

@ -188,6 +188,27 @@ class ChatService:
deleted_files=deleted_files 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 # Global singleton instance
chat_service = ChatService() chat_service = ChatService()