mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge pull request #24 from Plaud-AI/feat_config
feat: update device agent bind
This commit is contained in:
commit
4ea00f8b39
9 changed files with 112 additions and 100 deletions
|
|
@ -9,7 +9,7 @@ from services.agent_service import agent_service
|
||||||
from services.llm_service import llm_service
|
from services.llm_service import llm_service
|
||||||
from utils.response import success_response
|
from utils.response import success_response
|
||||||
from api.auth import get_current_user_id
|
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
|
from config import get_logger
|
||||||
import base64
|
import base64
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
|
|
@ -68,6 +68,23 @@ async def get_agent_detail(
|
||||||
return success_response(data=agent_response.model_dump())
|
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")
|
@router.post("", summary="Create Agent")
|
||||||
async def create_agent(
|
async def create_agent(
|
||||||
name: str = Form(...),
|
name: str = Form(...),
|
||||||
|
|
@ -76,6 +93,7 @@ async def create_agent(
|
||||||
voice_id: Optional[str] = Form(None),
|
voice_id: Optional[str] = Form(None),
|
||||||
voice_opening: Optional[str] = Form(None),
|
voice_opening: Optional[str] = Form(None),
|
||||||
voice_closing: Optional[str] = Form(None),
|
voice_closing: Optional[str] = Form(None),
|
||||||
|
wake_word: Optional[str] = Form(None),
|
||||||
avatar: Optional[UploadFile] = File(None),
|
avatar: Optional[UploadFile] = File(None),
|
||||||
current_user_id: str = Depends(get_current_user_id),
|
current_user_id: str = Depends(get_current_user_id),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
|
|
@ -92,6 +110,7 @@ async def create_agent(
|
||||||
voice_id=voice_id,
|
voice_id=voice_id,
|
||||||
voice_opening=voice_opening,
|
voice_opening=voice_opening,
|
||||||
voice_closing=voice_closing,
|
voice_closing=voice_closing,
|
||||||
|
wake_word=wake_word,
|
||||||
avatar=avatar
|
avatar=avatar
|
||||||
)
|
)
|
||||||
return success_response(data=agent.model_dump())
|
return success_response(data=agent.model_dump())
|
||||||
|
|
@ -106,6 +125,7 @@ async def update_agent(
|
||||||
instruction: Optional[str] = Form(None),
|
instruction: Optional[str] = Form(None),
|
||||||
voice_opening: Optional[str] = Form(None),
|
voice_opening: Optional[str] = Form(None),
|
||||||
voice_closing: Optional[str] = Form(None),
|
voice_closing: Optional[str] = Form(None),
|
||||||
|
wake_word: Optional[str] = Form(None),
|
||||||
avatar: Optional[UploadFile] = File(None),
|
avatar: Optional[UploadFile] = File(None),
|
||||||
current_user_id: str = Depends(get_current_user_id),
|
current_user_id: str = Depends(get_current_user_id),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
|
|
@ -123,6 +143,7 @@ async def update_agent(
|
||||||
instruction=instruction,
|
instruction=instruction,
|
||||||
voice_opening=voice_opening,
|
voice_opening=voice_opening,
|
||||||
voice_closing=voice_closing,
|
voice_closing=voice_closing,
|
||||||
|
wake_word=wake_word,
|
||||||
avatar=avatar
|
avatar=avatar
|
||||||
)
|
)
|
||||||
return success_response(data=agent.model_dump())
|
return success_response(data=agent.model_dump())
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,7 @@ from utils.response import success_response
|
||||||
from api.auth import get_current_user_id
|
from api.auth import get_current_user_id
|
||||||
from schemas.device import (
|
from schemas.device import (
|
||||||
DeviceBindRequest,
|
DeviceBindRequest,
|
||||||
DeviceAddAgentRequest,
|
DeviceAddAgentRequest
|
||||||
DeviceSetDefaultAgentRequest
|
|
||||||
)
|
)
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
@ -21,17 +20,15 @@ async def bind_device(
|
||||||
db: AsyncSession = Depends(get_db)
|
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
|
- If device exists but unbound, binds to current user
|
||||||
- First agent bound becomes default
|
|
||||||
"""
|
"""
|
||||||
device = await device_service.bind_device(
|
device = await device_service.bind_device(
|
||||||
db=db,
|
db=db,
|
||||||
owner_id=current_user_id,
|
owner_id=current_user_id,
|
||||||
sn=request.sn,
|
device_id=request.device_id
|
||||||
agent_id=request.agent_id
|
|
||||||
)
|
)
|
||||||
return success_response(data=device.model_dump())
|
return success_response(data=device.model_dump())
|
||||||
|
|
||||||
|
|
@ -108,19 +105,3 @@ async def remove_agent_from_device(
|
||||||
return success_response(data=device.model_dump())
|
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())
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -40,6 +40,7 @@ CREATE TABLE IF NOT EXISTS agents (
|
||||||
instruction TEXT NOT NULL,
|
instruction TEXT NOT NULL,
|
||||||
voice_opening TEXT,
|
voice_opening TEXT,
|
||||||
voice_closing TEXT,
|
voice_closing TEXT,
|
||||||
|
wake_word VARCHAR(50),
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
|
||||||
updated_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)
|
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.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_opening IS 'Opening message when conversation starts';
|
||||||
COMMENT ON COLUMN agents.voice_closing IS 'Closing message when conversation ends';
|
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 ====================
|
-- ==================== Table: voices ====================
|
||||||
-- Voice configuration table
|
-- 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 (
|
CREATE TABLE IF NOT EXISTS devices (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
device_id VARCHAR(50) UNIQUE NOT NULL,
|
device_id VARCHAR(50) UNIQUE NOT NULL,
|
||||||
sn VARCHAR(100) UNIQUE NOT NULL,
|
|
||||||
owner_id VARCHAR(50),
|
owner_id VARCHAR(50),
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
|
||||||
updated_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
|
-- 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_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);
|
CREATE INDEX IF NOT EXISTS idx_devices_owner_id ON devices(owner_id);
|
||||||
|
|
||||||
-- Comments for devices table
|
-- Comments for devices table
|
||||||
COMMENT ON TABLE devices IS 'Device registry for hardware devices';
|
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.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)';
|
COMMENT ON COLUMN devices.owner_id IS 'User ID of device owner (null if unbound)';
|
||||||
|
|
||||||
-- ==================== Table: agent_device_bindings ====================
|
-- ==================== Table: agent_device_bindings ====================
|
||||||
|
|
|
||||||
|
|
@ -36,6 +36,7 @@ class AgentModel(Base):
|
||||||
instruction: Mapped[str] = mapped_column(Text, nullable=False)
|
instruction: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
voice_opening: Mapped[str | None] = mapped_column(Text, nullable=True)
|
voice_opening: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
voice_closing: 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
|
# Timestamps
|
||||||
created_at: Mapped[datetime] = mapped_column(
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
|
@ -136,7 +137,8 @@ class Agent:
|
||||||
description: Optional[str] = None,
|
description: Optional[str] = None,
|
||||||
voice_id: Optional[str] = None,
|
voice_id: Optional[str] = None,
|
||||||
voice_opening: Optional[str] = None,
|
voice_opening: Optional[str] = None,
|
||||||
voice_closing: Optional[str] = None
|
voice_closing: Optional[str] = None,
|
||||||
|
wake_word: Optional[str] = None
|
||||||
) -> AgentModel:
|
) -> AgentModel:
|
||||||
"""Create a new agent"""
|
"""Create a new agent"""
|
||||||
agent = AgentModel(
|
agent = AgentModel(
|
||||||
|
|
@ -148,7 +150,8 @@ class Agent:
|
||||||
voice_id=voice_id,
|
voice_id=voice_id,
|
||||||
instruction=instruction,
|
instruction=instruction,
|
||||||
voice_opening=voice_opening,
|
voice_opening=voice_opening,
|
||||||
voice_closing=voice_closing
|
voice_closing=voice_closing,
|
||||||
|
wake_word=wake_word
|
||||||
)
|
)
|
||||||
db.add(agent)
|
db.add(agent)
|
||||||
await db.commit()
|
await db.commit()
|
||||||
|
|
@ -183,6 +186,32 @@ class Agent:
|
||||||
await db.commit()
|
await db.commit()
|
||||||
return result.rowcount > 0
|
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
|
@staticmethod
|
||||||
async def get_agents_with_latest_message(
|
async def get_agents_with_latest_message(
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,7 @@ class DeviceModel(Base):
|
||||||
# Device unique identifier (external)
|
# Device unique identifier (external)
|
||||||
device_id: Mapped[str] = mapped_column(String(50), unique=True, nullable=False)
|
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)
|
sn: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
|
||||||
|
|
||||||
# Owner user ID (null if unbound)
|
# Owner user ID (null if unbound)
|
||||||
|
|
@ -43,12 +43,11 @@ class DeviceModel(Base):
|
||||||
|
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index('idx_devices_device_id', 'device_id', unique=True),
|
Index('idx_devices_device_id', 'device_id', unique=True),
|
||||||
Index('idx_devices_sn', 'sn', unique=True),
|
|
||||||
Index('idx_devices_owner_id', 'owner_id'),
|
Index('idx_devices_owner_id', 'owner_id'),
|
||||||
)
|
)
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f"<DeviceModel(id={self.id}, device_id={self.device_id}, sn={self.sn})>"
|
return f"<DeviceModel(id={self.id}, device_id={self.device_id})>"
|
||||||
|
|
||||||
|
|
||||||
class AgentDeviceBindingModel(Base):
|
class AgentDeviceBindingModel(Base):
|
||||||
|
|
@ -100,12 +99,6 @@ class Device:
|
||||||
result = await db.execute(select(DeviceModel).where(DeviceModel.device_id == device_id))
|
result = await db.execute(select(DeviceModel).where(DeviceModel.device_id == device_id))
|
||||||
return result.scalar_one_or_none()
|
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
|
@staticmethod
|
||||||
async def get_by_owner(db: AsyncSession, owner_id: str) -> List[DeviceModel]:
|
async def get_by_owner(db: AsyncSession, owner_id: str) -> List[DeviceModel]:
|
||||||
"""Get all devices owned by a user"""
|
"""Get all devices owned by a user"""
|
||||||
|
|
@ -120,13 +113,11 @@ class Device:
|
||||||
async def create(
|
async def create(
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
device_id: str,
|
device_id: str,
|
||||||
sn: str,
|
|
||||||
owner_id: Optional[str] = None
|
owner_id: Optional[str] = None
|
||||||
) -> DeviceModel:
|
) -> DeviceModel:
|
||||||
"""Create a new device"""
|
"""Create a new device"""
|
||||||
device = DeviceModel(
|
device = DeviceModel(
|
||||||
device_id=device_id,
|
device_id=device_id,
|
||||||
sn=sn,
|
|
||||||
owner_id=owner_id
|
owner_id=owner_id
|
||||||
)
|
)
|
||||||
db.add(device)
|
db.add(device)
|
||||||
|
|
|
||||||
|
|
@ -32,12 +32,29 @@ class AgentResponse(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
|
||||||
|
wake_word: Optional[str] = None
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
from_attributes = True
|
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):
|
class AgentWithLatestMessage(BaseModel):
|
||||||
"""Agent with latest message for list view"""
|
"""Agent with latest message for list view"""
|
||||||
agent_id: str
|
agent_id: str
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,7 @@ from pydantic import BaseModel, Field
|
||||||
|
|
||||||
class DeviceBindRequest(BaseModel):
|
class DeviceBindRequest(BaseModel):
|
||||||
"""Request to bind a device"""
|
"""Request to bind a device"""
|
||||||
sn: str = Field(..., description="Device serial number")
|
device_id: str = Field(..., description="Device unique identifier")
|
||||||
agent_id: str = Field(..., description="Agent ID to bind")
|
|
||||||
|
|
||||||
|
|
||||||
class DeviceAddAgentRequest(BaseModel):
|
class DeviceAddAgentRequest(BaseModel):
|
||||||
|
|
@ -17,11 +16,6 @@ class DeviceAddAgentRequest(BaseModel):
|
||||||
is_default: bool = Field(default=False, description="Set as default agent")
|
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 ====================
|
# ==================== Response Schemas ====================
|
||||||
|
|
||||||
class AgentBindingResponse(BaseModel):
|
class AgentBindingResponse(BaseModel):
|
||||||
|
|
@ -37,7 +31,6 @@ class AgentBindingResponse(BaseModel):
|
||||||
class DeviceResponse(BaseModel):
|
class DeviceResponse(BaseModel):
|
||||||
"""Device response"""
|
"""Device response"""
|
||||||
device_id: str
|
device_id: str
|
||||||
sn: str
|
|
||||||
owner_id: Optional[str] = None
|
owner_id: Optional[str] = None
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
updated_at: datetime
|
updated_at: datetime
|
||||||
|
|
@ -49,7 +42,6 @@ class DeviceResponse(BaseModel):
|
||||||
class DeviceWithBindingsResponse(BaseModel):
|
class DeviceWithBindingsResponse(BaseModel):
|
||||||
"""Device with agent bindings"""
|
"""Device with agent bindings"""
|
||||||
device_id: str
|
device_id: str
|
||||||
sn: str
|
|
||||||
owner_id: Optional[str] = None
|
owner_id: Optional[str] = None
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
updated_at: datetime
|
updated_at: datetime
|
||||||
|
|
|
||||||
|
|
@ -118,6 +118,23 @@ class AgentService:
|
||||||
|
|
||||||
return agent
|
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(
|
async def create_agent(
|
||||||
self,
|
self,
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
|
|
@ -129,6 +146,7 @@ class AgentService:
|
||||||
voice_id: Optional[str] = None,
|
voice_id: Optional[str] = None,
|
||||||
voice_opening: Optional[str] = None,
|
voice_opening: Optional[str] = None,
|
||||||
voice_closing: Optional[str] = None,
|
voice_closing: Optional[str] = None,
|
||||||
|
wake_word: Optional[str] = None,
|
||||||
avatar: Optional[UploadFile] = None
|
avatar: Optional[UploadFile] = None
|
||||||
) -> AgentResponse:
|
) -> AgentResponse:
|
||||||
"""Create a new agent"""
|
"""Create a new agent"""
|
||||||
|
|
@ -151,7 +169,8 @@ class AgentService:
|
||||||
description=description,
|
description=description,
|
||||||
voice_id=voice_id,
|
voice_id=voice_id,
|
||||||
voice_opening=voice_opening,
|
voice_opening=voice_opening,
|
||||||
voice_closing=voice_closing
|
voice_closing=voice_closing,
|
||||||
|
wake_word=wake_word
|
||||||
)
|
)
|
||||||
|
|
||||||
return AgentResponse.model_validate(agent)
|
return AgentResponse.model_validate(agent)
|
||||||
|
|
@ -168,6 +187,7 @@ class AgentService:
|
||||||
instruction: Optional[str] = None,
|
instruction: Optional[str] = None,
|
||||||
voice_opening: Optional[str] = None,
|
voice_opening: Optional[str] = None,
|
||||||
voice_closing: Optional[str] = None,
|
voice_closing: Optional[str] = None,
|
||||||
|
wake_word: Optional[str] = None,
|
||||||
avatar: Optional[UploadFile] = None
|
avatar: Optional[UploadFile] = None
|
||||||
) -> AgentResponse:
|
) -> AgentResponse:
|
||||||
"""Update agent"""
|
"""Update agent"""
|
||||||
|
|
@ -194,6 +214,8 @@ class AgentService:
|
||||||
update_data['voice_opening'] = voice_opening
|
update_data['voice_opening'] = voice_opening
|
||||||
if voice_closing is not None:
|
if voice_closing is not None:
|
||||||
update_data['voice_closing'] = voice_closing
|
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)
|
# Upload new avatar if provided (using agent_id as filename)
|
||||||
# Note: Since we use agent_id as filename, uploading will automatically
|
# Note: Since we use agent_id as filename, uploading will automatically
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,6 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from repositories.device import Device, AgentDeviceBinding, DeviceModel
|
from repositories.device import Device, AgentDeviceBinding, DeviceModel
|
||||||
from repositories.agent import Agent
|
from repositories.agent import Agent
|
||||||
from utils.exceptions import NotFoundException, BadRequestException
|
from utils.exceptions import NotFoundException, BadRequestException
|
||||||
from utils.ulid import generate_device_id
|
|
||||||
from schemas.device import (
|
from schemas.device import (
|
||||||
DeviceResponse,
|
DeviceResponse,
|
||||||
DeviceWithBindingsResponse,
|
DeviceWithBindingsResponse,
|
||||||
|
|
@ -20,23 +19,14 @@ class DeviceService:
|
||||||
self,
|
self,
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
owner_id: str,
|
owner_id: str,
|
||||||
sn: str,
|
device_id: str
|
||||||
agent_id: str
|
|
||||||
) -> DeviceWithBindingsResponse:
|
) -> DeviceWithBindingsResponse:
|
||||||
"""
|
"""
|
||||||
Bind a device to user with an agent.
|
Bind a device to user by device_id.
|
||||||
If device exists but unbound, update owner and add binding.
|
If device exists but unbound, update owner.
|
||||||
If device doesn't exist, create it.
|
If device doesn't exist, create it.
|
||||||
"""
|
"""
|
||||||
# Verify agent exists and belongs to user
|
device = await Device.get_by_id(db, device_id)
|
||||||
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)
|
|
||||||
|
|
||||||
if device:
|
if device:
|
||||||
# Device exists
|
# Device exists
|
||||||
|
|
@ -45,19 +35,10 @@ class DeviceService:
|
||||||
|
|
||||||
# Update owner if not set
|
# Update owner if not set
|
||||||
if not device.owner_id:
|
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:
|
else:
|
||||||
# Create new device
|
# Create new device
|
||||||
device_id = generate_device_id()
|
device = await Device.create(db, device_id, owner_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)
|
|
||||||
|
|
||||||
return await self._build_device_with_bindings(db, device)
|
return await self._build_device_with_bindings(db, device)
|
||||||
|
|
||||||
|
|
@ -115,6 +96,10 @@ class DeviceService:
|
||||||
if agent.owner_id != owner_id:
|
if agent.owner_id != owner_id:
|
||||||
raise BadRequestException("Agent does not belong to you")
|
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
|
# Check if binding already exists
|
||||||
existing = await AgentDeviceBinding.get_binding(db, device_id, agent_id)
|
existing = await AgentDeviceBinding.get_binding(db, device_id, agent_id)
|
||||||
if existing:
|
if existing:
|
||||||
|
|
@ -155,30 +140,6 @@ class DeviceService:
|
||||||
|
|
||||||
return await self._build_device_with_bindings(db, device)
|
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(
|
async def _build_device_with_bindings(
|
||||||
self,
|
self,
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
|
|
@ -189,7 +150,6 @@ class DeviceService:
|
||||||
|
|
||||||
return DeviceWithBindingsResponse(
|
return DeviceWithBindingsResponse(
|
||||||
device_id=device.device_id,
|
device_id=device.device_id,
|
||||||
sn=device.sn,
|
|
||||||
owner_id=device.owner_id,
|
owner_id=device.owner_id,
|
||||||
created_at=device.created_at,
|
created_at=device.created_at,
|
||||||
updated_at=device.updated_at,
|
updated_at=device.updated_at,
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue