diff --git a/main/live-agent-api/api/v1/templates.py b/main/live-agent-api/api/v1/templates.py index 5e4383af5..c31041f3d 100644 --- a/main/live-agent-api/api/v1/templates.py +++ b/main/live-agent-api/api/v1/templates.py @@ -1,7 +1,7 @@ -from fastapi import APIRouter, Depends +from fastapi import APIRouter, Depends, Form, File, UploadFile from sqlalchemy.ext.asyncio import AsyncSession -from infra import get_db +from infra import get_db, get_s3 from services.agent_service import agent_service from utils.response import success_response @@ -16,3 +16,40 @@ async def get_templates( templates = await agent_service.get_templates(db) return success_response(data={"templates": [t.model_dump() for t in templates]}) + +@router.post("", summary="Create Agent Template") +async def create_template( + name: str = Form(...), + description: str = Form(...), + voice_id: str = Form(...), + instruction: str = Form(...), + voice_opening: str = Form(...), + voice_closing: str = Form(...), + avatar: UploadFile = File(...), + db: AsyncSession = Depends(get_db), + s3 = Depends(get_s3) +): + """ + Create a new agent template (all fields required) + + - **name**: Template name + - **description**: Template description + - **voice_id**: Fish Audio voice ID + - **instruction**: System prompt for the agent + - **voice_opening**: Opening message + - **voice_closing**: Closing message + - **avatar**: Avatar image file + """ + template = await agent_service.create_template( + db=db, + s3=s3, + name=name, + description=description, + voice_id=voice_id, + instruction=instruction, + voice_opening=voice_opening, + voice_closing=voice_closing, + avatar=avatar + ) + return success_response(data=template.model_dump()) + diff --git a/main/live-agent-api/repositories/agent.py b/main/live-agent-api/repositories/agent.py index 012bb505a..636f490e7 100644 --- a/main/live-agent-api/repositories/agent.py +++ b/main/live-agent-api/repositories/agent.py @@ -1,10 +1,11 @@ -from datetime import datetime -from typing import Optional, List, Tuple -from sqlalchemy import String, Text, TIMESTAMP, ForeignKey, Index, select, delete +from datetime import datetime, timezone +from typing import Optional, List, Tuple, Any +from sqlalchemy import String, Text, TIMESTAMP, ForeignKey, Index, select, delete, func from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.ext.asyncio import AsyncSession from infra.database import Base, utc_now +from repositories.chat import ChatMessageModel # ==================== ORM Model ==================== @@ -182,3 +183,88 @@ class Agent: await db.commit() return result.rowcount > 0 + @staticmethod + async def get_agents_with_latest_message( + db: AsyncSession, + owner_id: str, + cursor: Optional[str] = None, + limit: int = 20 + ) -> Tuple[List[Tuple[Any, ...]], Optional[str], bool]: + """ + Get agents with their latest message, ordered by latest activity time + + Args: + db: Database session + owner_id: User ID + cursor: ISO datetime string of last item's sort_time + limit: Number of items to return + + Returns: + Tuple of (rows, next_cursor, has_more) + Each row contains: (AgentModel, latest_message_id, latest_message_role, + latest_message_content, latest_message_time, sort_time) + """ + # Subquery: get latest message per agent using DISTINCT ON + latest_msg_subq = ( + select( + ChatMessageModel.agent_id, + ChatMessageModel.message_id, + ChatMessageModel.role, + ChatMessageModel.content, + ChatMessageModel.created_at.label('message_time') + ) + .distinct(ChatMessageModel.agent_id) + .order_by(ChatMessageModel.agent_id, ChatMessageModel.message_id.desc()) + .subquery('latest_messages') + ) + + # Sort time: use message time if available, otherwise agent created_at + sort_time_expr = func.coalesce( + latest_msg_subq.c.message_time, + AgentModel.created_at + ) + + sort_time = sort_time_expr.label('sort_time') + + # Main query: join agents with latest messages + query = ( + select( + AgentModel, + latest_msg_subq.c.message_id.label('latest_message_id'), + latest_msg_subq.c.role.label('latest_message_role'), + latest_msg_subq.c.content.label('latest_message_content'), + latest_msg_subq.c.message_time.label('latest_message_time'), + sort_time + ) + .outerjoin(latest_msg_subq, AgentModel.agent_id == latest_msg_subq.c.agent_id) + .where(AgentModel.owner_id == owner_id) + ) + + # Apply cursor filter + if cursor: + try: + cursor_time = datetime.fromisoformat(cursor) + query = query.where(sort_time_expr < cursor_time) + except (ValueError, TypeError): + pass + + # Order by sort_time DESC, agent_id DESC for stable sorting + query = query.order_by(sort_time.desc(), AgentModel.agent_id.desc()).limit(limit + 1) + + result = await db.execute(query) + rows = result.all() + + # Check if there are more records + has_more = len(rows) > limit + if has_more: + rows = rows[:limit] + + # Generate next cursor from last item's sort_time + next_cursor = None + if has_more and rows: + last_sort_time = rows[-1].sort_time + if last_sort_time: + next_cursor = last_sort_time.replace(tzinfo=None).isoformat() + + return rows, next_cursor, has_more + diff --git a/main/live-agent-api/repositories/agent_template.py b/main/live-agent-api/repositories/agent_template.py index e0c0f4cad..0fffa7c37 100644 --- a/main/live-agent-api/repositories/agent_template.py +++ b/main/live-agent-api/repositories/agent_template.py @@ -71,3 +71,31 @@ class AgentTemplate: result = await db.execute(stmt) return result.scalars().all() + @staticmethod + async def create( + db: AsyncSession, + template_id: str, + name: str, + avatar_url: Optional[str] = None, + description: Optional[str] = None, + voice_id: Optional[str] = None, + instruction: Optional[str] = None, + voice_opening: Optional[str] = None, + voice_closing: Optional[str] = None + ) -> AgentTemplateModel: + """Create a new agent template""" + template = AgentTemplateModel( + template_id=template_id, + name=name, + avatar_url=avatar_url, + description=description, + voice_id=voice_id, + instruction=instruction, + voice_opening=voice_opening, + voice_closing=voice_closing + ) + db.add(template) + await db.commit() + await db.refresh(template) + return template + diff --git a/main/live-agent-api/schemas/agent.py b/main/live-agent-api/schemas/agent.py index 9b197aae6..64f018a19 100644 --- a/main/live-agent-api/schemas/agent.py +++ b/main/live-agent-api/schemas/agent.py @@ -1,7 +1,6 @@ from datetime import datetime from typing import Optional -from pydantic import BaseModel, Field -from fastapi import UploadFile +from pydantic import BaseModel # ==================== Template Schemas ==================== @@ -17,7 +16,6 @@ class AgentTemplateResponse(BaseModel): voice_opening: Optional[str] = None voice_closing: Optional[str] = None created_at: datetime - updated_at: datetime class Config: from_attributes = True @@ -40,9 +38,18 @@ class AgentResponse(BaseModel): from_attributes = True +class AgentWithLatestMessage(BaseModel): + """Agent with latest message for list view""" + agent_id: str + name: str + avatar_url: Optional[str] = None + last_activity_time: datetime # 最近活动时间 (消息时间 or agent创建时间) + latest_message_text: Optional[str] = None # 最新消息的文本内容 + + class AgentListResponse(BaseModel): """Agent list response with cursor-based pagination""" - agents: list[AgentResponse] + agents: list[AgentWithLatestMessage] next_cursor: Optional[str] = None has_more: bool = False diff --git a/main/live-agent-api/services/agent_service.py b/main/live-agent-api/services/agent_service.py index 29f69dcac..4a5478d18 100644 --- a/main/live-agent-api/services/agent_service.py +++ b/main/live-agent-api/services/agent_service.py @@ -9,8 +9,10 @@ from schemas.agent import ( AgentResponse, AgentListResponse, AgentTemplateResponse, - AgentConfigResponse + AgentConfigResponse, + AgentWithLatestMessage ) +from utils.ulid import generate_template_id class AgentService: """Agent service layer""" @@ -18,6 +20,38 @@ class AgentService: """Get all agent templates""" templates = await AgentTemplate.get_all(db) return [AgentTemplateResponse.model_validate(t) for t in templates] + + async def create_template( + self, + db: AsyncSession, + s3, + name: str, + description: str, + voice_id: str, + instruction: str, + voice_opening: str, + voice_closing: str, + avatar: UploadFile + ) -> AgentTemplateResponse: + """Create a new agent template (all fields required)""" + # Generate template_id + template_id = generate_template_id() + + # Upload avatar + avatar_url = await FileRepository.upload_avatar(s3, avatar, template_id) + + template = await AgentTemplate.create( + db=db, + template_id=template_id, + name=name, + avatar_url=avatar_url, + description=description, + voice_id=voice_id, + instruction=instruction, + voice_opening=voice_opening, + voice_closing=voice_closing + ) + return AgentTemplateResponse.model_validate(template) async def get_agent_list( self, @@ -27,27 +61,47 @@ class AgentService: page_size: int = 10 ) -> AgentListResponse: """ - Get user's agent list with cursor-based pagination + Get user's agent list with cursor-based pagination, ordered by latest message time Args: db: Database session owner_id: User ID - cursor: Pagination cursor (ISO datetime string) + cursor: Pagination cursor (ISO datetime string of sort_time) page_size: Number of items per page Returns: - AgentListResponse with agents, next_cursor, and has_more + AgentListResponse with agents (including latest message), next_cursor, and has_more """ - agents, next_cursor, has_more = await Agent.get_agents_by_owner( + rows, next_cursor, has_more = await Agent.get_agents_with_latest_message( db, owner_id=owner_id, cursor=cursor, limit=page_size ) - agent_responses = [AgentResponse.model_validate(a) for a in agents] + # Process rows into response format + agents = [] + for row in rows: + agent = row[0] # AgentModel instance + + # Extract text content from latest message if exists + latest_message_text = None + if row.latest_message_content: + for item in row.latest_message_content: + if item.get('message_type') == 'text': + latest_message_text = item.get('message_content') + break + + agents.append(AgentWithLatestMessage( + agent_id=agent.agent_id, + name=agent.name, + avatar_url=agent.avatar_url, + last_activity_time=row.sort_time, + latest_message_text=latest_message_text + )) + return AgentListResponse( - agents=agent_responses, + agents=agents, next_cursor=next_cursor, has_more=has_more )