diff --git a/main/live-agent-api/api/v1/agents.py b/main/live-agent-api/api/v1/agents.py index 341b07a74..013ad4084 100644 --- a/main/live-agent-api/api/v1/agents.py +++ b/main/live-agent-api/api/v1/agents.py @@ -9,7 +9,7 @@ from services.agent_service import agent_service from services.llm_service import llm_service from utils.response import success_response from api.auth import get_current_user_id -from schemas.agent import AgentResponse +from schemas.agent import AgentResponse, BindableAgentResponse, BindableAgentListResponse from config import get_logger import base64 from fastapi import HTTPException @@ -68,6 +68,23 @@ async def get_agent_detail( return success_response(data=agent_response.model_dump()) +@router.get("/bindable", summary="Get bindable agents for device") +async def get_bindable_agents( + current_user_id: str = Depends(get_current_user_id), + db: AsyncSession = Depends(get_db) +): + """ + Get agents that can be bound to device. + + Only agents with wake_word configured can be bound to device. + """ + agents = await agent_service.get_bindable_agents(db=db, owner_id=current_user_id) + response = BindableAgentListResponse( + agents=[BindableAgentResponse.model_validate(a) for a in agents] + ) + return success_response(data=response.model_dump()) + + @router.post("", summary="Create Agent") async def create_agent( name: str = Form(...), @@ -76,6 +93,7 @@ async def create_agent( voice_id: Optional[str] = Form(None), voice_opening: Optional[str] = Form(None), voice_closing: Optional[str] = Form(None), + wake_word: Optional[str] = Form(None), avatar: Optional[UploadFile] = File(None), current_user_id: str = Depends(get_current_user_id), db: AsyncSession = Depends(get_db), @@ -92,6 +110,7 @@ async def create_agent( voice_id=voice_id, voice_opening=voice_opening, voice_closing=voice_closing, + wake_word=wake_word, avatar=avatar ) return success_response(data=agent.model_dump()) @@ -106,6 +125,7 @@ async def update_agent( instruction: Optional[str] = Form(None), voice_opening: Optional[str] = Form(None), voice_closing: Optional[str] = Form(None), + wake_word: Optional[str] = Form(None), avatar: Optional[UploadFile] = File(None), current_user_id: str = Depends(get_current_user_id), db: AsyncSession = Depends(get_db), @@ -123,6 +143,7 @@ async def update_agent( instruction=instruction, voice_opening=voice_opening, voice_closing=voice_closing, + wake_word=wake_word, avatar=avatar ) return success_response(data=agent.model_dump()) diff --git a/main/live-agent-api/api/v1/devices.py b/main/live-agent-api/api/v1/devices.py index 5e5190bf2..ad20c6c18 100644 --- a/main/live-agent-api/api/v1/devices.py +++ b/main/live-agent-api/api/v1/devices.py @@ -7,8 +7,7 @@ from utils.response import success_response from api.auth import get_current_user_id from schemas.device import ( DeviceBindRequest, - DeviceAddAgentRequest, - DeviceSetDefaultAgentRequest + DeviceAddAgentRequest ) router = APIRouter() @@ -21,17 +20,15 @@ async def bind_device( db: AsyncSession = Depends(get_db) ): """ - Bind a device to user with an agent. + Bind a device to user by device_id. - - If device (SN) doesn't exist, creates it + - If device doesn't exist, creates it - If device exists but unbound, binds to current user - - First agent bound becomes default """ device = await device_service.bind_device( db=db, owner_id=current_user_id, - sn=request.sn, - agent_id=request.agent_id + device_id=request.device_id ) return success_response(data=device.model_dump()) @@ -108,19 +105,3 @@ async def remove_agent_from_device( return success_response(data=device.model_dump()) -@router.put("/{device_id}/default-agent", summary="Set default agent") -async def set_default_agent( - device_id: str, - request: DeviceSetDefaultAgentRequest, - current_user_id: str = Depends(get_current_user_id), - db: AsyncSession = Depends(get_db) -): - """Set an agent as default for device""" - device = await device_service.set_default_agent( - db=db, - owner_id=current_user_id, - device_id=device_id, - agent_id=request.agent_id - ) - return success_response(data=device.model_dump()) - diff --git a/main/live-agent-api/init_db.sql b/main/live-agent-api/init_db.sql index 1ea47d796..eff283b5b 100644 --- a/main/live-agent-api/init_db.sql +++ b/main/live-agent-api/init_db.sql @@ -40,6 +40,7 @@ CREATE TABLE IF NOT EXISTS agents ( instruction TEXT NOT NULL, voice_opening TEXT, voice_closing TEXT, + wake_word VARCHAR(50), created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), updated_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), CONSTRAINT fk_agents_owner FOREIGN KEY (owner_id) @@ -57,6 +58,7 @@ COMMENT ON COLUMN agents.owner_id IS 'User ID of the agent owner'; COMMENT ON COLUMN agents.instruction IS 'System prompt/instruction for the agent'; COMMENT ON COLUMN agents.voice_opening IS 'Opening message when conversation starts'; COMMENT ON COLUMN agents.voice_closing IS 'Closing message when conversation ends'; +COMMENT ON COLUMN agents.wake_word IS 'Wake word for device binding (required for device binding)'; -- ==================== Table: voices ==================== -- Voice configuration table @@ -153,7 +155,6 @@ COMMENT ON COLUMN chat_messages.created_at IS 'When message was stored in databa CREATE TABLE IF NOT EXISTS devices ( id SERIAL PRIMARY KEY, device_id VARCHAR(50) UNIQUE NOT NULL, - sn VARCHAR(100) UNIQUE NOT NULL, owner_id VARCHAR(50), created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), updated_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), @@ -163,13 +164,11 @@ CREATE TABLE IF NOT EXISTS devices ( -- Indexes for devices table CREATE UNIQUE INDEX IF NOT EXISTS idx_devices_device_id ON devices(device_id); -CREATE UNIQUE INDEX IF NOT EXISTS idx_devices_sn ON devices(sn); CREATE INDEX IF NOT EXISTS idx_devices_owner_id ON devices(owner_id); -- Comments for devices table COMMENT ON TABLE devices IS 'Device registry for hardware devices'; COMMENT ON COLUMN devices.device_id IS 'External unique identifier (ULID)'; -COMMENT ON COLUMN devices.sn IS 'Hardware serial number (globally unique)'; COMMENT ON COLUMN devices.owner_id IS 'User ID of device owner (null if unbound)'; -- ==================== Table: agent_device_bindings ==================== diff --git a/main/live-agent-api/repositories/agent.py b/main/live-agent-api/repositories/agent.py index 4d5e1c650..c4a4d5a91 100644 --- a/main/live-agent-api/repositories/agent.py +++ b/main/live-agent-api/repositories/agent.py @@ -36,6 +36,7 @@ class AgentModel(Base): instruction: Mapped[str] = mapped_column(Text, nullable=False) voice_opening: Mapped[str | None] = mapped_column(Text, nullable=True) 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 # Timestamps created_at: Mapped[datetime] = mapped_column( @@ -136,7 +137,8 @@ class Agent: description: Optional[str] = None, voice_id: Optional[str] = None, voice_opening: Optional[str] = None, - voice_closing: Optional[str] = None + voice_closing: Optional[str] = None, + wake_word: Optional[str] = None ) -> AgentModel: """Create a new agent""" agent = AgentModel( @@ -148,7 +150,8 @@ class Agent: voice_id=voice_id, instruction=instruction, voice_opening=voice_opening, - voice_closing=voice_closing + voice_closing=voice_closing, + wake_word=wake_word ) db.add(agent) await db.commit() @@ -183,6 +186,32 @@ class Agent: await db.commit() return result.rowcount > 0 + @staticmethod + async def get_bindable_agents( + db: AsyncSession, + owner_id: str + ) -> List[AgentModel]: + """ + Get agents that can be bound to device (must have wake_word configured) + + Args: + db: Database session + owner_id: User ID + + Returns: + List of agents with wake_word configured + """ + result = await db.execute( + select(AgentModel) + .where( + AgentModel.owner_id == owner_id, + AgentModel.wake_word.isnot(None), + AgentModel.wake_word != '' + ) + .order_by(AgentModel.created_at.desc()) + ) + return list(result.scalars().all()) + @staticmethod async def get_agents_with_latest_message( db: AsyncSession, diff --git a/main/live-agent-api/repositories/device.py b/main/live-agent-api/repositories/device.py index b70364dec..2e61aebc4 100644 --- a/main/live-agent-api/repositories/device.py +++ b/main/live-agent-api/repositories/device.py @@ -18,7 +18,7 @@ class DeviceModel(Base): # Device unique identifier (external) device_id: Mapped[str] = mapped_column(String(50), unique=True, nullable=False) - # Hardware serial number (globally unique) + # Device serial number sn: Mapped[str] = mapped_column(String(100), unique=True, nullable=False) # Owner user ID (null if unbound) @@ -43,12 +43,11 @@ class DeviceModel(Base): __table_args__ = ( Index('idx_devices_device_id', 'device_id', unique=True), - Index('idx_devices_sn', 'sn', unique=True), Index('idx_devices_owner_id', 'owner_id'), ) def __repr__(self): - return f"" + return f"" class AgentDeviceBindingModel(Base): @@ -100,12 +99,6 @@ class Device: result = await db.execute(select(DeviceModel).where(DeviceModel.device_id == device_id)) return result.scalar_one_or_none() - @staticmethod - async def get_by_sn(db: AsyncSession, sn: str) -> Optional[DeviceModel]: - """Get device by SN""" - result = await db.execute(select(DeviceModel).where(DeviceModel.sn == sn)) - return result.scalar_one_or_none() - @staticmethod async def get_by_owner(db: AsyncSession, owner_id: str) -> List[DeviceModel]: """Get all devices owned by a user""" @@ -120,13 +113,11 @@ class Device: async def create( db: AsyncSession, device_id: str, - sn: str, owner_id: Optional[str] = None ) -> DeviceModel: """Create a new device""" device = DeviceModel( device_id=device_id, - sn=sn, owner_id=owner_id ) db.add(device) diff --git a/main/live-agent-api/schemas/agent.py b/main/live-agent-api/schemas/agent.py index 64f018a19..7dc8f0dfc 100644 --- a/main/live-agent-api/schemas/agent.py +++ b/main/live-agent-api/schemas/agent.py @@ -32,12 +32,29 @@ class AgentResponse(BaseModel): instruction: str voice_opening: Optional[str] = None voice_closing: Optional[str] = None + wake_word: Optional[str] = None created_at: datetime class Config: from_attributes = True +class BindableAgentResponse(BaseModel): + """Agent that can be bound to device (has wake_word)""" + agent_id: str + name: str + avatar_url: Optional[str] = None + wake_word: str # Required for bindable agents + + class Config: + from_attributes = True + + +class BindableAgentListResponse(BaseModel): + """List of agents that can be bound to device""" + agents: list[BindableAgentResponse] + + class AgentWithLatestMessage(BaseModel): """Agent with latest message for list view""" agent_id: str diff --git a/main/live-agent-api/schemas/device.py b/main/live-agent-api/schemas/device.py index 3ffbe026e..6f0c32c96 100644 --- a/main/live-agent-api/schemas/device.py +++ b/main/live-agent-api/schemas/device.py @@ -7,8 +7,7 @@ from pydantic import BaseModel, Field class DeviceBindRequest(BaseModel): """Request to bind a device""" - sn: str = Field(..., description="Device serial number") - agent_id: str = Field(..., description="Agent ID to bind") + device_id: str = Field(..., description="Device unique identifier") class DeviceAddAgentRequest(BaseModel): @@ -17,11 +16,6 @@ class DeviceAddAgentRequest(BaseModel): is_default: bool = Field(default=False, description="Set as default agent") -class DeviceSetDefaultAgentRequest(BaseModel): - """Request to set default agent""" - agent_id: str = Field(..., description="Agent ID to set as default") - - # ==================== Response Schemas ==================== class AgentBindingResponse(BaseModel): @@ -37,7 +31,6 @@ class AgentBindingResponse(BaseModel): class DeviceResponse(BaseModel): """Device response""" device_id: str - sn: str owner_id: Optional[str] = None created_at: datetime updated_at: datetime @@ -49,7 +42,6 @@ class DeviceResponse(BaseModel): class DeviceWithBindingsResponse(BaseModel): """Device with agent bindings""" device_id: str - sn: str owner_id: Optional[str] = None created_at: datetime updated_at: datetime diff --git a/main/live-agent-api/services/agent_service.py b/main/live-agent-api/services/agent_service.py index 4a5478d18..48515519d 100644 --- a/main/live-agent-api/services/agent_service.py +++ b/main/live-agent-api/services/agent_service.py @@ -118,6 +118,23 @@ class AgentService: return agent + async def get_bindable_agents( + self, + db: AsyncSession, + owner_id: str + ) -> List[AgentModel]: + """ + Get agents that can be bound to device (must have wake_word configured) + + Args: + db: Database session + owner_id: User ID + + Returns: + List of agents with wake_word configured + """ + return await Agent.get_bindable_agents(db, owner_id) + async def create_agent( self, db: AsyncSession, @@ -129,6 +146,7 @@ class AgentService: voice_id: Optional[str] = None, voice_opening: Optional[str] = None, voice_closing: Optional[str] = None, + wake_word: Optional[str] = None, avatar: Optional[UploadFile] = None ) -> AgentResponse: """Create a new agent""" @@ -151,7 +169,8 @@ class AgentService: description=description, voice_id=voice_id, voice_opening=voice_opening, - voice_closing=voice_closing + voice_closing=voice_closing, + wake_word=wake_word ) return AgentResponse.model_validate(agent) @@ -168,6 +187,7 @@ class AgentService: instruction: Optional[str] = None, voice_opening: Optional[str] = None, voice_closing: Optional[str] = None, + wake_word: Optional[str] = None, avatar: Optional[UploadFile] = None ) -> AgentResponse: """Update agent""" @@ -194,6 +214,8 @@ class AgentService: update_data['voice_opening'] = voice_opening if voice_closing is not None: update_data['voice_closing'] = voice_closing + if wake_word is not None: + update_data['wake_word'] = wake_word # Upload new avatar if provided (using agent_id as filename) # Note: Since we use agent_id as filename, uploading will automatically diff --git a/main/live-agent-api/services/device_service.py b/main/live-agent-api/services/device_service.py index b7ae47397..9ef1d2248 100644 --- a/main/live-agent-api/services/device_service.py +++ b/main/live-agent-api/services/device_service.py @@ -4,7 +4,6 @@ from sqlalchemy.ext.asyncio import AsyncSession from repositories.device import Device, AgentDeviceBinding, DeviceModel from repositories.agent import Agent from utils.exceptions import NotFoundException, BadRequestException -from utils.ulid import generate_device_id from schemas.device import ( DeviceResponse, DeviceWithBindingsResponse, @@ -20,23 +19,14 @@ class DeviceService: self, db: AsyncSession, owner_id: str, - sn: str, - agent_id: str + device_id: str ) -> DeviceWithBindingsResponse: """ - Bind a device to user with an agent. - If device exists but unbound, update owner and add binding. + Bind a device to user by device_id. + If device exists but unbound, update owner. If device doesn't exist, create it. """ - # Verify agent exists and belongs to user - agent = await Agent.get_by_id(db, agent_id) - if not agent: - raise NotFoundException("Agent not found") - if agent.owner_id != owner_id: - raise BadRequestException("Agent does not belong to you") - - # Check if device exists - device = await Device.get_by_sn(db, sn) + device = await Device.get_by_id(db, device_id) if device: # Device exists @@ -45,19 +35,10 @@ class DeviceService: # Update owner if not set if not device.owner_id: - device = await Device.update_owner(db, device.device_id, owner_id) + device = await Device.update_owner(db, device_id, owner_id) else: # Create new device - device_id = generate_device_id() - device = await Device.create(db, device_id, sn, owner_id) - - # Check if binding already exists - existing_binding = await AgentDeviceBinding.get_binding(db, device.device_id, agent_id) - if not existing_binding: - # Check if device has any bindings (for setting default) - bindings = await AgentDeviceBinding.get_bindings_by_device(db, device.device_id) - is_default = len(bindings) == 0 # First binding is default - await AgentDeviceBinding.create(db, device.device_id, agent_id, is_default) + device = await Device.create(db, device_id, owner_id) return await self._build_device_with_bindings(db, device) @@ -115,6 +96,10 @@ class DeviceService: if agent.owner_id != owner_id: raise BadRequestException("Agent does not belong to you") + # Verify agent has wake_word configured (required for device binding) + if not agent.wake_word: + raise BadRequestException("Agent must have a wake word configured to bind to device") + # Check if binding already exists existing = await AgentDeviceBinding.get_binding(db, device_id, agent_id) if existing: @@ -155,30 +140,6 @@ class DeviceService: return await self._build_device_with_bindings(db, device) - async def set_default_agent( - self, - db: AsyncSession, - owner_id: str, - device_id: str, - agent_id: str - ) -> DeviceWithBindingsResponse: - """Set an agent as default for device""" - device = await Device.get_by_id(db, device_id) - if not device: - raise NotFoundException("Device not found") - - if device.owner_id != owner_id: - raise BadRequestException("Device does not belong to you") - - # Check if binding exists - binding = await AgentDeviceBinding.get_binding(db, device_id, agent_id) - if not binding: - raise NotFoundException("Agent is not bound to this device") - - await AgentDeviceBinding.set_default(db, device_id, agent_id) - - return await self._build_device_with_bindings(db, device) - async def _build_device_with_bindings( self, db: AsyncSession, @@ -189,7 +150,6 @@ class DeviceService: return DeviceWithBindingsResponse( device_id=device.device_id, - sn=device.sn, owner_id=device.owner_id, created_at=device.created_at, updated_at=device.updated_at,