From 4116c3475876c29f04127ea33271ac4d057ee817 Mon Sep 17 00:00:00 2001 From: Harold Date: Wed, 17 Dec 2025 13:51:09 +0800 Subject: [PATCH] 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)