feat: create agent with template_id && filter template that has been created

This commit is contained in:
Harold 2025-12-17 13:51:09 +08:00
parent fc715cc00e
commit 4116c34758
8 changed files with 107 additions and 14 deletions

View file

@ -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())

View file

@ -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]})

View file

@ -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,

View file

@ -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

View file

@ -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()

View file

@ -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()

View file

@ -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)