mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: agent review done && device and binding develop done
This commit is contained in:
parent
12c6311cd5
commit
86b6f76f60
31 changed files with 2779 additions and 245 deletions
|
|
@ -11,8 +11,8 @@ from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
from config.settings import settings
|
from config.settings import settings
|
||||||
from orm import init_database, close_database
|
from orm import init_database, close_database
|
||||||
from utils.id_generator import init_id_generator, close_id_generator
|
from utils import id_generator
|
||||||
from router import agent_router
|
from router import agent_router, device_router, binding_router
|
||||||
|
|
||||||
|
|
||||||
# Configure logging
|
# Configure logging
|
||||||
|
|
@ -30,9 +30,8 @@ async def lifespan(app: FastAPI):
|
||||||
# Startup
|
# Startup
|
||||||
logger.info("Starting Live Agent Dashboard API...")
|
logger.info("Starting Live Agent Dashboard API...")
|
||||||
|
|
||||||
# Initialize ID generator
|
# Initialize ID generator (singleton, automatically initialized on first use)
|
||||||
init_id_generator(instance_id=settings.instance_id)
|
logger.info(f"ID generator ready: {id_generator}")
|
||||||
logger.info(f"Initialized ID generator (instance={settings.instance_id})")
|
|
||||||
|
|
||||||
# Initialize database
|
# Initialize database
|
||||||
await init_database()
|
await init_database()
|
||||||
|
|
@ -44,7 +43,6 @@ async def lifespan(app: FastAPI):
|
||||||
# Shutdown
|
# Shutdown
|
||||||
logger.info("Shutting down Live Agent Dashboard API...")
|
logger.info("Shutting down Live Agent Dashboard API...")
|
||||||
await close_database()
|
await close_database()
|
||||||
close_id_generator()
|
|
||||||
logger.info("Application shutdown complete")
|
logger.info("Application shutdown complete")
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -74,6 +72,8 @@ app.add_middleware(
|
||||||
|
|
||||||
# Include routers
|
# Include routers
|
||||||
app.include_router(agent_router, prefix=settings.api_prefix)
|
app.include_router(agent_router, prefix=settings.api_prefix)
|
||||||
|
app.include_router(device_router, prefix=settings.api_prefix)
|
||||||
|
app.include_router(binding_router, prefix=settings.api_prefix)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
|
|
|
||||||
|
|
@ -10,13 +10,12 @@ from orm.base import (
|
||||||
get_db,
|
get_db,
|
||||||
init_database,
|
init_database,
|
||||||
close_database,
|
close_database,
|
||||||
|
get_session_maker,
|
||||||
)
|
)
|
||||||
|
|
||||||
from orm.agent import Agent, AgentRepository
|
from orm.agent import Agent, AgentRepository
|
||||||
|
from orm.device import Device, DeviceRepository
|
||||||
# Future imports:
|
from orm.binding import DeviceAgentBinding, DeviceAgentBindingRepository
|
||||||
# from orm.device import Device, DeviceRepository
|
|
||||||
# from orm.binding import Binding, BindingRepository
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
# Base infrastructure
|
# Base infrastructure
|
||||||
|
|
@ -24,15 +23,17 @@ __all__ = [
|
||||||
"get_db",
|
"get_db",
|
||||||
"init_database",
|
"init_database",
|
||||||
"close_database",
|
"close_database",
|
||||||
|
"get_session_maker",
|
||||||
|
|
||||||
# Agent domain
|
# Agent domain
|
||||||
"Agent",
|
"Agent",
|
||||||
"AgentRepository",
|
"AgentRepository",
|
||||||
|
|
||||||
# Future domains
|
# Device domain
|
||||||
# "Device",
|
"Device",
|
||||||
# "DeviceRepository",
|
"DeviceRepository",
|
||||||
# "Binding",
|
|
||||||
# "BindingRepository",
|
|
||||||
]
|
|
||||||
|
|
||||||
|
# Binding domain
|
||||||
|
"DeviceAgentBinding",
|
||||||
|
"DeviceAgentBindingRepository",
|
||||||
|
]
|
||||||
|
|
|
||||||
|
|
@ -17,13 +17,13 @@ class Agent(Base):
|
||||||
|
|
||||||
Represents a voice assistant agent with its configuration.
|
Represents a voice assistant agent with its configuration.
|
||||||
"""
|
"""
|
||||||
__tablename__ = "agents"
|
__tablename__ = "live_agents"
|
||||||
|
|
||||||
# Primary Key
|
# Primary Key
|
||||||
id: Mapped[str] = mapped_column(
|
id: Mapped[str] = mapped_column(
|
||||||
String(64),
|
String(64),
|
||||||
primary_key=True,
|
primary_key=True,
|
||||||
comment="Agent unique ID (Snowflake ID)"
|
comment="Agent unique ID"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Basic Information
|
# Basic Information
|
||||||
|
|
@ -33,13 +33,6 @@ class Agent(Base):
|
||||||
comment="Agent display name"
|
comment="Agent display name"
|
||||||
)
|
)
|
||||||
|
|
||||||
template: Mapped[str] = mapped_column(
|
|
||||||
String(100),
|
|
||||||
nullable=False,
|
|
||||||
default="blank",
|
|
||||||
comment="Agent template type (e.g., personal-assistant, blank)"
|
|
||||||
)
|
|
||||||
|
|
||||||
language: Mapped[str] = mapped_column(
|
language: Mapped[str] = mapped_column(
|
||||||
String(10),
|
String(10),
|
||||||
nullable=False,
|
nullable=False,
|
||||||
|
|
@ -96,7 +89,6 @@ class Agent(Base):
|
||||||
return {
|
return {
|
||||||
"id": self.id,
|
"id": self.id,
|
||||||
"name": self.name,
|
"name": self.name,
|
||||||
"template": self.template,
|
|
||||||
"language": self.language,
|
"language": self.language,
|
||||||
"firstMessage": self.first_message,
|
"firstMessage": self.first_message,
|
||||||
"systemPrompt": self.system_prompt,
|
"systemPrompt": self.system_prompt,
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ Encapsulates all database operations for Agent.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from sqlalchemy import select, func, or_
|
from sqlalchemy import select, func
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from orm.agent.model import Agent
|
from orm.agent.model import Agent
|
||||||
|
|
@ -43,18 +43,14 @@ class AgentRepository:
|
||||||
search: Optional[str] = None,
|
search: Optional[str] = None,
|
||||||
page: int = 1,
|
page: int = 1,
|
||||||
page_size: int = 20,
|
page_size: int = 20,
|
||||||
sort_by: str = "created_at",
|
|
||||||
sort_order: str = "desc",
|
|
||||||
) -> tuple[list[Agent], int]:
|
) -> tuple[list[Agent], int]:
|
||||||
"""
|
"""
|
||||||
Find all agents with filtering, pagination and sorting
|
Find all agents with filtering and pagination (sorted by creation time desc)
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
search: Search keyword (searches in name and system_prompt)
|
search: Search keyword (searches in name and system_prompt)
|
||||||
page: Page number (starting from 1)
|
page: Page number (starting from 1)
|
||||||
page_size: Number of items per page
|
page_size: Number of items per page
|
||||||
sort_by: Field to sort by
|
|
||||||
sort_order: Sort direction ('asc' or 'desc')
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Tuple of (agents list, total count)
|
Tuple of (agents list, total count)
|
||||||
|
|
@ -65,12 +61,7 @@ class AgentRepository:
|
||||||
# Apply search filter
|
# Apply search filter
|
||||||
if search:
|
if search:
|
||||||
search_pattern = f"%{search}%"
|
search_pattern = f"%{search}%"
|
||||||
stmt = stmt.where(
|
stmt = stmt.where(Agent.name.ilike(search_pattern))
|
||||||
or_(
|
|
||||||
Agent.name.ilike(search_pattern),
|
|
||||||
Agent.system_prompt.ilike(search_pattern),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
# Get total count
|
# Get total count
|
||||||
count_stmt = select(func.count()).select_from(stmt.subquery())
|
count_stmt = select(func.count()).select_from(stmt.subquery())
|
||||||
|
|
@ -78,11 +69,7 @@ class AgentRepository:
|
||||||
total = total_result.scalar_one()
|
total = total_result.scalar_one()
|
||||||
|
|
||||||
# Apply sorting
|
# Apply sorting
|
||||||
sort_column = getattr(Agent, sort_by, Agent.created_at)
|
stmt = stmt.order_by(Agent.created_at.desc())
|
||||||
if sort_order == "desc":
|
|
||||||
stmt = stmt.order_by(sort_column.desc())
|
|
||||||
else:
|
|
||||||
stmt = stmt.order_by(sort_column.asc())
|
|
||||||
|
|
||||||
# Apply pagination
|
# Apply pagination
|
||||||
offset = (page - 1) * page_size
|
offset = (page - 1) * page_size
|
||||||
|
|
|
||||||
11
main/live-agent-api/orm/binding/__init__.py
Normal file
11
main/live-agent-api/orm/binding/__init__.py
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
"""
|
||||||
|
DeviceAgentBinding ORM Package
|
||||||
|
|
||||||
|
Exports DeviceAgentBinding model and repository.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from .model import DeviceAgentBinding
|
||||||
|
from .repository import DeviceAgentBindingRepository
|
||||||
|
|
||||||
|
__all__ = ["DeviceAgentBinding", "DeviceAgentBindingRepository"]
|
||||||
|
|
||||||
93
main/live-agent-api/orm/binding/model.py
Normal file
93
main/live-agent-api/orm/binding/model.py
Normal file
|
|
@ -0,0 +1,93 @@
|
||||||
|
"""
|
||||||
|
DeviceAgentBinding ORM Model
|
||||||
|
|
||||||
|
Defines the DeviceAgentBinding database table structure for linking devices and agents.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from sqlalchemy import String, DateTime, ForeignKey, UniqueConstraint
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from orm.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceAgentBinding(Base):
|
||||||
|
"""
|
||||||
|
DeviceAgentBinding database model
|
||||||
|
|
||||||
|
Represents the binding relationship between a device and an agent.
|
||||||
|
Each device can only be bound to one agent at a time.
|
||||||
|
"""
|
||||||
|
__tablename__ = "device_agent_bindings"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint('device_id', name='uq_device_id'),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Primary Key
|
||||||
|
id: Mapped[str] = mapped_column(
|
||||||
|
String(64),
|
||||||
|
primary_key=True,
|
||||||
|
comment="Binding unique ID (ULID)"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Foreign Keys
|
||||||
|
device_id: Mapped[str] = mapped_column(
|
||||||
|
String(64),
|
||||||
|
ForeignKey("devices.id", ondelete="CASCADE"),
|
||||||
|
nullable=False,
|
||||||
|
unique=True,
|
||||||
|
index=True,
|
||||||
|
comment="Device ID (FK)"
|
||||||
|
)
|
||||||
|
|
||||||
|
agent_id: Mapped[str] = mapped_column(
|
||||||
|
String(64),
|
||||||
|
ForeignKey("agents.id", ondelete="CASCADE"),
|
||||||
|
nullable=False,
|
||||||
|
index=True,
|
||||||
|
comment="Agent ID (FK)"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Binding Information
|
||||||
|
status: Mapped[str] = mapped_column(
|
||||||
|
String(20),
|
||||||
|
nullable=False,
|
||||||
|
default="active",
|
||||||
|
comment="Binding status (active, inactive)"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Timestamps
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime,
|
||||||
|
nullable=False,
|
||||||
|
default=lambda: datetime.now(timezone.utc),
|
||||||
|
comment="Creation timestamp"
|
||||||
|
)
|
||||||
|
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime,
|
||||||
|
nullable=False,
|
||||||
|
default=lambda: datetime.now(timezone.utc),
|
||||||
|
onupdate=lambda: datetime.now(timezone.utc),
|
||||||
|
comment="Last update timestamp"
|
||||||
|
)
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f"<DeviceAgentBinding(id={self.id}, device_id={self.device_id}, agent_id={self.agent_id})>"
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
"""
|
||||||
|
Convert model to dictionary
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dictionary representation of the binding
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"id": self.id,
|
||||||
|
"deviceId": self.device_id,
|
||||||
|
"agentId": self.agent_id,
|
||||||
|
"status": self.status,
|
||||||
|
"createdAt": self.created_at.isoformat() if self.created_at else None,
|
||||||
|
"updatedAt": self.updated_at.isoformat() if self.updated_at else None,
|
||||||
|
}
|
||||||
|
|
||||||
183
main/live-agent-api/orm/binding/repository.py
Normal file
183
main/live-agent-api/orm/binding/repository.py
Normal file
|
|
@ -0,0 +1,183 @@
|
||||||
|
"""
|
||||||
|
DeviceAgentBinding Repository
|
||||||
|
|
||||||
|
Data access layer for DeviceAgentBinding entity.
|
||||||
|
Encapsulates all database operations for device-agent bindings.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Optional
|
||||||
|
from sqlalchemy import select, func, or_
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from orm.binding.model import DeviceAgentBinding
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceAgentBindingRepository:
|
||||||
|
"""Repository for DeviceAgentBinding data access operations"""
|
||||||
|
|
||||||
|
def __init__(self, db: AsyncSession):
|
||||||
|
"""
|
||||||
|
Initialize repository with database session
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db: SQLAlchemy async session
|
||||||
|
"""
|
||||||
|
self.db = db
|
||||||
|
|
||||||
|
async def find_by_id(self, binding_id: str) -> Optional[DeviceAgentBinding]:
|
||||||
|
"""
|
||||||
|
Find binding by ID
|
||||||
|
|
||||||
|
Args:
|
||||||
|
binding_id: Binding unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
DeviceAgentBinding instance or None if not found
|
||||||
|
"""
|
||||||
|
stmt = select(DeviceAgentBinding).where(DeviceAgentBinding.id == binding_id)
|
||||||
|
result = await self.db.execute(stmt)
|
||||||
|
return result.scalar_one_or_none()
|
||||||
|
|
||||||
|
async def find_by_device_id(self, device_id: str) -> Optional[DeviceAgentBinding]:
|
||||||
|
"""
|
||||||
|
Find binding by device ID
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Device unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
DeviceAgentBinding instance or None if not found
|
||||||
|
"""
|
||||||
|
stmt = select(DeviceAgentBinding).where(DeviceAgentBinding.device_id == device_id)
|
||||||
|
result = await self.db.execute(stmt)
|
||||||
|
return result.scalar_one_or_none()
|
||||||
|
|
||||||
|
async def find_by_agent_id(self, agent_id: str) -> list[DeviceAgentBinding]:
|
||||||
|
"""
|
||||||
|
Find all bindings for an agent
|
||||||
|
|
||||||
|
Args:
|
||||||
|
agent_id: Agent unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List of DeviceAgentBinding instances
|
||||||
|
"""
|
||||||
|
stmt = select(DeviceAgentBinding).where(DeviceAgentBinding.agent_id == agent_id)
|
||||||
|
result = await self.db.execute(stmt)
|
||||||
|
return list(result.scalars().all())
|
||||||
|
|
||||||
|
async def find_all(
|
||||||
|
self,
|
||||||
|
device_id: Optional[str] = None,
|
||||||
|
agent_id: Optional[str] = None,
|
||||||
|
status: Optional[str] = None,
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 20,
|
||||||
|
sort_by: str = "created_at",
|
||||||
|
sort_order: str = "desc",
|
||||||
|
) -> tuple[list[DeviceAgentBinding], int]:
|
||||||
|
"""
|
||||||
|
Find all bindings with filtering, pagination and sorting
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Filter by device ID
|
||||||
|
agent_id: Filter by agent ID
|
||||||
|
status: Filter by status
|
||||||
|
page: Page number (starting from 1)
|
||||||
|
page_size: Number of items per page
|
||||||
|
sort_by: Field to sort by
|
||||||
|
sort_order: Sort direction ('asc' or 'desc')
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (bindings list, total count)
|
||||||
|
"""
|
||||||
|
# Build base query
|
||||||
|
stmt = select(DeviceAgentBinding)
|
||||||
|
|
||||||
|
# Apply filters
|
||||||
|
if device_id:
|
||||||
|
stmt = stmt.where(DeviceAgentBinding.device_id == device_id)
|
||||||
|
|
||||||
|
if agent_id:
|
||||||
|
stmt = stmt.where(DeviceAgentBinding.agent_id == agent_id)
|
||||||
|
|
||||||
|
if status:
|
||||||
|
stmt = stmt.where(DeviceAgentBinding.status == status)
|
||||||
|
|
||||||
|
# Get total count
|
||||||
|
count_stmt = select(func.count()).select_from(stmt.subquery())
|
||||||
|
total_result = await self.db.execute(count_stmt)
|
||||||
|
total = total_result.scalar_one()
|
||||||
|
|
||||||
|
# Apply sorting
|
||||||
|
sort_column = getattr(DeviceAgentBinding, sort_by, DeviceAgentBinding.created_at)
|
||||||
|
if sort_order == "desc":
|
||||||
|
stmt = stmt.order_by(sort_column.desc())
|
||||||
|
else:
|
||||||
|
stmt = stmt.order_by(sort_column.asc())
|
||||||
|
|
||||||
|
# Apply pagination
|
||||||
|
offset = (page - 1) * page_size
|
||||||
|
stmt = stmt.offset(offset).limit(page_size)
|
||||||
|
|
||||||
|
# Execute query
|
||||||
|
result = await self.db.execute(stmt)
|
||||||
|
bindings = list(result.scalars().all())
|
||||||
|
|
||||||
|
return bindings, total
|
||||||
|
|
||||||
|
async def save(self, binding: DeviceAgentBinding) -> DeviceAgentBinding:
|
||||||
|
"""
|
||||||
|
Save or update binding
|
||||||
|
|
||||||
|
Args:
|
||||||
|
binding: DeviceAgentBinding instance to save
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Saved binding instance
|
||||||
|
"""
|
||||||
|
self.db.add(binding)
|
||||||
|
await self.db.flush()
|
||||||
|
await self.db.refresh(binding)
|
||||||
|
return binding
|
||||||
|
|
||||||
|
async def delete(self, binding: DeviceAgentBinding) -> None:
|
||||||
|
"""
|
||||||
|
Delete binding
|
||||||
|
|
||||||
|
Args:
|
||||||
|
binding: DeviceAgentBinding instance to delete
|
||||||
|
"""
|
||||||
|
await self.db.delete(binding)
|
||||||
|
await self.db.flush()
|
||||||
|
|
||||||
|
async def exists(self, binding_id: str) -> bool:
|
||||||
|
"""
|
||||||
|
Check if binding exists
|
||||||
|
|
||||||
|
Args:
|
||||||
|
binding_id: Binding unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if binding exists, False otherwise
|
||||||
|
"""
|
||||||
|
stmt = select(func.count()).where(DeviceAgentBinding.id == binding_id)
|
||||||
|
result = await self.db.execute(stmt)
|
||||||
|
count = result.scalar_one()
|
||||||
|
return count > 0
|
||||||
|
|
||||||
|
async def device_has_binding(self, device_id: str) -> bool:
|
||||||
|
"""
|
||||||
|
Check if device already has a binding
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Device unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if device has binding, False otherwise
|
||||||
|
"""
|
||||||
|
stmt = select(func.count()).where(DeviceAgentBinding.device_id == device_id)
|
||||||
|
result = await self.db.execute(stmt)
|
||||||
|
count = result.scalar_one()
|
||||||
|
return count > 0
|
||||||
|
|
||||||
11
main/live-agent-api/orm/device/__init__.py
Normal file
11
main/live-agent-api/orm/device/__init__.py
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
"""
|
||||||
|
Device ORM Package
|
||||||
|
|
||||||
|
Exports Device model and repository.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from .model import Device
|
||||||
|
from .repository import DeviceRepository
|
||||||
|
|
||||||
|
__all__ = ["Device", "DeviceRepository"]
|
||||||
|
|
||||||
130
main/live-agent-api/orm/device/model.py
Normal file
130
main/live-agent-api/orm/device/model.py
Normal file
|
|
@ -0,0 +1,130 @@
|
||||||
|
"""
|
||||||
|
Device ORM Model
|
||||||
|
|
||||||
|
Defines the Device database table structure and basic data operations.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from sqlalchemy import String, Text, DateTime, Boolean
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from orm.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Device(Base):
|
||||||
|
"""
|
||||||
|
Device database model
|
||||||
|
|
||||||
|
Represents a physical device that can be bound to agents.
|
||||||
|
"""
|
||||||
|
__tablename__ = "devices"
|
||||||
|
|
||||||
|
# Primary Key
|
||||||
|
id: Mapped[str] = mapped_column(
|
||||||
|
String(64),
|
||||||
|
primary_key=True,
|
||||||
|
comment="Device unique ID (ULID)"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Basic Information
|
||||||
|
name: Mapped[str] = mapped_column(
|
||||||
|
String(255),
|
||||||
|
nullable=False,
|
||||||
|
comment="Device display name"
|
||||||
|
)
|
||||||
|
|
||||||
|
device_id: Mapped[str] = mapped_column(
|
||||||
|
String(255),
|
||||||
|
nullable=False,
|
||||||
|
unique=True,
|
||||||
|
index=True,
|
||||||
|
comment="Device hardware ID"
|
||||||
|
)
|
||||||
|
|
||||||
|
model: Mapped[str] = mapped_column(
|
||||||
|
String(100),
|
||||||
|
nullable=True,
|
||||||
|
comment="Device model (e.g., PLAUD NOTE)"
|
||||||
|
)
|
||||||
|
|
||||||
|
firmware_version: Mapped[str] = mapped_column(
|
||||||
|
String(50),
|
||||||
|
nullable=True,
|
||||||
|
comment="Firmware version"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Device Status
|
||||||
|
status: Mapped[str] = mapped_column(
|
||||||
|
String(20),
|
||||||
|
nullable=False,
|
||||||
|
default="active",
|
||||||
|
comment="Device status (active, inactive, offline)"
|
||||||
|
)
|
||||||
|
|
||||||
|
is_online: Mapped[bool] = mapped_column(
|
||||||
|
Boolean,
|
||||||
|
nullable=False,
|
||||||
|
default=False,
|
||||||
|
comment="Whether device is currently online"
|
||||||
|
)
|
||||||
|
|
||||||
|
last_seen_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime,
|
||||||
|
nullable=True,
|
||||||
|
comment="Last seen timestamp"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Additional Information
|
||||||
|
description: Mapped[str] = mapped_column(
|
||||||
|
Text,
|
||||||
|
nullable=True,
|
||||||
|
comment="Device description"
|
||||||
|
)
|
||||||
|
|
||||||
|
extra_data: Mapped[str] = mapped_column(
|
||||||
|
Text,
|
||||||
|
nullable=True,
|
||||||
|
comment="Additional metadata (JSON format)"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Timestamps
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime,
|
||||||
|
nullable=False,
|
||||||
|
default=lambda: datetime.now(timezone.utc),
|
||||||
|
comment="Creation timestamp"
|
||||||
|
)
|
||||||
|
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime,
|
||||||
|
nullable=False,
|
||||||
|
default=lambda: datetime.now(timezone.utc),
|
||||||
|
onupdate=lambda: datetime.now(timezone.utc),
|
||||||
|
comment="Last update timestamp"
|
||||||
|
)
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f"<Device(id={self.id}, name={self.name}, device_id={self.device_id})>"
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
"""
|
||||||
|
Convert model to dictionary
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dictionary representation of the device
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"id": self.id,
|
||||||
|
"name": self.name,
|
||||||
|
"deviceId": self.device_id,
|
||||||
|
"model": self.model,
|
||||||
|
"firmwareVersion": self.firmware_version,
|
||||||
|
"status": self.status,
|
||||||
|
"isOnline": self.is_online,
|
||||||
|
"lastSeenAt": self.last_seen_at.isoformat() if self.last_seen_at else None,
|
||||||
|
"description": self.description,
|
||||||
|
"extraData": self.extra_data,
|
||||||
|
"createdAt": self.created_at.isoformat() if self.created_at else None,
|
||||||
|
"updatedAt": self.updated_at.isoformat() if self.updated_at else None,
|
||||||
|
}
|
||||||
|
|
||||||
172
main/live-agent-api/orm/device/repository.py
Normal file
172
main/live-agent-api/orm/device/repository.py
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
"""
|
||||||
|
Device Repository
|
||||||
|
|
||||||
|
Data access layer for Device entity.
|
||||||
|
Encapsulates all database operations for Device.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Optional
|
||||||
|
from sqlalchemy import select, func, or_
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from orm.device.model import Device
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceRepository:
|
||||||
|
"""Repository for Device data access operations"""
|
||||||
|
|
||||||
|
def __init__(self, db: AsyncSession):
|
||||||
|
"""
|
||||||
|
Initialize repository with database session
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db: SQLAlchemy async session
|
||||||
|
"""
|
||||||
|
self.db = db
|
||||||
|
|
||||||
|
async def find_by_id(self, device_id: str) -> Optional[Device]:
|
||||||
|
"""
|
||||||
|
Find device by ID
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Device unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Device instance or None if not found
|
||||||
|
"""
|
||||||
|
stmt = select(Device).where(Device.id == device_id)
|
||||||
|
result = await self.db.execute(stmt)
|
||||||
|
return result.scalar_one_or_none()
|
||||||
|
|
||||||
|
async def find_by_device_id(self, device_id: str) -> Optional[Device]:
|
||||||
|
"""
|
||||||
|
Find device by hardware device ID
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Device hardware ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Device instance or None if not found
|
||||||
|
"""
|
||||||
|
stmt = select(Device).where(Device.device_id == device_id)
|
||||||
|
result = await self.db.execute(stmt)
|
||||||
|
return result.scalar_one_or_none()
|
||||||
|
|
||||||
|
async def find_all(
|
||||||
|
self,
|
||||||
|
search: Optional[str] = None,
|
||||||
|
status: Optional[str] = None,
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 20,
|
||||||
|
sort_by: str = "created_at",
|
||||||
|
sort_order: str = "desc",
|
||||||
|
) -> tuple[list[Device], int]:
|
||||||
|
"""
|
||||||
|
Find all devices with filtering, pagination and sorting
|
||||||
|
|
||||||
|
Args:
|
||||||
|
search: Search keyword (searches in name and device_id)
|
||||||
|
status: Filter by status
|
||||||
|
page: Page number (starting from 1)
|
||||||
|
page_size: Number of items per page
|
||||||
|
sort_by: Field to sort by
|
||||||
|
sort_order: Sort direction ('asc' or 'desc')
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (devices list, total count)
|
||||||
|
"""
|
||||||
|
# Build base query
|
||||||
|
stmt = select(Device)
|
||||||
|
|
||||||
|
# Apply search filter
|
||||||
|
if search:
|
||||||
|
search_pattern = f"%{search}%"
|
||||||
|
stmt = stmt.where(
|
||||||
|
or_(
|
||||||
|
Device.name.ilike(search_pattern),
|
||||||
|
Device.device_id.ilike(search_pattern),
|
||||||
|
Device.model.ilike(search_pattern),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Apply status filter
|
||||||
|
if status:
|
||||||
|
stmt = stmt.where(Device.status == status)
|
||||||
|
|
||||||
|
# Get total count
|
||||||
|
count_stmt = select(func.count()).select_from(stmt.subquery())
|
||||||
|
total_result = await self.db.execute(count_stmt)
|
||||||
|
total = total_result.scalar_one()
|
||||||
|
|
||||||
|
# Apply sorting
|
||||||
|
sort_column = getattr(Device, sort_by, Device.created_at)
|
||||||
|
if sort_order == "desc":
|
||||||
|
stmt = stmt.order_by(sort_column.desc())
|
||||||
|
else:
|
||||||
|
stmt = stmt.order_by(sort_column.asc())
|
||||||
|
|
||||||
|
# Apply pagination
|
||||||
|
offset = (page - 1) * page_size
|
||||||
|
stmt = stmt.offset(offset).limit(page_size)
|
||||||
|
|
||||||
|
# Execute query
|
||||||
|
result = await self.db.execute(stmt)
|
||||||
|
devices = list(result.scalars().all())
|
||||||
|
|
||||||
|
return devices, total
|
||||||
|
|
||||||
|
async def save(self, device: Device) -> Device:
|
||||||
|
"""
|
||||||
|
Save or update device
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device: Device instance to save
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Saved device instance
|
||||||
|
"""
|
||||||
|
self.db.add(device)
|
||||||
|
await self.db.flush()
|
||||||
|
await self.db.refresh(device)
|
||||||
|
return device
|
||||||
|
|
||||||
|
async def delete(self, device: Device) -> None:
|
||||||
|
"""
|
||||||
|
Delete device
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device: Device instance to delete
|
||||||
|
"""
|
||||||
|
await self.db.delete(device)
|
||||||
|
await self.db.flush()
|
||||||
|
|
||||||
|
async def exists(self, device_id: str) -> bool:
|
||||||
|
"""
|
||||||
|
Check if device exists
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Device unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if device exists, False otherwise
|
||||||
|
"""
|
||||||
|
stmt = select(func.count()).where(Device.id == device_id)
|
||||||
|
result = await self.db.execute(stmt)
|
||||||
|
count = result.scalar_one()
|
||||||
|
return count > 0
|
||||||
|
|
||||||
|
async def device_id_exists(self, device_id: str) -> bool:
|
||||||
|
"""
|
||||||
|
Check if hardware device ID exists
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Device hardware ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if device_id exists, False otherwise
|
||||||
|
"""
|
||||||
|
stmt = select(func.count()).where(Device.device_id == device_id)
|
||||||
|
result = await self.db.execute(stmt)
|
||||||
|
count = result.scalar_one()
|
||||||
|
return count > 0
|
||||||
|
|
||||||
|
|
@ -13,7 +13,8 @@ dependencies = [
|
||||||
"openai>=1.54.0",
|
"openai>=1.54.0",
|
||||||
"python-dotenv>=1.0.0",
|
"python-dotenv>=1.0.0",
|
||||||
"httpx>=0.27.0",
|
"httpx>=0.27.0",
|
||||||
"snowflake-id>=1.0.2",
|
"python-ulid>=2.7.0",
|
||||||
|
"pyyaml>=6.0.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[dependency-groups]
|
[dependency-groups]
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,11 @@ FastAPI route handlers for all API endpoints.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from router.agent import router as agent_router
|
from router.agent import router as agent_router
|
||||||
|
from router.device import router as device_router
|
||||||
|
from router.binding import router as binding_router
|
||||||
|
|
||||||
__all__ = ["agent_router"]
|
__all__ = [
|
||||||
|
"agent_router",
|
||||||
|
"device_router",
|
||||||
|
"binding_router",
|
||||||
|
]
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,7 @@ from utils.response import (
|
||||||
error_response,
|
error_response,
|
||||||
paginated_response,
|
paginated_response,
|
||||||
)
|
)
|
||||||
|
from templates import TemplateLoader
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
@ -38,20 +39,16 @@ async def get_agent_list(
|
||||||
search: Annotated[str | None, Query(description="Search keyword")] = None,
|
search: Annotated[str | None, Query(description="Search keyword")] = None,
|
||||||
page: Annotated[int, Query(ge=1, description="Page number")] = 1,
|
page: Annotated[int, Query(ge=1, description="Page number")] = 1,
|
||||||
pageSize: Annotated[int, Query(ge=1, le=100, alias="pageSize", description="Items per page")] = 20,
|
pageSize: Annotated[int, Query(ge=1, le=100, alias="pageSize", description="Items per page")] = 20,
|
||||||
sortBy: Annotated[str, Query(alias="sortBy", description="Sort field")] = "createdAt",
|
|
||||||
sortOrder: Annotated[str, Query(alias="sortOrder", pattern="^(asc|desc)$", description="Sort order")] = "desc",
|
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> ApiResponse:
|
) -> ApiResponse:
|
||||||
"""
|
"""
|
||||||
Get Agent list with search, pagination and sorting
|
Get Agent list with search and pagination (sorted by creation time desc)
|
||||||
|
|
||||||
- **search**: Search keyword (searches in name and system prompt)
|
- **search**: Search keyword (searches in name and system prompt)
|
||||||
- **page**: Page number (starting from 1)
|
- **page**: Page number (starting from 1)
|
||||||
- **pageSize**: Number of items per page (1-100)
|
- **pageSize**: Number of items per page (1-100, default: 20)
|
||||||
- **sortBy**: Field to sort by (default: createdAt)
|
|
||||||
- **sortOrder**: Sort order - asc or desc (default: desc)
|
|
||||||
|
|
||||||
Returns paginated list of agents with total count.
|
Returns paginated list of agents sorted by creation time (newest first) with total count.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Create query object
|
# Create query object
|
||||||
|
|
@ -59,8 +56,6 @@ async def get_agent_list(
|
||||||
search=search,
|
search=search,
|
||||||
page=page,
|
page=page,
|
||||||
page_size=pageSize,
|
page_size=pageSize,
|
||||||
sort_by=sortBy,
|
|
||||||
sort_order=sortOrder,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Get service
|
# Get service
|
||||||
|
|
@ -154,6 +149,13 @@ async def create_agent(
|
||||||
code=201
|
code=201
|
||||||
)
|
)
|
||||||
|
|
||||||
|
except ValueError as e:
|
||||||
|
# Template validation errors
|
||||||
|
logger.warning(f"Validation error creating agent: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=str(e),
|
||||||
|
code=400
|
||||||
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error creating agent: {str(e)}")
|
logger.error(f"Error creating agent: {str(e)}")
|
||||||
return error_response(
|
return error_response(
|
||||||
|
|
@ -296,10 +298,19 @@ async def generate_system_prompt(
|
||||||
Generate system prompt using AI
|
Generate system prompt using AI
|
||||||
|
|
||||||
Request body:
|
Request body:
|
||||||
- **description**: Description of the agent's purpose (required)
|
- **description**: Description of the agent's purpose and requirements (required)
|
||||||
|
- **currentPrompt**: Existing system prompt to refine or build upon (optional)
|
||||||
|
|
||||||
Uses OpenAI to generate a professional system prompt based on the description.
|
Uses OpenAI to generate a professional system prompt that follows the 6-module structure:
|
||||||
Returns the generated prompt.
|
1. Personality - Agent's character and communication style
|
||||||
|
2. Environment - Context and operating setting
|
||||||
|
3. Tone - Language tone and interaction manner
|
||||||
|
4. Goal - Primary objectives and purposes
|
||||||
|
5. Guardrails - Rules, limitations, and ethical boundaries
|
||||||
|
6. Tools - Available capabilities and functions
|
||||||
|
|
||||||
|
If currentPrompt is provided, the AI will refine it based on the description.
|
||||||
|
Otherwise, it creates a new prompt from scratch.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
service = get_agent_service(db)
|
service = get_agent_service(db)
|
||||||
|
|
|
||||||
324
main/live-agent-api/router/binding.py
Normal file
324
main/live-agent-api/router/binding.py
Normal file
|
|
@ -0,0 +1,324 @@
|
||||||
|
"""
|
||||||
|
DeviceAgentBinding Router
|
||||||
|
|
||||||
|
API endpoints for Device-Agent binding management.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Annotated
|
||||||
|
from fastapi import APIRouter, Depends, Query
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from orm import get_db
|
||||||
|
from services.binding_service import BindingService, get_binding_service
|
||||||
|
from schemas.binding import (
|
||||||
|
BindingCreate,
|
||||||
|
BindingUpdate,
|
||||||
|
BindingResponse,
|
||||||
|
BindingListQuery,
|
||||||
|
)
|
||||||
|
from utils.response import (
|
||||||
|
ApiResponse,
|
||||||
|
success_response,
|
||||||
|
error_response,
|
||||||
|
paginated_response,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/binding", tags=["binding"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/")
|
||||||
|
async def get_binding_list(
|
||||||
|
deviceId: Annotated[str | None, Query(alias="deviceId", description="Filter by device ID")] = None,
|
||||||
|
agentId: Annotated[str | None, Query(alias="agentId", description="Filter by agent ID")] = None,
|
||||||
|
status: Annotated[str | None, Query(description="Filter by status")] = None,
|
||||||
|
page: Annotated[int, Query(ge=1, description="Page number")] = 1,
|
||||||
|
pageSize: Annotated[int, Query(ge=1, le=100, alias="pageSize", description="Items per page")] = 10,
|
||||||
|
sortBy: Annotated[str, Query(alias="sortBy", description="Sort field")] = "createdAt",
|
||||||
|
sortOrder: Annotated[str, Query(alias="sortOrder", pattern="^(asc|desc)$", description="Sort order")] = "desc",
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""
|
||||||
|
Get DeviceAgentBinding list with filtering, pagination and sorting
|
||||||
|
|
||||||
|
- **deviceId**: Filter by device ID
|
||||||
|
- **agentId**: Filter by agent ID
|
||||||
|
- **status**: Filter by status (active, inactive)
|
||||||
|
- **page**: Page number (starting from 1)
|
||||||
|
- **pageSize**: Number of items per page (1-100)
|
||||||
|
- **sortBy**: Field to sort by (default: createdAt)
|
||||||
|
- **sortOrder**: Sort order - asc or desc (default: desc)
|
||||||
|
|
||||||
|
Returns paginated list of bindings with total count.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# Create query object
|
||||||
|
query = BindingListQuery(
|
||||||
|
device_id=deviceId,
|
||||||
|
agent_id=agentId,
|
||||||
|
status=status,
|
||||||
|
page=page,
|
||||||
|
page_size=pageSize,
|
||||||
|
sort_by=sortBy,
|
||||||
|
sort_order=sortOrder,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Get service
|
||||||
|
service = get_binding_service(db)
|
||||||
|
|
||||||
|
# Get bindings
|
||||||
|
bindings, total = await service.get_binding_list(query)
|
||||||
|
|
||||||
|
# Convert to response format
|
||||||
|
binding_responses = [
|
||||||
|
BindingResponse.model_validate(binding) for binding in bindings
|
||||||
|
]
|
||||||
|
|
||||||
|
# Create paginated response
|
||||||
|
pagination_data = paginated_response(
|
||||||
|
items=binding_responses,
|
||||||
|
total=total,
|
||||||
|
page=page,
|
||||||
|
page_size=pageSize,
|
||||||
|
)
|
||||||
|
|
||||||
|
return success_response(data=pagination_data)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error getting binding list: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=f"Failed to get binding list: {str(e)}",
|
||||||
|
code=500
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{binding_id}")
|
||||||
|
async def get_binding_detail(
|
||||||
|
binding_id: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""
|
||||||
|
Get DeviceAgentBinding details by ID
|
||||||
|
|
||||||
|
- **binding_id**: Binding unique ID
|
||||||
|
|
||||||
|
Returns detailed binding information.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
service = get_binding_service(db)
|
||||||
|
binding = await service.get_binding_by_id(binding_id)
|
||||||
|
|
||||||
|
if not binding:
|
||||||
|
return error_response(
|
||||||
|
message=f"Binding not found: {binding_id}",
|
||||||
|
code=404
|
||||||
|
)
|
||||||
|
|
||||||
|
binding_response = BindingResponse.model_validate(binding)
|
||||||
|
return success_response(data=binding_response)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error getting binding detail: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=f"Failed to get binding detail: {str(e)}",
|
||||||
|
code=500
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/device/{device_id}")
|
||||||
|
async def get_binding_by_device(
|
||||||
|
device_id: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""
|
||||||
|
Get DeviceAgentBinding by device ID
|
||||||
|
|
||||||
|
- **device_id**: Device unique ID
|
||||||
|
|
||||||
|
Returns binding information for the device.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
service = get_binding_service(db)
|
||||||
|
binding = await service.get_binding_by_device_id(device_id)
|
||||||
|
|
||||||
|
if not binding:
|
||||||
|
return error_response(
|
||||||
|
message=f"No binding found for device: {device_id}",
|
||||||
|
code=404
|
||||||
|
)
|
||||||
|
|
||||||
|
binding_response = BindingResponse.model_validate(binding)
|
||||||
|
return success_response(data=binding_response)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error getting binding by device: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=f"Failed to get binding by device: {str(e)}",
|
||||||
|
code=500
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/")
|
||||||
|
async def create_binding(
|
||||||
|
binding_data: BindingCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""
|
||||||
|
Create a new DeviceAgentBinding
|
||||||
|
|
||||||
|
Request body:
|
||||||
|
- **deviceId**: Device unique ID (required)
|
||||||
|
- **agentId**: Agent unique ID (required)
|
||||||
|
|
||||||
|
Returns the created binding with generated ID.
|
||||||
|
|
||||||
|
Note: Each device can only be bound to one agent at a time.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
service = get_binding_service(db)
|
||||||
|
binding = await service.create_binding(binding_data)
|
||||||
|
|
||||||
|
binding_response = BindingResponse.model_validate(binding)
|
||||||
|
return success_response(
|
||||||
|
data=binding_response,
|
||||||
|
message="Binding created successfully",
|
||||||
|
code=201
|
||||||
|
)
|
||||||
|
|
||||||
|
except ValueError as e:
|
||||||
|
# Business logic errors (e.g., device not found, already bound)
|
||||||
|
logger.warning(f"Validation error creating binding: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=str(e),
|
||||||
|
code=400
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error creating binding: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=f"Failed to create binding: {str(e)}",
|
||||||
|
code=500
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{binding_id}")
|
||||||
|
async def update_binding(
|
||||||
|
binding_id: str,
|
||||||
|
binding_data: BindingUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""
|
||||||
|
Update DeviceAgentBinding configuration
|
||||||
|
|
||||||
|
- **binding_id**: Binding unique ID
|
||||||
|
|
||||||
|
Request body (all fields optional):
|
||||||
|
- **agentId**: Agent unique ID (to change the bound agent)
|
||||||
|
- **status**: Binding status (active, inactive)
|
||||||
|
|
||||||
|
Returns the updated binding information.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
service = get_binding_service(db)
|
||||||
|
binding = await service.update_binding(binding_id, binding_data)
|
||||||
|
|
||||||
|
if not binding:
|
||||||
|
return error_response(
|
||||||
|
message=f"Binding not found: {binding_id}",
|
||||||
|
code=404
|
||||||
|
)
|
||||||
|
|
||||||
|
binding_response = BindingResponse.model_validate(binding)
|
||||||
|
return success_response(
|
||||||
|
data=binding_response,
|
||||||
|
message="Binding updated successfully"
|
||||||
|
)
|
||||||
|
|
||||||
|
except ValueError as e:
|
||||||
|
# Business logic errors (e.g., agent not found)
|
||||||
|
logger.warning(f"Validation error updating binding: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=str(e),
|
||||||
|
code=400
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error updating binding: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=f"Failed to update binding: {str(e)}",
|
||||||
|
code=500
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{binding_id}")
|
||||||
|
async def delete_binding(
|
||||||
|
binding_id: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""
|
||||||
|
Delete a DeviceAgentBinding
|
||||||
|
|
||||||
|
- **binding_id**: Binding unique ID
|
||||||
|
|
||||||
|
Deletes the binding relationship between device and agent.
|
||||||
|
Returns success message if deleted.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
service = get_binding_service(db)
|
||||||
|
deleted = await service.delete_binding(binding_id)
|
||||||
|
|
||||||
|
if not deleted:
|
||||||
|
return error_response(
|
||||||
|
message=f"Binding not found: {binding_id}",
|
||||||
|
code=404
|
||||||
|
)
|
||||||
|
|
||||||
|
return success_response(
|
||||||
|
data={"id": binding_id},
|
||||||
|
message="Binding deleted successfully"
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error deleting binding: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=f"Failed to delete binding: {str(e)}",
|
||||||
|
code=500
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/device/{device_id}")
|
||||||
|
async def unbind_device(
|
||||||
|
device_id: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""
|
||||||
|
Remove binding for a device
|
||||||
|
|
||||||
|
- **device_id**: Device unique ID
|
||||||
|
|
||||||
|
Unbinds the device from its agent.
|
||||||
|
Returns success message if unbound.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
service = get_binding_service(db)
|
||||||
|
unbound = await service.unbind_device(device_id)
|
||||||
|
|
||||||
|
if not unbound:
|
||||||
|
return error_response(
|
||||||
|
message=f"No binding found for device: {device_id}",
|
||||||
|
code=404
|
||||||
|
)
|
||||||
|
|
||||||
|
return success_response(
|
||||||
|
data={"deviceId": device_id},
|
||||||
|
message="Device unbound successfully"
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error unbinding device: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=f"Failed to unbind device: {str(e)}",
|
||||||
|
code=500
|
||||||
|
)
|
||||||
|
|
||||||
253
main/live-agent-api/router/device.py
Normal file
253
main/live-agent-api/router/device.py
Normal file
|
|
@ -0,0 +1,253 @@
|
||||||
|
"""
|
||||||
|
Device Router
|
||||||
|
|
||||||
|
API endpoints for Device management.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Annotated
|
||||||
|
from fastapi import APIRouter, Depends, Query
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from orm import get_db
|
||||||
|
from services.device_service import DeviceService, get_device_service
|
||||||
|
from schemas.device import (
|
||||||
|
DeviceCreate,
|
||||||
|
DeviceUpdate,
|
||||||
|
DeviceResponse,
|
||||||
|
DeviceListQuery,
|
||||||
|
)
|
||||||
|
from utils.response import (
|
||||||
|
ApiResponse,
|
||||||
|
success_response,
|
||||||
|
error_response,
|
||||||
|
paginated_response,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/device", tags=["device"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/")
|
||||||
|
async def get_device_list(
|
||||||
|
search: Annotated[str | None, Query(description="Search keyword")] = None,
|
||||||
|
status: Annotated[str | None, Query(description="Filter by status")] = None,
|
||||||
|
page: Annotated[int, Query(ge=1, description="Page number")] = 1,
|
||||||
|
pageSize: Annotated[int, Query(ge=1, le=100, alias="pageSize", description="Items per page")] = 10,
|
||||||
|
sortBy: Annotated[str, Query(alias="sortBy", description="Sort field")] = "createdAt",
|
||||||
|
sortOrder: Annotated[str, Query(alias="sortOrder", pattern="^(asc|desc)$", description="Sort order")] = "desc",
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""
|
||||||
|
Get Device list with search, filtering, pagination and sorting
|
||||||
|
|
||||||
|
- **search**: Search keyword (searches in name, device_id, and model)
|
||||||
|
- **status**: Filter by status (active, inactive, offline)
|
||||||
|
- **page**: Page number (starting from 1)
|
||||||
|
- **pageSize**: Number of items per page (1-100)
|
||||||
|
- **sortBy**: Field to sort by (default: createdAt)
|
||||||
|
- **sortOrder**: Sort order - asc or desc (default: desc)
|
||||||
|
|
||||||
|
Returns paginated list of devices with total count.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# Create query object
|
||||||
|
query = DeviceListQuery(
|
||||||
|
search=search,
|
||||||
|
status=status,
|
||||||
|
page=page,
|
||||||
|
page_size=pageSize,
|
||||||
|
sort_by=sortBy,
|
||||||
|
sort_order=sortOrder,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Get service
|
||||||
|
service = get_device_service(db)
|
||||||
|
|
||||||
|
# Get devices
|
||||||
|
devices, total = await service.get_device_list(query)
|
||||||
|
|
||||||
|
# Convert to response format
|
||||||
|
device_responses = [
|
||||||
|
DeviceResponse.model_validate(device) for device in devices
|
||||||
|
]
|
||||||
|
|
||||||
|
# Create paginated response
|
||||||
|
pagination_data = paginated_response(
|
||||||
|
items=device_responses,
|
||||||
|
total=total,
|
||||||
|
page=page,
|
||||||
|
page_size=pageSize,
|
||||||
|
)
|
||||||
|
|
||||||
|
return success_response(data=pagination_data)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error getting device list: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=f"Failed to get device list: {str(e)}",
|
||||||
|
code=500
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{device_id}")
|
||||||
|
async def get_device_detail(
|
||||||
|
device_id: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""
|
||||||
|
Get Device details by ID
|
||||||
|
|
||||||
|
- **device_id**: Device unique ID
|
||||||
|
|
||||||
|
Returns detailed device information.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
service = get_device_service(db)
|
||||||
|
device = await service.get_device_by_id(device_id)
|
||||||
|
|
||||||
|
if not device:
|
||||||
|
return error_response(
|
||||||
|
message=f"Device not found: {device_id}",
|
||||||
|
code=404
|
||||||
|
)
|
||||||
|
|
||||||
|
device_response = DeviceResponse.model_validate(device)
|
||||||
|
return success_response(data=device_response)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error getting device detail: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=f"Failed to get device detail: {str(e)}",
|
||||||
|
code=500
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/")
|
||||||
|
async def create_device(
|
||||||
|
device_data: DeviceCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""
|
||||||
|
Create a new Device
|
||||||
|
|
||||||
|
Request body:
|
||||||
|
- **name**: Device display name (required)
|
||||||
|
- **deviceId**: Device hardware ID (required, must be unique)
|
||||||
|
- **model**: Device model (optional)
|
||||||
|
- **firmwareVersion**: Firmware version (optional)
|
||||||
|
- **status**: Device status (default: active)
|
||||||
|
- **description**: Device description (optional)
|
||||||
|
- **metadata**: Additional metadata in JSON format (optional)
|
||||||
|
|
||||||
|
Returns the created device with generated ID.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
service = get_device_service(db)
|
||||||
|
device = await service.create_device(device_data)
|
||||||
|
|
||||||
|
device_response = DeviceResponse.model_validate(device)
|
||||||
|
return success_response(
|
||||||
|
data=device_response,
|
||||||
|
message="Device created successfully",
|
||||||
|
code=201
|
||||||
|
)
|
||||||
|
|
||||||
|
except ValueError as e:
|
||||||
|
# Business logic errors (e.g., duplicate device_id)
|
||||||
|
logger.warning(f"Validation error creating device: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=str(e),
|
||||||
|
code=400
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error creating device: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=f"Failed to create device: {str(e)}",
|
||||||
|
code=500
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{device_id}")
|
||||||
|
async def update_device(
|
||||||
|
device_id: str,
|
||||||
|
device_data: DeviceUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""
|
||||||
|
Update Device configuration
|
||||||
|
|
||||||
|
- **device_id**: Device unique ID
|
||||||
|
|
||||||
|
Request body (all fields optional):
|
||||||
|
- **name**: Device display name
|
||||||
|
- **model**: Device model
|
||||||
|
- **firmwareVersion**: Firmware version
|
||||||
|
- **status**: Device status
|
||||||
|
- **isOnline**: Whether device is online
|
||||||
|
- **description**: Device description
|
||||||
|
- **metadata**: Additional metadata
|
||||||
|
|
||||||
|
Returns the updated device information.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
service = get_device_service(db)
|
||||||
|
device = await service.update_device(device_id, device_data)
|
||||||
|
|
||||||
|
if not device:
|
||||||
|
return error_response(
|
||||||
|
message=f"Device not found: {device_id}",
|
||||||
|
code=404
|
||||||
|
)
|
||||||
|
|
||||||
|
device_response = DeviceResponse.model_validate(device)
|
||||||
|
return success_response(
|
||||||
|
data=device_response,
|
||||||
|
message="Device updated successfully"
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error updating device: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=f"Failed to update device: {str(e)}",
|
||||||
|
code=500
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{device_id}")
|
||||||
|
async def delete_device(
|
||||||
|
device_id: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> ApiResponse:
|
||||||
|
"""
|
||||||
|
Delete a Device
|
||||||
|
|
||||||
|
- **device_id**: Device unique ID
|
||||||
|
|
||||||
|
Deletes the device if no binding relationships exist.
|
||||||
|
Returns success message if deleted.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
service = get_device_service(db)
|
||||||
|
deleted = await service.delete_device(device_id)
|
||||||
|
|
||||||
|
if not deleted:
|
||||||
|
return error_response(
|
||||||
|
message=f"Device not found: {device_id}",
|
||||||
|
code=404
|
||||||
|
)
|
||||||
|
|
||||||
|
return success_response(
|
||||||
|
data={"id": device_id},
|
||||||
|
message="Device deleted successfully"
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error deleting device: {str(e)}")
|
||||||
|
return error_response(
|
||||||
|
message=f"Failed to delete device: {str(e)}",
|
||||||
|
code=500
|
||||||
|
)
|
||||||
|
|
||||||
|
|
@ -4,6 +4,7 @@ API Schemas
|
||||||
Pydantic models for request/response validation.
|
Pydantic models for request/response validation.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
# Agent schemas
|
||||||
from schemas.agent import (
|
from schemas.agent import (
|
||||||
AgentBase,
|
AgentBase,
|
||||||
AgentCreate,
|
AgentCreate,
|
||||||
|
|
@ -15,7 +16,26 @@ from schemas.agent import (
|
||||||
GeneratePromptResponse,
|
GeneratePromptResponse,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Device schemas
|
||||||
|
from schemas.device import (
|
||||||
|
DeviceBase,
|
||||||
|
DeviceCreate,
|
||||||
|
DeviceUpdate,
|
||||||
|
DeviceResponse,
|
||||||
|
DeviceListQuery,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Binding schemas
|
||||||
|
from schemas.binding import (
|
||||||
|
BindingCreate,
|
||||||
|
BindingUpdate,
|
||||||
|
BindingResponse,
|
||||||
|
BindingWithDetails,
|
||||||
|
BindingListQuery,
|
||||||
|
)
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
|
# Agent schemas
|
||||||
"AgentBase",
|
"AgentBase",
|
||||||
"AgentCreate",
|
"AgentCreate",
|
||||||
"AgentUpdate",
|
"AgentUpdate",
|
||||||
|
|
@ -24,5 +44,18 @@ __all__ = [
|
||||||
"AgentListQuery",
|
"AgentListQuery",
|
||||||
"GeneratePromptRequest",
|
"GeneratePromptRequest",
|
||||||
"GeneratePromptResponse",
|
"GeneratePromptResponse",
|
||||||
]
|
|
||||||
|
|
||||||
|
# Device schemas
|
||||||
|
"DeviceBase",
|
||||||
|
"DeviceCreate",
|
||||||
|
"DeviceUpdate",
|
||||||
|
"DeviceResponse",
|
||||||
|
"DeviceListQuery",
|
||||||
|
|
||||||
|
# Binding schemas
|
||||||
|
"BindingCreate",
|
||||||
|
"BindingUpdate",
|
||||||
|
"BindingResponse",
|
||||||
|
"BindingWithDetails",
|
||||||
|
"BindingListQuery",
|
||||||
|
]
|
||||||
|
|
|
||||||
|
|
@ -18,11 +18,6 @@ class AgentBase(BaseModel):
|
||||||
max_length=255,
|
max_length=255,
|
||||||
description="Agent display name"
|
description="Agent display name"
|
||||||
)
|
)
|
||||||
template: str = Field(
|
|
||||||
default="blank",
|
|
||||||
max_length=100,
|
|
||||||
description="Agent template type"
|
|
||||||
)
|
|
||||||
language: str = Field(
|
language: str = Field(
|
||||||
default="en",
|
default="en",
|
||||||
max_length=10,
|
max_length=10,
|
||||||
|
|
@ -50,7 +45,6 @@ class AgentBase(BaseModel):
|
||||||
"json_schema_extra": {
|
"json_schema_extra": {
|
||||||
"example": {
|
"example": {
|
||||||
"name": "My Assistant",
|
"name": "My Assistant",
|
||||||
"template": "personal-assistant",
|
|
||||||
"language": "en",
|
"language": "en",
|
||||||
"firstMessage": "Hello! How can I help you today?",
|
"firstMessage": "Hello! How can I help you today?",
|
||||||
"systemPrompt": "You are a helpful assistant.",
|
"systemPrompt": "You are a helpful assistant.",
|
||||||
|
|
@ -63,6 +57,12 @@ class AgentBase(BaseModel):
|
||||||
class AgentCreate(AgentBase):
|
class AgentCreate(AgentBase):
|
||||||
"""Schema for creating a new Agent"""
|
"""Schema for creating a new Agent"""
|
||||||
|
|
||||||
|
template: str = Field(
|
||||||
|
default="blank",
|
||||||
|
max_length=100,
|
||||||
|
description="Agent template type (blank, personal_assistant, learning_companion, health_wellness, hospital_assistant)"
|
||||||
|
)
|
||||||
|
|
||||||
@field_validator('name')
|
@field_validator('name')
|
||||||
@classmethod
|
@classmethod
|
||||||
def validate_name(cls, v: str) -> str:
|
def validate_name(cls, v: str) -> str:
|
||||||
|
|
@ -84,14 +84,8 @@ class AgentCreate(AgentBase):
|
||||||
|
|
||||||
|
|
||||||
class AgentUpdate(BaseModel):
|
class AgentUpdate(BaseModel):
|
||||||
"""Schema for updating an Agent (all fields optional)"""
|
"""Schema for updating an Agent (all fields optional, name is immutable)"""
|
||||||
|
|
||||||
name: Optional[str] = Field(
|
|
||||||
None,
|
|
||||||
min_length=1,
|
|
||||||
max_length=255,
|
|
||||||
description="Agent display name"
|
|
||||||
)
|
|
||||||
language: Optional[str] = Field(
|
language: Optional[str] = Field(
|
||||||
None,
|
None,
|
||||||
max_length=10,
|
max_length=10,
|
||||||
|
|
@ -118,7 +112,6 @@ class AgentUpdate(BaseModel):
|
||||||
"populate_by_name": True,
|
"populate_by_name": True,
|
||||||
"json_schema_extra": {
|
"json_schema_extra": {
|
||||||
"example": {
|
"example": {
|
||||||
"name": "Updated Agent Name",
|
|
||||||
"language": "zh",
|
"language": "zh",
|
||||||
"firstMessage": "你好!有什么可以帮助你的吗?",
|
"firstMessage": "你好!有什么可以帮助你的吗?",
|
||||||
"systemPrompt": "You are a helpful Chinese assistant.",
|
"systemPrompt": "You are a helpful Chinese assistant.",
|
||||||
|
|
@ -127,16 +120,6 @@ class AgentUpdate(BaseModel):
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@field_validator('name')
|
|
||||||
@classmethod
|
|
||||||
def validate_name(cls, v: Optional[str]) -> Optional[str]:
|
|
||||||
"""Validate and clean agent name"""
|
|
||||||
if v is not None:
|
|
||||||
v = v.strip()
|
|
||||||
if not v:
|
|
||||||
raise ValueError("Agent name cannot be empty")
|
|
||||||
return v
|
|
||||||
|
|
||||||
@field_validator('language')
|
@field_validator('language')
|
||||||
@classmethod
|
@classmethod
|
||||||
def validate_language(cls, v: Optional[str]) -> Optional[str]:
|
def validate_language(cls, v: Optional[str]) -> Optional[str]:
|
||||||
|
|
@ -189,7 +172,6 @@ class AgentResponse(AgentBase):
|
||||||
"example": {
|
"example": {
|
||||||
"id": "1234567890",
|
"id": "1234567890",
|
||||||
"name": "My Assistant",
|
"name": "My Assistant",
|
||||||
"template": "personal-assistant",
|
|
||||||
"language": "en",
|
"language": "en",
|
||||||
"firstMessage": "Hello! How can I help you today?",
|
"firstMessage": "Hello! How can I help you today?",
|
||||||
"systemPrompt": "You are a helpful assistant.",
|
"systemPrompt": "You are a helpful assistant.",
|
||||||
|
|
@ -202,7 +184,7 @@ class AgentResponse(AgentBase):
|
||||||
|
|
||||||
|
|
||||||
class AgentListQuery(BaseModel):
|
class AgentListQuery(BaseModel):
|
||||||
"""Schema for Agent list query parameters"""
|
"""Schema for Agent list query parameters (sorted by creation time desc)"""
|
||||||
|
|
||||||
search: Optional[str] = Field(
|
search: Optional[str] = Field(
|
||||||
None,
|
None,
|
||||||
|
|
@ -221,17 +203,6 @@ class AgentListQuery(BaseModel):
|
||||||
le=100,
|
le=100,
|
||||||
description="Number of items per page"
|
description="Number of items per page"
|
||||||
)
|
)
|
||||||
sort_by: str = Field(
|
|
||||||
default="createdAt",
|
|
||||||
alias="sortBy",
|
|
||||||
description="Sort field"
|
|
||||||
)
|
|
||||||
sort_order: str = Field(
|
|
||||||
default="desc",
|
|
||||||
alias="sortOrder",
|
|
||||||
pattern="^(asc|desc)$",
|
|
||||||
description="Sort order (asc or desc)"
|
|
||||||
)
|
|
||||||
|
|
||||||
model_config = {
|
model_config = {
|
||||||
"populate_by_name": True
|
"populate_by_name": True
|
||||||
|
|
@ -244,14 +215,22 @@ class GeneratePromptRequest(BaseModel):
|
||||||
description: str = Field(
|
description: str = Field(
|
||||||
...,
|
...,
|
||||||
min_length=1,
|
min_length=1,
|
||||||
max_length=1000,
|
max_length=500,
|
||||||
description="Description of the agent's purpose"
|
description="Description of the agent's purpose and requirements"
|
||||||
|
)
|
||||||
|
current_prompt: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
alias="currentPrompt",
|
||||||
|
max_length=10000,
|
||||||
|
description="Existing system prompt to refine or build upon (optional)"
|
||||||
)
|
)
|
||||||
|
|
||||||
model_config = {
|
model_config = {
|
||||||
|
"populate_by_name": True,
|
||||||
"json_schema_extra": {
|
"json_schema_extra": {
|
||||||
"example": {
|
"example": {
|
||||||
"description": "a customer support agent for PLAUD"
|
"description": "a customer support agent for PLAUD that handles technical questions",
|
||||||
|
"currentPrompt": "You are a helpful assistant for PLAUD customers."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
170
main/live-agent-api/schemas/binding.py
Normal file
170
main/live-agent-api/schemas/binding.py
Normal file
|
|
@ -0,0 +1,170 @@
|
||||||
|
"""
|
||||||
|
DeviceAgentBinding Schemas
|
||||||
|
|
||||||
|
Pydantic models for DeviceAgentBinding API request/response validation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class BindingCreate(BaseModel):
|
||||||
|
"""Schema for creating a new DeviceAgentBinding"""
|
||||||
|
|
||||||
|
device_id: str = Field(
|
||||||
|
...,
|
||||||
|
alias="deviceId",
|
||||||
|
min_length=1,
|
||||||
|
max_length=64,
|
||||||
|
description="Device unique ID"
|
||||||
|
)
|
||||||
|
agent_id: str = Field(
|
||||||
|
...,
|
||||||
|
alias="agentId",
|
||||||
|
min_length=1,
|
||||||
|
max_length=64,
|
||||||
|
description="Agent unique ID"
|
||||||
|
)
|
||||||
|
|
||||||
|
model_config = {
|
||||||
|
"populate_by_name": True,
|
||||||
|
"json_schema_extra": {
|
||||||
|
"example": {
|
||||||
|
"deviceId": "1234567890",
|
||||||
|
"agentId": "0987654321"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class BindingUpdate(BaseModel):
|
||||||
|
"""Schema for updating a DeviceAgentBinding"""
|
||||||
|
|
||||||
|
agent_id: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
alias="agentId",
|
||||||
|
min_length=1,
|
||||||
|
max_length=64,
|
||||||
|
description="Agent unique ID"
|
||||||
|
)
|
||||||
|
status: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
max_length=20,
|
||||||
|
description="Binding status (active, inactive)"
|
||||||
|
)
|
||||||
|
|
||||||
|
model_config = {
|
||||||
|
"populate_by_name": True,
|
||||||
|
"json_schema_extra": {
|
||||||
|
"example": {
|
||||||
|
"agentId": "0987654321",
|
||||||
|
"status": "active"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class BindingResponse(BaseModel):
|
||||||
|
"""Schema for DeviceAgentBinding response"""
|
||||||
|
|
||||||
|
id: str = Field(..., description="Binding unique ID")
|
||||||
|
device_id: str = Field(..., alias="deviceId", description="Device unique ID")
|
||||||
|
agent_id: str = Field(..., alias="agentId", description="Agent unique ID")
|
||||||
|
status: str = Field(..., description="Binding status")
|
||||||
|
created_at: datetime = Field(
|
||||||
|
...,
|
||||||
|
alias="createdAt",
|
||||||
|
description="Creation timestamp"
|
||||||
|
)
|
||||||
|
updated_at: datetime = Field(
|
||||||
|
...,
|
||||||
|
alias="updatedAt",
|
||||||
|
description="Last update timestamp"
|
||||||
|
)
|
||||||
|
|
||||||
|
model_config = {
|
||||||
|
"populate_by_name": True,
|
||||||
|
"from_attributes": True,
|
||||||
|
"json_schema_extra": {
|
||||||
|
"example": {
|
||||||
|
"id": "1122334455",
|
||||||
|
"deviceId": "1234567890",
|
||||||
|
"agentId": "0987654321",
|
||||||
|
"status": "active",
|
||||||
|
"createdAt": "2024-01-01T00:00:00",
|
||||||
|
"updatedAt": "2024-01-01T00:00:00"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class BindingWithDetails(BindingResponse):
|
||||||
|
"""Schema for DeviceAgentBinding response with device and agent details"""
|
||||||
|
|
||||||
|
device_name: Optional[str] = Field(None, alias="deviceName", description="Device name")
|
||||||
|
agent_name: Optional[str] = Field(None, alias="agentName", description="Agent name")
|
||||||
|
|
||||||
|
model_config = {
|
||||||
|
"populate_by_name": True,
|
||||||
|
"from_attributes": True,
|
||||||
|
"json_schema_extra": {
|
||||||
|
"example": {
|
||||||
|
"id": "1122334455",
|
||||||
|
"deviceId": "1234567890",
|
||||||
|
"agentId": "0987654321",
|
||||||
|
"status": "active",
|
||||||
|
"deviceName": "My PLAUD Device",
|
||||||
|
"agentName": "My Assistant",
|
||||||
|
"createdAt": "2024-01-01T00:00:00",
|
||||||
|
"updatedAt": "2024-01-01T00:00:00"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class BindingListQuery(BaseModel):
|
||||||
|
"""Schema for DeviceAgentBinding list query parameters"""
|
||||||
|
|
||||||
|
device_id: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
alias="deviceId",
|
||||||
|
description="Filter by device ID"
|
||||||
|
)
|
||||||
|
agent_id: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
alias="agentId",
|
||||||
|
description="Filter by agent ID"
|
||||||
|
)
|
||||||
|
status: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
description="Filter by status"
|
||||||
|
)
|
||||||
|
page: int = Field(
|
||||||
|
default=1,
|
||||||
|
ge=1,
|
||||||
|
description="Page number"
|
||||||
|
)
|
||||||
|
page_size: int = Field(
|
||||||
|
default=20,
|
||||||
|
alias="pageSize",
|
||||||
|
ge=1,
|
||||||
|
le=100,
|
||||||
|
description="Number of items per page"
|
||||||
|
)
|
||||||
|
sort_by: str = Field(
|
||||||
|
default="createdAt",
|
||||||
|
alias="sortBy",
|
||||||
|
description="Sort field"
|
||||||
|
)
|
||||||
|
sort_order: str = Field(
|
||||||
|
default="desc",
|
||||||
|
alias="sortOrder",
|
||||||
|
pattern="^(asc|desc)$",
|
||||||
|
description="Sort order (asc or desc)"
|
||||||
|
)
|
||||||
|
|
||||||
|
model_config = {
|
||||||
|
"populate_by_name": True
|
||||||
|
}
|
||||||
|
|
||||||
270
main/live-agent-api/schemas/device.py
Normal file
270
main/live-agent-api/schemas/device.py
Normal file
|
|
@ -0,0 +1,270 @@
|
||||||
|
"""
|
||||||
|
Device Schemas
|
||||||
|
|
||||||
|
Pydantic models for Device API request/response validation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
from pydantic import BaseModel, Field, field_validator
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceBase(BaseModel):
|
||||||
|
"""Base schema for Device with common fields"""
|
||||||
|
|
||||||
|
name: str = Field(
|
||||||
|
...,
|
||||||
|
min_length=1,
|
||||||
|
max_length=255,
|
||||||
|
description="Device display name"
|
||||||
|
)
|
||||||
|
device_id: str = Field(
|
||||||
|
...,
|
||||||
|
alias="deviceId",
|
||||||
|
min_length=1,
|
||||||
|
max_length=255,
|
||||||
|
description="Device hardware ID"
|
||||||
|
)
|
||||||
|
model: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
max_length=100,
|
||||||
|
description="Device model (e.g., PLAUD NOTE)"
|
||||||
|
)
|
||||||
|
firmware_version: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
alias="firmwareVersion",
|
||||||
|
max_length=50,
|
||||||
|
description="Firmware version"
|
||||||
|
)
|
||||||
|
status: str = Field(
|
||||||
|
default="active",
|
||||||
|
max_length=20,
|
||||||
|
description="Device status (active, inactive, offline)"
|
||||||
|
)
|
||||||
|
description: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
description="Device description"
|
||||||
|
)
|
||||||
|
extra_data: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
alias="extraData",
|
||||||
|
description="Additional metadata (JSON format)"
|
||||||
|
)
|
||||||
|
|
||||||
|
model_config = {
|
||||||
|
"populate_by_name": True,
|
||||||
|
"json_schema_extra": {
|
||||||
|
"example": {
|
||||||
|
"name": "My PLAUD Device",
|
||||||
|
"deviceId": "PLAUD-12345678",
|
||||||
|
"model": "PLAUD NOTE",
|
||||||
|
"firmwareVersion": "1.0.0",
|
||||||
|
"status": "active",
|
||||||
|
"description": "My personal voice recorder"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceCreate(DeviceBase):
|
||||||
|
"""Schema for creating a new Device"""
|
||||||
|
|
||||||
|
@field_validator('name')
|
||||||
|
@classmethod
|
||||||
|
def validate_name(cls, v: str) -> str:
|
||||||
|
"""Validate and clean device name"""
|
||||||
|
v = v.strip()
|
||||||
|
if not v:
|
||||||
|
raise ValueError("Device name cannot be empty")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('device_id')
|
||||||
|
@classmethod
|
||||||
|
def validate_device_id(cls, v: str) -> str:
|
||||||
|
"""Validate and clean device ID"""
|
||||||
|
v = v.strip()
|
||||||
|
if not v:
|
||||||
|
raise ValueError("Device ID cannot be empty")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('status')
|
||||||
|
@classmethod
|
||||||
|
def validate_status(cls, v: str) -> str:
|
||||||
|
"""Validate status value"""
|
||||||
|
valid_statuses = ["active", "inactive", "offline"]
|
||||||
|
if v not in valid_statuses:
|
||||||
|
raise ValueError(f"Status must be one of: {', '.join(valid_statuses)}")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceUpdate(BaseModel):
|
||||||
|
"""Schema for updating a Device (all fields optional)"""
|
||||||
|
|
||||||
|
name: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
min_length=1,
|
||||||
|
max_length=255,
|
||||||
|
description="Device display name"
|
||||||
|
)
|
||||||
|
model: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
max_length=100,
|
||||||
|
description="Device model"
|
||||||
|
)
|
||||||
|
firmware_version: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
alias="firmwareVersion",
|
||||||
|
max_length=50,
|
||||||
|
description="Firmware version"
|
||||||
|
)
|
||||||
|
status: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
max_length=20,
|
||||||
|
description="Device status"
|
||||||
|
)
|
||||||
|
is_online: Optional[bool] = Field(
|
||||||
|
None,
|
||||||
|
alias="isOnline",
|
||||||
|
description="Whether device is online"
|
||||||
|
)
|
||||||
|
description: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
description="Device description"
|
||||||
|
)
|
||||||
|
extra_data: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
alias="extraData",
|
||||||
|
description="Additional metadata"
|
||||||
|
)
|
||||||
|
|
||||||
|
model_config = {
|
||||||
|
"populate_by_name": True,
|
||||||
|
"json_schema_extra": {
|
||||||
|
"example": {
|
||||||
|
"name": "Updated Device Name",
|
||||||
|
"status": "active",
|
||||||
|
"isOnline": True,
|
||||||
|
"firmwareVersion": "1.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@field_validator('name')
|
||||||
|
@classmethod
|
||||||
|
def validate_name(cls, v: Optional[str]) -> Optional[str]:
|
||||||
|
"""Validate and clean device name"""
|
||||||
|
if v is not None:
|
||||||
|
v = v.strip()
|
||||||
|
if not v:
|
||||||
|
raise ValueError("Device name cannot be empty")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('status')
|
||||||
|
@classmethod
|
||||||
|
def validate_status(cls, v: Optional[str]) -> Optional[str]:
|
||||||
|
"""Validate status value"""
|
||||||
|
if v is not None:
|
||||||
|
valid_statuses = ["active", "inactive", "offline"]
|
||||||
|
if v not in valid_statuses:
|
||||||
|
raise ValueError(f"Status must be one of: {', '.join(valid_statuses)}")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceResponse(BaseModel):
|
||||||
|
"""Schema for Device response"""
|
||||||
|
|
||||||
|
id: str = Field(..., description="Device unique ID")
|
||||||
|
name: str = Field(..., description="Device display name")
|
||||||
|
device_id: str = Field(..., alias="deviceId", description="Device hardware ID")
|
||||||
|
model: Optional[str] = Field(None, description="Device model")
|
||||||
|
firmware_version: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
alias="firmwareVersion",
|
||||||
|
description="Firmware version"
|
||||||
|
)
|
||||||
|
status: str = Field(..., description="Device status")
|
||||||
|
is_online: bool = Field(..., alias="isOnline", description="Whether device is online")
|
||||||
|
last_seen_at: Optional[datetime] = Field(
|
||||||
|
None,
|
||||||
|
alias="lastSeenAt",
|
||||||
|
description="Last seen timestamp"
|
||||||
|
)
|
||||||
|
description: Optional[str] = Field(None, description="Device description")
|
||||||
|
extra_data: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
alias="extraData",
|
||||||
|
description="Additional metadata"
|
||||||
|
)
|
||||||
|
created_at: datetime = Field(
|
||||||
|
...,
|
||||||
|
alias="createdAt",
|
||||||
|
description="Creation timestamp"
|
||||||
|
)
|
||||||
|
updated_at: datetime = Field(
|
||||||
|
...,
|
||||||
|
alias="updatedAt",
|
||||||
|
description="Last update timestamp"
|
||||||
|
)
|
||||||
|
|
||||||
|
model_config = {
|
||||||
|
"populate_by_name": True,
|
||||||
|
"from_attributes": True,
|
||||||
|
"json_schema_extra": {
|
||||||
|
"example": {
|
||||||
|
"id": "1234567890",
|
||||||
|
"name": "My PLAUD Device",
|
||||||
|
"deviceId": "PLAUD-12345678",
|
||||||
|
"model": "PLAUD NOTE",
|
||||||
|
"firmwareVersion": "1.0.0",
|
||||||
|
"status": "active",
|
||||||
|
"isOnline": True,
|
||||||
|
"lastSeenAt": "2024-01-01T00:00:00",
|
||||||
|
"description": "My personal voice recorder",
|
||||||
|
"metadata": None,
|
||||||
|
"createdAt": "2024-01-01T00:00:00",
|
||||||
|
"updatedAt": "2024-01-01T00:00:00"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceListQuery(BaseModel):
|
||||||
|
"""Schema for Device list query parameters"""
|
||||||
|
|
||||||
|
search: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
max_length=255,
|
||||||
|
description="Search keyword"
|
||||||
|
)
|
||||||
|
status: Optional[str] = Field(
|
||||||
|
None,
|
||||||
|
description="Filter by status"
|
||||||
|
)
|
||||||
|
page: int = Field(
|
||||||
|
default=1,
|
||||||
|
ge=1,
|
||||||
|
description="Page number"
|
||||||
|
)
|
||||||
|
page_size: int = Field(
|
||||||
|
default=20,
|
||||||
|
alias="pageSize",
|
||||||
|
ge=1,
|
||||||
|
le=100,
|
||||||
|
description="Number of items per page"
|
||||||
|
)
|
||||||
|
sort_by: str = Field(
|
||||||
|
default="createdAt",
|
||||||
|
alias="sortBy",
|
||||||
|
description="Sort field"
|
||||||
|
)
|
||||||
|
sort_order: str = Field(
|
||||||
|
default="desc",
|
||||||
|
alias="sortOrder",
|
||||||
|
pattern="^(asc|desc)$",
|
||||||
|
description="Sort order (asc or desc)"
|
||||||
|
)
|
||||||
|
|
||||||
|
model_config = {
|
||||||
|
"populate_by_name": True
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -18,12 +18,25 @@ from schemas.agent import (
|
||||||
AgentListQuery,
|
AgentListQuery,
|
||||||
GeneratePromptRequest,
|
GeneratePromptRequest,
|
||||||
)
|
)
|
||||||
from utils.id_generator import generate_id
|
from utils import id_generator
|
||||||
|
from templates import TemplateLoader
|
||||||
from config.settings import settings
|
from config.settings import settings
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
BLANK_TEMPLATE = "blank"
|
||||||
|
SYSTEM_PROMPT_INSTRUCTION = """
|
||||||
|
You are an AI assistant that helps create system prompts for voice assistant agents.
|
||||||
|
Generate a clear, professional system prompt that strictly follows this 6-module structure:
|
||||||
|
1. **Personality**: Define the agent's character, traits, and communication style
|
||||||
|
2. **Environment**: Describe the context and setting where the agent operates
|
||||||
|
3. **Tone**: Specify the language tone and manner of interaction
|
||||||
|
4. **Goal**: State the primary objectives and purposes of the agent
|
||||||
|
5. **Guardrails**: Define rules, limitations, and ethical boundaries
|
||||||
|
6. **Tools**: List available capabilities, APIs, or functions the agent can use
|
||||||
|
Each section should be clearly labeled with markdown headers (##).
|
||||||
|
The prompt should be comprehensive yet concise, suitable for a voice assistant.
|
||||||
|
"""
|
||||||
|
|
||||||
class AgentService:
|
class AgentService:
|
||||||
"""Service class for Agent business logic"""
|
"""Service class for Agent business logic"""
|
||||||
|
|
@ -43,7 +56,7 @@ class AgentService:
|
||||||
query: AgentListQuery
|
query: AgentListQuery
|
||||||
) -> tuple[list[Agent], int]:
|
) -> tuple[list[Agent], int]:
|
||||||
"""
|
"""
|
||||||
Get paginated list of agents with optional search
|
Get paginated list of agents with optional search (sorted by creation time desc)
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
query: Query parameters for filtering and pagination
|
query: Query parameters for filtering and pagination
|
||||||
|
|
@ -55,8 +68,6 @@ class AgentService:
|
||||||
search=query.search,
|
search=query.search,
|
||||||
page=query.page,
|
page=query.page,
|
||||||
page_size=query.page_size,
|
page_size=query.page_size,
|
||||||
sort_by=query.sort_by,
|
|
||||||
sort_order=query.sort_order,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
|
|
@ -93,21 +104,43 @@ class AgentService:
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Created agent instance
|
Created agent instance
|
||||||
"""
|
|
||||||
# Business logic: Generate unique ID
|
|
||||||
agent_id = generate_id()
|
|
||||||
|
|
||||||
# Business logic: Create agent instance
|
Raises:
|
||||||
|
ValueError: If template does not exist
|
||||||
|
"""
|
||||||
|
# 1. Generate unique ID
|
||||||
|
agent_id = id_generator.generate()
|
||||||
|
|
||||||
|
# 2. Create blank agent first
|
||||||
agent = Agent(
|
agent = Agent(
|
||||||
id=agent_id,
|
id=agent_id,
|
||||||
name=agent_data.name,
|
name=agent_data.name,
|
||||||
template=agent_data.template,
|
|
||||||
language=agent_data.language,
|
language=agent_data.language,
|
||||||
first_message=agent_data.first_message,
|
first_message=agent_data.first_message,
|
||||||
system_prompt=agent_data.system_prompt,
|
system_prompt=agent_data.system_prompt,
|
||||||
wake_word=agent_data.wake_word,
|
wake_word=agent_data.wake_word,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 3. If not blank template, load and populate from template
|
||||||
|
if agent_data.template != BLANK_TEMPLATE:
|
||||||
|
try:
|
||||||
|
template = TemplateLoader.load(agent_data.template)
|
||||||
|
|
||||||
|
if template is None:
|
||||||
|
raise ValueError(f"Failed to load template: {agent_data.template}")
|
||||||
|
|
||||||
|
# Populate agent from template (template values are applied if user didn't provide)
|
||||||
|
agent.language = template.language
|
||||||
|
agent.first_message = template.greeting
|
||||||
|
agent.system_prompt = template.profile
|
||||||
|
agent.wake_word = template.wake_word
|
||||||
|
|
||||||
|
logger.info(f"Populated agent from template: {agent_data.template}")
|
||||||
|
|
||||||
|
except ValueError as e:
|
||||||
|
logger.error(f"Error loading template: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
# Persist to database
|
# Persist to database
|
||||||
agent = await self.repo.save(agent)
|
agent = await self.repo.save(agent)
|
||||||
|
|
||||||
|
|
@ -201,11 +234,10 @@ class AgentService:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# Business logic: Create duplicate with new ID and name
|
# Business logic: Create duplicate with new ID and name
|
||||||
new_id = generate_id()
|
new_id = id_generator.generate()
|
||||||
duplicate_agent = Agent(
|
duplicate_agent = Agent(
|
||||||
id=new_id,
|
id=new_id,
|
||||||
name=new_name,
|
name=new_name,
|
||||||
template=source_agent.template,
|
|
||||||
language=source_agent.language,
|
language=source_agent.language,
|
||||||
first_message=source_agent.first_message,
|
first_message=source_agent.first_message,
|
||||||
system_prompt=source_agent.system_prompt,
|
system_prompt=source_agent.system_prompt,
|
||||||
|
|
@ -229,42 +261,52 @@ class AgentService:
|
||||||
Generate system prompt using AI
|
Generate system prompt using AI
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
request: Prompt generation request with description
|
request: Prompt generation request with description and optional existing prompt
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Generated system prompt
|
Generated system prompt following the 6-module structure
|
||||||
"""
|
"""
|
||||||
logger.info(f"Generating prompt for: {request.description}")
|
logger.info(f"Generating prompt for: {request.description}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
system_instruction = SYSTEM_PROMPT_INSTRUCTION
|
||||||
|
|
||||||
|
# Build user message based on whether existing prompt is provided
|
||||||
|
if request.current_prompt:
|
||||||
|
user_message = (
|
||||||
|
f"I need help refining or regenerating a system prompt.\n\n"
|
||||||
|
f"**User Requirements/Description:**\n{request.description}\n\n"
|
||||||
|
f"**Current Prompt:**\n{request.current_prompt}\n\n"
|
||||||
|
f"Please create an improved system prompt that incorporates the requirements "
|
||||||
|
f"and builds upon the existing prompt, following the 6-module structure."
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
user_message = (
|
||||||
|
f"Create a new system prompt for: {request.description}\n\n"
|
||||||
|
f"Please structure it according to the 6 modules (Personality, Environment, Tone, Goal, Guardrails, Tools)."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create prompt using OpenAI API
|
||||||
|
# Note: Using chat.completions for now, ready to migrate to response.create when available
|
||||||
response = await self.openai_client.chat.completions.create(
|
response = await self.openai_client.chat.completions.create(
|
||||||
model=settings.openai_model,
|
model=settings.openai_model,
|
||||||
messages=[
|
messages=[
|
||||||
{
|
{
|
||||||
"role": "system",
|
"role": "system",
|
||||||
"content": (
|
"content": system_instruction
|
||||||
"You are an AI assistant that helps create system prompts "
|
|
||||||
"for voice assistant agents. Generate a clear, concise, "
|
|
||||||
"and professional system prompt based on the user's description. "
|
|
||||||
"The prompt should define the agent's role, capabilities, "
|
|
||||||
"and behavior guidelines."
|
|
||||||
)
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"role": "user",
|
"role": "user",
|
||||||
"content": (
|
"content": user_message
|
||||||
f"Create a system prompt for {request.description}. "
|
|
||||||
f"The prompt should be suitable for a voice assistant agent."
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
temperature=0.7,
|
temperature=0.7,
|
||||||
max_tokens=500,
|
max_tokens=1500,
|
||||||
)
|
)
|
||||||
|
|
||||||
generated_prompt = response.choices[0].message.content.strip()
|
generated_prompt = response.choices[0].message.content.strip()
|
||||||
|
|
||||||
logger.info("Successfully generated system prompt")
|
logger.info("Successfully generated system prompt with 6-module structure")
|
||||||
|
|
||||||
return generated_prompt
|
return generated_prompt
|
||||||
|
|
||||||
|
|
|
||||||
260
main/live-agent-api/services/binding_service.py
Normal file
260
main/live-agent-api/services/binding_service.py
Normal file
|
|
@ -0,0 +1,260 @@
|
||||||
|
"""
|
||||||
|
DeviceAgentBinding Service
|
||||||
|
|
||||||
|
Business logic layer for DeviceAgentBinding operations.
|
||||||
|
Uses Repository pattern for data access.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from orm.binding import DeviceAgentBinding, DeviceAgentBindingRepository
|
||||||
|
from orm.device import DeviceRepository
|
||||||
|
from orm.agent import AgentRepository
|
||||||
|
from schemas.binding import BindingCreate, BindingUpdate, BindingListQuery
|
||||||
|
from utils import id_generator
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class BindingService:
|
||||||
|
"""Service class for DeviceAgentBinding business logic"""
|
||||||
|
|
||||||
|
def __init__(self, db: AsyncSession):
|
||||||
|
"""
|
||||||
|
Initialize Binding service
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db: Database session
|
||||||
|
"""
|
||||||
|
self.repo = DeviceAgentBindingRepository(db)
|
||||||
|
self.device_repo = DeviceRepository(db)
|
||||||
|
self.agent_repo = AgentRepository(db)
|
||||||
|
|
||||||
|
async def get_binding_list(
|
||||||
|
self,
|
||||||
|
query: BindingListQuery
|
||||||
|
) -> tuple[list[DeviceAgentBinding], int]:
|
||||||
|
"""
|
||||||
|
Get paginated list of bindings with optional filtering
|
||||||
|
|
||||||
|
Args:
|
||||||
|
query: Query parameters for filtering and pagination
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (bindings list, total count)
|
||||||
|
"""
|
||||||
|
bindings, total = await self.repo.find_all(
|
||||||
|
device_id=query.device_id,
|
||||||
|
agent_id=query.agent_id,
|
||||||
|
status=query.status,
|
||||||
|
page=query.page,
|
||||||
|
page_size=query.page_size,
|
||||||
|
sort_by=query.sort_by,
|
||||||
|
sort_order=query.sort_order,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Retrieved {len(bindings)} bindings (page {query.page}, total {total})"
|
||||||
|
)
|
||||||
|
|
||||||
|
return bindings, total
|
||||||
|
|
||||||
|
async def get_binding_by_id(self, binding_id: str) -> Optional[DeviceAgentBinding]:
|
||||||
|
"""
|
||||||
|
Get binding by ID
|
||||||
|
|
||||||
|
Args:
|
||||||
|
binding_id: Binding unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
DeviceAgentBinding instance or None if not found
|
||||||
|
"""
|
||||||
|
binding = await self.repo.find_by_id(binding_id)
|
||||||
|
|
||||||
|
if binding:
|
||||||
|
logger.info(f"Retrieved binding: {binding_id}")
|
||||||
|
else:
|
||||||
|
logger.warning(f"Binding not found: {binding_id}")
|
||||||
|
|
||||||
|
return binding
|
||||||
|
|
||||||
|
async def get_binding_by_device_id(self, device_id: str) -> Optional[DeviceAgentBinding]:
|
||||||
|
"""
|
||||||
|
Get binding by device ID
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Device unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
DeviceAgentBinding instance or None if not found
|
||||||
|
"""
|
||||||
|
binding = await self.repo.find_by_device_id(device_id)
|
||||||
|
|
||||||
|
if binding:
|
||||||
|
logger.info(f"Retrieved binding for device: {device_id}")
|
||||||
|
else:
|
||||||
|
logger.warning(f"No binding found for device: {device_id}")
|
||||||
|
|
||||||
|
return binding
|
||||||
|
|
||||||
|
async def get_bindings_by_agent_id(self, agent_id: str) -> list[DeviceAgentBinding]:
|
||||||
|
"""
|
||||||
|
Get all bindings for an agent
|
||||||
|
|
||||||
|
Args:
|
||||||
|
agent_id: Agent unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List of DeviceAgentBinding instances
|
||||||
|
"""
|
||||||
|
bindings = await self.repo.find_by_agent_id(agent_id)
|
||||||
|
|
||||||
|
logger.info(f"Retrieved {len(bindings)} bindings for agent: {agent_id}")
|
||||||
|
|
||||||
|
return bindings
|
||||||
|
|
||||||
|
async def create_binding(self, binding_data: BindingCreate) -> DeviceAgentBinding:
|
||||||
|
"""
|
||||||
|
Create a new device-agent binding
|
||||||
|
|
||||||
|
Args:
|
||||||
|
binding_data: Binding creation data
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Created binding instance
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If device or agent not found, or device already has binding
|
||||||
|
"""
|
||||||
|
# Business logic: Validate device exists
|
||||||
|
device = await self.device_repo.find_by_id(binding_data.device_id)
|
||||||
|
if not device:
|
||||||
|
raise ValueError(f"Device not found: {binding_data.device_id}")
|
||||||
|
|
||||||
|
# Business logic: Validate agent exists
|
||||||
|
agent = await self.agent_repo.find_by_id(binding_data.agent_id)
|
||||||
|
if not agent:
|
||||||
|
raise ValueError(f"Agent not found: {binding_data.agent_id}")
|
||||||
|
|
||||||
|
# Business logic: Check if device already has a binding
|
||||||
|
if await self.repo.device_has_binding(binding_data.device_id):
|
||||||
|
raise ValueError(f"Device already has a binding: {binding_data.device_id}")
|
||||||
|
|
||||||
|
# Business logic: Generate unique ID
|
||||||
|
binding_id = id_generator.generate()
|
||||||
|
|
||||||
|
# Business logic: Create binding instance
|
||||||
|
binding = DeviceAgentBinding(
|
||||||
|
id=binding_id,
|
||||||
|
device_id=binding_data.device_id,
|
||||||
|
agent_id=binding_data.agent_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Persist to database
|
||||||
|
binding = await self.repo.save(binding)
|
||||||
|
|
||||||
|
logger.info(f"Created binding: {binding_id} (device={binding_data.device_id}, agent={binding_data.agent_id})")
|
||||||
|
|
||||||
|
return binding
|
||||||
|
|
||||||
|
async def update_binding(
|
||||||
|
self,
|
||||||
|
binding_id: str,
|
||||||
|
binding_data: BindingUpdate
|
||||||
|
) -> Optional[DeviceAgentBinding]:
|
||||||
|
"""
|
||||||
|
Update binding configuration
|
||||||
|
|
||||||
|
Args:
|
||||||
|
binding_id: Binding unique ID
|
||||||
|
binding_data: Binding update data
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Updated binding instance or None if not found
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If new agent not found
|
||||||
|
"""
|
||||||
|
# Get existing binding
|
||||||
|
binding = await self.repo.find_by_id(binding_id)
|
||||||
|
if not binding:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Business logic: Validate new agent if provided
|
||||||
|
if binding_data.agent_id:
|
||||||
|
agent = await self.agent_repo.find_by_id(binding_data.agent_id)
|
||||||
|
if not agent:
|
||||||
|
raise ValueError(f"Agent not found: {binding_data.agent_id}")
|
||||||
|
binding.agent_id = binding_data.agent_id
|
||||||
|
|
||||||
|
# Business logic: Update status if provided
|
||||||
|
if binding_data.status:
|
||||||
|
binding.status = binding_data.status
|
||||||
|
|
||||||
|
# Business logic: Update timestamp
|
||||||
|
binding.updated_at = datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
# Persist changes
|
||||||
|
binding = await self.repo.save(binding)
|
||||||
|
|
||||||
|
logger.info(f"Updated binding: {binding_id}")
|
||||||
|
|
||||||
|
return binding
|
||||||
|
|
||||||
|
async def delete_binding(self, binding_id: str) -> bool:
|
||||||
|
"""
|
||||||
|
Delete a binding
|
||||||
|
|
||||||
|
Args:
|
||||||
|
binding_id: Binding unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if deleted, False if not found
|
||||||
|
"""
|
||||||
|
binding = await self.repo.find_by_id(binding_id)
|
||||||
|
if not binding:
|
||||||
|
return False
|
||||||
|
|
||||||
|
await self.repo.delete(binding)
|
||||||
|
|
||||||
|
logger.info(f"Deleted binding: {binding_id}")
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def unbind_device(self, device_id: str) -> bool:
|
||||||
|
"""
|
||||||
|
Remove binding for a device
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Device unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if unbound, False if no binding found
|
||||||
|
"""
|
||||||
|
binding = await self.repo.find_by_device_id(device_id)
|
||||||
|
if not binding:
|
||||||
|
return False
|
||||||
|
|
||||||
|
await self.repo.delete(binding)
|
||||||
|
|
||||||
|
logger.info(f"Unbound device: {device_id}")
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def get_binding_service(db: AsyncSession) -> BindingService:
|
||||||
|
"""
|
||||||
|
Dependency function to get Binding service
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db: Database session
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
BindingService instance
|
||||||
|
"""
|
||||||
|
return BindingService(db)
|
||||||
|
|
||||||
248
main/live-agent-api/services/device_service.py
Normal file
248
main/live-agent-api/services/device_service.py
Normal file
|
|
@ -0,0 +1,248 @@
|
||||||
|
"""
|
||||||
|
Device Service
|
||||||
|
|
||||||
|
Business logic layer for Device operations.
|
||||||
|
Uses Repository pattern for data access.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from orm.device import Device, DeviceRepository
|
||||||
|
from schemas.device import DeviceCreate, DeviceUpdate, DeviceListQuery
|
||||||
|
from utils import id_generator
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceService:
|
||||||
|
"""Service class for Device business logic"""
|
||||||
|
|
||||||
|
def __init__(self, db: AsyncSession):
|
||||||
|
"""
|
||||||
|
Initialize Device service
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db: Database session
|
||||||
|
"""
|
||||||
|
self.repo = DeviceRepository(db)
|
||||||
|
|
||||||
|
async def get_device_list(
|
||||||
|
self,
|
||||||
|
query: DeviceListQuery
|
||||||
|
) -> tuple[list[Device], int]:
|
||||||
|
"""
|
||||||
|
Get paginated list of devices with optional search and filtering
|
||||||
|
|
||||||
|
Args:
|
||||||
|
query: Query parameters for filtering and pagination
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (devices list, total count)
|
||||||
|
"""
|
||||||
|
devices, total = await self.repo.find_all(
|
||||||
|
search=query.search,
|
||||||
|
status=query.status,
|
||||||
|
page=query.page,
|
||||||
|
page_size=query.page_size,
|
||||||
|
sort_by=query.sort_by,
|
||||||
|
sort_order=query.sort_order,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Retrieved {len(devices)} devices (page {query.page}, total {total})"
|
||||||
|
)
|
||||||
|
|
||||||
|
return devices, total
|
||||||
|
|
||||||
|
async def get_device_by_id(self, device_id: str) -> Optional[Device]:
|
||||||
|
"""
|
||||||
|
Get device by ID
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Device unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Device instance or None if not found
|
||||||
|
"""
|
||||||
|
device = await self.repo.find_by_id(device_id)
|
||||||
|
|
||||||
|
if device:
|
||||||
|
logger.info(f"Retrieved device: {device_id}")
|
||||||
|
else:
|
||||||
|
logger.warning(f"Device not found: {device_id}")
|
||||||
|
|
||||||
|
return device
|
||||||
|
|
||||||
|
async def get_device_by_device_id(self, device_id: str) -> Optional[Device]:
|
||||||
|
"""
|
||||||
|
Get device by hardware device ID
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Device hardware ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Device instance or None if not found
|
||||||
|
"""
|
||||||
|
device = await self.repo.find_by_device_id(device_id)
|
||||||
|
|
||||||
|
if device:
|
||||||
|
logger.info(f"Retrieved device by device_id: {device_id}")
|
||||||
|
else:
|
||||||
|
logger.warning(f"Device not found by device_id: {device_id}")
|
||||||
|
|
||||||
|
return device
|
||||||
|
|
||||||
|
async def create_device(self, device_data: DeviceCreate) -> Device:
|
||||||
|
"""
|
||||||
|
Create a new device
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_data: Device creation data
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Created device instance
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If device_id already exists
|
||||||
|
"""
|
||||||
|
# Business logic: Check if device_id already exists
|
||||||
|
if await self.repo.device_id_exists(device_data.device_id):
|
||||||
|
raise ValueError(f"Device ID already exists: {device_data.device_id}")
|
||||||
|
|
||||||
|
# Business logic: Generate unique ID
|
||||||
|
device_id = id_generator.generate()
|
||||||
|
|
||||||
|
# Business logic: Create device instance
|
||||||
|
device = Device(
|
||||||
|
id=device_id,
|
||||||
|
name=device_data.name,
|
||||||
|
device_id=device_data.device_id,
|
||||||
|
model=device_data.model,
|
||||||
|
firmware_version=device_data.firmware_version,
|
||||||
|
status=device_data.status,
|
||||||
|
description=device_data.description,
|
||||||
|
extra_data=device_data.extra_data,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Persist to database
|
||||||
|
device = await self.repo.save(device)
|
||||||
|
|
||||||
|
logger.info(f"Created device: {device_id} ({device.name})")
|
||||||
|
|
||||||
|
return device
|
||||||
|
|
||||||
|
async def update_device(
|
||||||
|
self,
|
||||||
|
device_id: str,
|
||||||
|
device_data: DeviceUpdate
|
||||||
|
) -> Optional[Device]:
|
||||||
|
"""
|
||||||
|
Update device configuration
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Device unique ID
|
||||||
|
device_data: Device update data
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Updated device instance or None if not found
|
||||||
|
"""
|
||||||
|
# Get existing device
|
||||||
|
device = await self.repo.find_by_id(device_id)
|
||||||
|
if not device:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Business logic: Update fields
|
||||||
|
update_data = device_data.model_dump(exclude_unset=True)
|
||||||
|
for field, value in update_data.items():
|
||||||
|
# Convert camelCase to snake_case
|
||||||
|
db_field = field.replace("firmwareVersion", "firmware_version")
|
||||||
|
db_field = db_field.replace("isOnline", "is_online")
|
||||||
|
db_field = db_field.replace("extraData", "extra_data")
|
||||||
|
|
||||||
|
if hasattr(device, db_field):
|
||||||
|
setattr(device, db_field, value)
|
||||||
|
|
||||||
|
# Business logic: Update last_seen_at if device comes online
|
||||||
|
if device_data.is_online is True:
|
||||||
|
device.last_seen_at = datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
# Business logic: Update timestamp
|
||||||
|
device.updated_at = datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
# Persist changes
|
||||||
|
device = await self.repo.save(device)
|
||||||
|
|
||||||
|
logger.info(f"Updated device: {device_id}")
|
||||||
|
|
||||||
|
return device
|
||||||
|
|
||||||
|
async def delete_device(self, device_id: str) -> bool:
|
||||||
|
"""
|
||||||
|
Delete a device
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Device unique ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if deleted, False if not found
|
||||||
|
"""
|
||||||
|
device = await self.repo.find_by_id(device_id)
|
||||||
|
if not device:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# TODO: Business logic - Check for binding relationships
|
||||||
|
# For now, just delete the device
|
||||||
|
# In production, should check if device has bindings and handle accordingly
|
||||||
|
|
||||||
|
await self.repo.delete(device)
|
||||||
|
|
||||||
|
logger.info(f"Deleted device: {device_id}")
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def update_device_status(
|
||||||
|
self,
|
||||||
|
device_id: str,
|
||||||
|
is_online: bool
|
||||||
|
) -> Optional[Device]:
|
||||||
|
"""
|
||||||
|
Update device online status
|
||||||
|
|
||||||
|
Args:
|
||||||
|
device_id: Device unique ID
|
||||||
|
is_online: Whether device is online
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Updated device instance or None if not found
|
||||||
|
"""
|
||||||
|
device = await self.repo.find_by_id(device_id)
|
||||||
|
if not device:
|
||||||
|
return None
|
||||||
|
|
||||||
|
device.is_online = is_online
|
||||||
|
device.last_seen_at = datetime.now(timezone.utc)
|
||||||
|
device.updated_at = datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
device = await self.repo.save(device)
|
||||||
|
|
||||||
|
logger.info(f"Updated device status: {device_id} (online={is_online})")
|
||||||
|
|
||||||
|
return device
|
||||||
|
|
||||||
|
|
||||||
|
def get_device_service(db: AsyncSession) -> DeviceService:
|
||||||
|
"""
|
||||||
|
Dependency function to get Device service
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db: Database session
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
DeviceService instance
|
||||||
|
"""
|
||||||
|
return DeviceService(db)
|
||||||
|
|
||||||
13
main/live-agent-api/templates/__init__.py
Normal file
13
main/live-agent-api/templates/__init__.py
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
"""
|
||||||
|
Templates Package
|
||||||
|
|
||||||
|
Agent templates and template loader.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from .loader import AgentTemplate, TemplateLoader
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"AgentTemplate",
|
||||||
|
"TemplateLoader",
|
||||||
|
]
|
||||||
|
|
||||||
70
main/live-agent-api/templates/health_wellness.yaml
Normal file
70
main/live-agent-api/templates/health_wellness.yaml
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
wake_word: Alice
|
||||||
|
language: en
|
||||||
|
greeting: Hello! I'm here to support your health and wellness journey. How can I assist you today?
|
||||||
|
profile: |
|
||||||
|
# Personality
|
||||||
|
|
||||||
|
You are a supportive and knowledgeable health and wellness companion.
|
||||||
|
You are empathetic, non-judgmental, and focused on holistic well-being.
|
||||||
|
You promote healthy habits and sustainable lifestyle changes.
|
||||||
|
|
||||||
|
# Environment
|
||||||
|
|
||||||
|
You are assisting the user via voice interaction.
|
||||||
|
The user is interested in improving their physical, mental, or emotional health.
|
||||||
|
You provide guidance and support, but are not a replacement for professional medical advice.
|
||||||
|
|
||||||
|
# Tone
|
||||||
|
|
||||||
|
Your responses are caring, supportive, and motivating.
|
||||||
|
You use gentle, encouraging language that promotes positive change.
|
||||||
|
You acknowledge challenges while focusing on solutions and progress.
|
||||||
|
You are informative but avoid being preachy or judgmental.
|
||||||
|
|
||||||
|
# Goal
|
||||||
|
|
||||||
|
Your primary goal is to support the user's health and wellness journey:
|
||||||
|
|
||||||
|
1. Healthy Habits:
|
||||||
|
|
||||||
|
- Help establish and maintain healthy routines.
|
||||||
|
- Track wellness goals (exercise, nutrition, sleep, hydration).
|
||||||
|
- Provide reminders and encouragement for healthy behaviors.
|
||||||
|
- Celebrate milestones and progress.
|
||||||
|
|
||||||
|
2. Mindfulness & Mental Health:
|
||||||
|
|
||||||
|
- Guide simple meditation and breathing exercises.
|
||||||
|
- Offer stress management techniques.
|
||||||
|
- Encourage self-care and work-life balance.
|
||||||
|
- Provide emotional support and active listening.
|
||||||
|
|
||||||
|
3. Fitness Support:
|
||||||
|
|
||||||
|
- Suggest appropriate exercises based on fitness level.
|
||||||
|
- Help set realistic fitness goals.
|
||||||
|
- Provide motivation and workout reminders.
|
||||||
|
- Track progress and adjust plans as needed.
|
||||||
|
|
||||||
|
4. Nutrition Guidance:
|
||||||
|
|
||||||
|
- Offer general nutrition information and healthy eating tips.
|
||||||
|
- Help track meals and water intake.
|
||||||
|
- Suggest balanced meal ideas.
|
||||||
|
- Promote mindful eating practices.
|
||||||
|
|
||||||
|
# Guardrails
|
||||||
|
|
||||||
|
NEVER provide medical diagnoses or treatment recommendations.
|
||||||
|
ALWAYS encourage users to consult healthcare professionals for medical concerns.
|
||||||
|
Focus on general wellness information, not specific medical advice.
|
||||||
|
Be sensitive to potential eating disorders or mental health crises.
|
||||||
|
If a user expresses thoughts of self-harm, immediately recommend professional help.
|
||||||
|
Respect individual differences in body types, abilities, and health goals.
|
||||||
|
Promote balanced, sustainable approaches rather than extreme methods.
|
||||||
|
|
||||||
|
# Tools
|
||||||
|
|
||||||
|
No tools provided.
|
||||||
|
timezone: UTC+8
|
||||||
|
|
||||||
57
main/live-agent-api/templates/hospital_assistant.yaml
Normal file
57
main/live-agent-api/templates/hospital_assistant.yaml
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
wake_word: Alice
|
||||||
|
language: en
|
||||||
|
greeting: Hi! How can I help you today?
|
||||||
|
profile: |
|
||||||
|
# Personality
|
||||||
|
|
||||||
|
You are a personal assistant designed to help users manage their daily hospital-related tasks.
|
||||||
|
You are efficient, organized, and detail-oriented.
|
||||||
|
You are friendly and helpful, but primarily focused on task completion.
|
||||||
|
|
||||||
|
# Environment
|
||||||
|
|
||||||
|
You are assisting the user via voice interaction.
|
||||||
|
The user is likely a healthcare professional working in a hospital setting.
|
||||||
|
The user is seeking assistance with their daily tasks.
|
||||||
|
|
||||||
|
# Tone
|
||||||
|
|
||||||
|
Your responses are clear, concise, and professional.
|
||||||
|
You use direct language and avoid unnecessary jargon.
|
||||||
|
You are polite and helpful, but prioritize efficiency.
|
||||||
|
|
||||||
|
# Goal
|
||||||
|
|
||||||
|
Your primary goal is to help the user efficiently process their daily hospital tasks through a structured workflow:
|
||||||
|
|
||||||
|
1. Task Identification:
|
||||||
|
|
||||||
|
- Identify the specific task the user needs assistance with (e.g., scheduling appointments, managing patient records, ordering supplies, etc.).
|
||||||
|
- Clarify any specific requirements or constraints for the task.
|
||||||
|
|
||||||
|
2. Task Execution:
|
||||||
|
|
||||||
|
- Provide step-by-step instructions for completing the task.
|
||||||
|
- Offer helpful tips and shortcuts to improve efficiency.
|
||||||
|
- If possible, automate parts of the task using available tools.
|
||||||
|
|
||||||
|
3. Task Confirmation:
|
||||||
|
|
||||||
|
- Confirm that the task has been completed successfully.
|
||||||
|
- Offer to assist with any follow-up tasks or related activities.
|
||||||
|
|
||||||
|
4. Task Logging:
|
||||||
|
|
||||||
|
- Automatically log the task and its completion status for future reference.
|
||||||
|
|
||||||
|
# Guardrails
|
||||||
|
|
||||||
|
Remain within the scope of hospital-related tasks.
|
||||||
|
Never provide medical advice or make clinical decisions.
|
||||||
|
Protect patient privacy and confidentiality at all times.
|
||||||
|
If you are unsure about something, ask for clarification.
|
||||||
|
|
||||||
|
# Tools
|
||||||
|
|
||||||
|
No tools provided.
|
||||||
|
timezone: UTC+8
|
||||||
68
main/live-agent-api/templates/learning_companion.yaml
Normal file
68
main/live-agent-api/templates/learning_companion.yaml
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
wake_word: Alice
|
||||||
|
language: en
|
||||||
|
greeting: Hi there! I'm excited to help you learn today. What would you like to explore?
|
||||||
|
profile: |
|
||||||
|
# Personality
|
||||||
|
|
||||||
|
You are an enthusiastic and patient learning companion dedicated to helping users expand their knowledge.
|
||||||
|
You are encouraging, curious, and passionate about education.
|
||||||
|
You make learning fun and engaging while maintaining high educational standards.
|
||||||
|
|
||||||
|
# Environment
|
||||||
|
|
||||||
|
You are assisting the user via voice interaction.
|
||||||
|
The user is actively seeking to learn new concepts, skills, or subjects.
|
||||||
|
You adapt your teaching style to match the user's learning pace and preferences.
|
||||||
|
|
||||||
|
# Tone
|
||||||
|
|
||||||
|
Your responses are encouraging, clear, and pedagogically sound.
|
||||||
|
You use analogies, examples, and real-world connections to make concepts relatable.
|
||||||
|
You celebrate progress and gently guide through challenges.
|
||||||
|
You ask thought-provoking questions to deepen understanding.
|
||||||
|
|
||||||
|
# Goal
|
||||||
|
|
||||||
|
Your primary goal is to facilitate effective and enjoyable learning experiences:
|
||||||
|
|
||||||
|
1. Concept Explanation:
|
||||||
|
|
||||||
|
- Break down complex topics into digestible chunks.
|
||||||
|
- Use multiple approaches (visual, verbal, practical) to explain concepts.
|
||||||
|
- Provide relevant examples and analogies.
|
||||||
|
- Check for understanding before moving forward.
|
||||||
|
|
||||||
|
2. Active Learning:
|
||||||
|
|
||||||
|
- Ask questions that promote critical thinking.
|
||||||
|
- Encourage the user to explain concepts in their own words.
|
||||||
|
- Provide practice problems and exercises.
|
||||||
|
- Offer constructive feedback on responses.
|
||||||
|
|
||||||
|
3. Study Support:
|
||||||
|
|
||||||
|
- Help create effective study plans and schedules.
|
||||||
|
- Suggest memory techniques and learning strategies.
|
||||||
|
- Assist with exam preparation and review.
|
||||||
|
- Provide motivation and study tips.
|
||||||
|
|
||||||
|
4. Knowledge Building:
|
||||||
|
|
||||||
|
- Connect new information to existing knowledge.
|
||||||
|
- Highlight patterns and relationships between concepts.
|
||||||
|
- Encourage curiosity and further exploration.
|
||||||
|
- Recommend additional resources for deeper learning.
|
||||||
|
|
||||||
|
# Guardrails
|
||||||
|
|
||||||
|
Adapt to the user's current knowledge level and learning pace.
|
||||||
|
Never provide direct answers to homework or test questions without guiding the learning process.
|
||||||
|
Encourage independent thinking and problem-solving.
|
||||||
|
If a topic is outside your expertise, acknowledge it and suggest reliable resources.
|
||||||
|
Maintain a supportive environment that makes mistakes feel safe and valuable.
|
||||||
|
|
||||||
|
# Tools
|
||||||
|
|
||||||
|
No tools provided.
|
||||||
|
timezone: UTC+8
|
||||||
|
|
||||||
118
main/live-agent-api/templates/loader.py
Normal file
118
main/live-agent-api/templates/loader.py
Normal file
|
|
@ -0,0 +1,118 @@
|
||||||
|
"""
|
||||||
|
Template Loader
|
||||||
|
|
||||||
|
Utility for loading agent templates from YAML files.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
import logging
|
||||||
|
from typing import Optional
|
||||||
|
from pathlib import Path
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class AgentTemplate(BaseModel):
|
||||||
|
"""
|
||||||
|
Agent template data structure
|
||||||
|
|
||||||
|
Pydantic model for validating and handling agent template data.
|
||||||
|
"""
|
||||||
|
|
||||||
|
wake_word: str = Field(..., description="Wake word to activate agent")
|
||||||
|
language: str = Field(..., description="Language code (e.g., en, zh)")
|
||||||
|
greeting: str = Field(..., description="Greeting message (maps to first_message)")
|
||||||
|
profile: str = Field(..., description="System prompt (maps to system_prompt)")
|
||||||
|
timezone: str = Field(default="UTC+8", description="Timezone")
|
||||||
|
|
||||||
|
model_config = {
|
||||||
|
"json_schema_extra": {
|
||||||
|
"example": {
|
||||||
|
"wake_word": "Hey Assistant",
|
||||||
|
"language": "en",
|
||||||
|
"greeting": "Hello! How can I help you?",
|
||||||
|
"profile": "You are a helpful assistant...",
|
||||||
|
"timezone": "UTC+8"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TemplateLoader:
|
||||||
|
"""
|
||||||
|
Template loader class with static methods for loading agent templates
|
||||||
|
|
||||||
|
All methods are static, no instance needed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Template directory path (relative to this file)
|
||||||
|
TEMPLATE_DIR = Path(__file__).parent
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def load(template_name: str) -> Optional[AgentTemplate]:
|
||||||
|
"""
|
||||||
|
Load agent template from YAML file
|
||||||
|
|
||||||
|
Args:
|
||||||
|
template_name: Template name (e.g., "personal_assistant", "learning_companion")
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
AgentTemplate instance or None if template is "blank"
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If template file is invalid or missing required fields
|
||||||
|
"""
|
||||||
|
# Special case: blank template
|
||||||
|
if template_name == "blank":
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Construct template file path
|
||||||
|
template_file = TemplateLoader.TEMPLATE_DIR / f"{template_name}.yaml"
|
||||||
|
|
||||||
|
# Check if template exists
|
||||||
|
if not template_file.exists():
|
||||||
|
logger.error(f"Template file not found: {template_file}")
|
||||||
|
raise ValueError(f"Template '{template_name}' does not exist")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Load YAML file
|
||||||
|
with open(template_file, 'r', encoding='utf-8') as f:
|
||||||
|
data = yaml.safe_load(f)
|
||||||
|
|
||||||
|
# Validate and create template using Pydantic
|
||||||
|
template = AgentTemplate(**data)
|
||||||
|
|
||||||
|
logger.info(f"Loaded template: {template_name}")
|
||||||
|
return template
|
||||||
|
|
||||||
|
except yaml.YAMLError as e:
|
||||||
|
logger.error(f"Error parsing YAML file {template_file}: {e}")
|
||||||
|
raise ValueError(f"Template '{template_name}' has invalid YAML format: {e}")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error loading template {template_name}: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def list_available() -> list[str]:
|
||||||
|
"""
|
||||||
|
List all available template names
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List of template names (without .yaml extension)
|
||||||
|
"""
|
||||||
|
if not TemplateLoader.TEMPLATE_DIR.exists():
|
||||||
|
logger.warning(f"Template directory not found: {TemplateLoader.TEMPLATE_DIR}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
templates = []
|
||||||
|
for file in TemplateLoader.TEMPLATE_DIR.glob("*.yaml"):
|
||||||
|
templates.append(file.stem)
|
||||||
|
|
||||||
|
# Always include blank template
|
||||||
|
templates.append("blank")
|
||||||
|
|
||||||
|
logger.info(f"Available templates: {templates}")
|
||||||
|
return sorted(templates)
|
||||||
|
|
||||||
62
main/live-agent-api/templates/personal_assistant.yaml
Normal file
62
main/live-agent-api/templates/personal_assistant.yaml
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
wake_word: Charlie
|
||||||
|
language: en
|
||||||
|
greeting: Hello! I'm your personal assistant. How can I help you today?
|
||||||
|
profile: |
|
||||||
|
# Personality
|
||||||
|
|
||||||
|
You are a versatile personal assistant designed to help users manage their daily tasks and activities.
|
||||||
|
You are friendly, proactive, and highly organized.
|
||||||
|
You anticipate user needs and offer helpful suggestions.
|
||||||
|
|
||||||
|
# Environment
|
||||||
|
|
||||||
|
You are assisting the user via voice interaction.
|
||||||
|
The user relies on you for various personal and professional tasks.
|
||||||
|
You have access to the user's schedule, reminders, and preferences.
|
||||||
|
|
||||||
|
# Tone
|
||||||
|
|
||||||
|
Your responses are warm, conversational, and supportive.
|
||||||
|
You use clear language and explain things in a way that's easy to understand.
|
||||||
|
You are encouraging and positive, helping the user stay motivated and productive.
|
||||||
|
|
||||||
|
# Goal
|
||||||
|
|
||||||
|
Your primary goal is to help the user manage their daily life efficiently:
|
||||||
|
|
||||||
|
1. Task Management:
|
||||||
|
|
||||||
|
- Help create, organize, and prioritize tasks.
|
||||||
|
- Set reminders for important deadlines and appointments.
|
||||||
|
- Suggest optimal times for task completion based on the user's schedule.
|
||||||
|
|
||||||
|
2. Information Assistance:
|
||||||
|
|
||||||
|
- Answer questions on a wide range of topics.
|
||||||
|
- Provide quick facts, definitions, and explanations.
|
||||||
|
- Help with research and information gathering.
|
||||||
|
|
||||||
|
3. Productivity Support:
|
||||||
|
|
||||||
|
- Offer time management tips and strategies.
|
||||||
|
- Help break down complex projects into manageable steps.
|
||||||
|
- Suggest productivity techniques like Pomodoro or time blocking.
|
||||||
|
|
||||||
|
4. Personal Organization:
|
||||||
|
|
||||||
|
- Manage calendar events and appointments.
|
||||||
|
- Keep track of shopping lists and to-dos.
|
||||||
|
- Help organize notes and ideas.
|
||||||
|
|
||||||
|
# Guardrails
|
||||||
|
|
||||||
|
Respect user privacy and confidentiality at all times.
|
||||||
|
Stay within the scope of general assistance and avoid specialized professional advice.
|
||||||
|
If you're unsure about something, admit it and offer to help find accurate information.
|
||||||
|
Never make decisions that could have serious consequences without user confirmation.
|
||||||
|
|
||||||
|
# Tools
|
||||||
|
|
||||||
|
No tools provided.
|
||||||
|
timezone: UTC+8
|
||||||
|
|
||||||
|
|
@ -0,0 +1,18 @@
|
||||||
|
"""
|
||||||
|
Utils package for live-agent-api
|
||||||
|
|
||||||
|
This package provides utility modules for the application,
|
||||||
|
including ID generation and response formatting.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
from utils import id_generator
|
||||||
|
|
||||||
|
# Generate ID using the global singleton instance
|
||||||
|
new_id = id_generator.generate()
|
||||||
|
"""
|
||||||
|
|
||||||
|
from .id_generator import id_generator
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"id_generator", # Global singleton instance (recommended usage)
|
||||||
|
]
|
||||||
|
|
@ -1,125 +1,75 @@
|
||||||
"""
|
"""
|
||||||
Snowflake ID Generator
|
ULID ID Generator
|
||||||
|
|
||||||
Wrapper around the snowflake-id library for generating distributed unique IDs.
|
ULID (Universally Unique Lexicographically Sortable Identifier) generator.
|
||||||
Uses Twitter's Snowflake algorithm to generate 64-bit IDs.
|
- Zero configuration: No instance ID or epoch setup needed
|
||||||
|
- Time-sortable: IDs are naturally ordered by creation time
|
||||||
|
- URL-safe: Base32 encoded
|
||||||
|
- 128-bit: Extremely low collision probability
|
||||||
|
- Format: 26 characters (e.g., 01ARZ3NDEKTSV4RRFFQ69G5FAV)
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from snowflake import SnowflakeGenerator
|
from ulid import ULID
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# Global ID generator instance
|
|
||||||
_id_generator: Optional[SnowflakeGenerator] = None
|
|
||||||
|
|
||||||
|
class ULIDGenerator:
|
||||||
def get_id_generator() -> SnowflakeGenerator:
|
|
||||||
"""
|
"""
|
||||||
Get the global ID generator instance
|
ULID ID Generator
|
||||||
|
|
||||||
|
A singleton class for generating distributed unique IDs using ULID.
|
||||||
|
Thread-safe and requires no configuration.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
generator = ULIDGenerator()
|
||||||
|
id_str = generator.generate()
|
||||||
|
id_int = generator.generate_int()
|
||||||
|
id_uuid = generator.generate_uuid()
|
||||||
|
"""
|
||||||
|
|
||||||
|
_instance: Optional['ULIDGenerator'] = None
|
||||||
|
_initialized: bool = False
|
||||||
|
|
||||||
|
def __new__(cls) -> ULIDGenerator:
|
||||||
|
"""Ensure singleton pattern"""
|
||||||
|
if cls._instance is None:
|
||||||
|
cls._instance = super().__new__(cls)
|
||||||
|
return cls._instance
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""
|
||||||
|
Initialize ULID generator
|
||||||
|
|
||||||
|
Note: Due to singleton pattern, __init__ is called every time
|
||||||
|
ULIDGenerator() is invoked, but initialization only happens once.
|
||||||
|
"""
|
||||||
|
if not self._initialized:
|
||||||
|
logger.info("Initializing ULID generator (singleton)")
|
||||||
|
self.__class__._initialized = True
|
||||||
|
logger.info("ULID generator initialized successfully")
|
||||||
|
|
||||||
|
def generate(self) -> str:
|
||||||
|
"""
|
||||||
|
Generate a unique ULID as string
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Snowflake ID generator instance
|
26-character ULID string (e.g., '01ARZ3NDEKTSV4RRFFQ69G5FAV')
|
||||||
|
|
||||||
Raises:
|
Example:
|
||||||
RuntimeError: If generator is not initialized
|
>>> generator = ULIDGenerator()
|
||||||
|
>>> id_str = generator.generate()
|
||||||
|
>>> print(id_str)
|
||||||
|
'01ARZ3NDEKTSV4RRFFQ69G5FAV'
|
||||||
"""
|
"""
|
||||||
global _id_generator
|
return str(ULID())
|
||||||
|
|
||||||
if _id_generator is None:
|
def __repr__(self) -> str:
|
||||||
raise RuntimeError(
|
"""String representation"""
|
||||||
"ID generator not initialized. "
|
return f"<ULIDGenerator (singleton)>"
|
||||||
"Call init_id_generator() in application lifespan."
|
|
||||||
)
|
|
||||||
|
|
||||||
return _id_generator
|
|
||||||
|
|
||||||
|
|
||||||
def generate_id() -> str:
|
# Create global singleton instance
|
||||||
"""
|
id_generator = ULIDGenerator()
|
||||||
Generate a unique Snowflake ID as string
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Unique ID as string
|
|
||||||
"""
|
|
||||||
generator = get_id_generator()
|
|
||||||
return str(next(generator))
|
|
||||||
|
|
||||||
|
|
||||||
def generate_id_int() -> int:
|
|
||||||
"""
|
|
||||||
Generate a unique Snowflake ID as integer
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Unique 64-bit integer ID
|
|
||||||
"""
|
|
||||||
generator = get_id_generator()
|
|
||||||
return next(generator)
|
|
||||||
|
|
||||||
|
|
||||||
def init_id_generator(instance_id: int = 1) -> None:
|
|
||||||
"""
|
|
||||||
Initialize global Snowflake ID generator
|
|
||||||
|
|
||||||
Should be called once during application startup in lifespan.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
instance_id: Unique instance ID for this service (0-1023)
|
|
||||||
In production, this should be:
|
|
||||||
- Stored in a distributed configuration center (e.g., etcd, Consul)
|
|
||||||
- Automatically assigned when service instances start
|
|
||||||
- Managed by orchestration system (e.g., Kubernetes StatefulSet)
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
ValueError: If instance_id is out of valid range
|
|
||||||
"""
|
|
||||||
global _id_generator
|
|
||||||
|
|
||||||
# Already initialized
|
|
||||||
if _id_generator is not None:
|
|
||||||
logger.warning("ID generator already initialized, skipping")
|
|
||||||
return
|
|
||||||
|
|
||||||
# Validate instance_id
|
|
||||||
if instance_id < 0 or instance_id > 1023:
|
|
||||||
raise ValueError(
|
|
||||||
f"Instance ID must be between 0 and 1023, got {instance_id}"
|
|
||||||
)
|
|
||||||
|
|
||||||
_id_generator = SnowflakeGenerator(instance_id)
|
|
||||||
logger.info(f"ID generator initialized with instance_id={instance_id}")
|
|
||||||
|
|
||||||
|
|
||||||
def close_id_generator() -> None:
|
|
||||||
"""
|
|
||||||
Close and cleanup ID generator
|
|
||||||
|
|
||||||
Optional cleanup function for application shutdown.
|
|
||||||
"""
|
|
||||||
global _id_generator
|
|
||||||
|
|
||||||
if _id_generator is not None:
|
|
||||||
logger.info("Closing ID generator...")
|
|
||||||
_id_generator = None
|
|
||||||
logger.info("ID generator closed")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
# Test ID generation
|
|
||||||
print("Testing Snowflake ID Generator")
|
|
||||||
print("=" * 50)
|
|
||||||
|
|
||||||
# Initialize with instance ID 1
|
|
||||||
init_id_generator(instance_id=1)
|
|
||||||
|
|
||||||
print("\nGenerating 10 sample IDs:")
|
|
||||||
for i in range(10):
|
|
||||||
id_str = generate_id()
|
|
||||||
print(f" {i+1:2d}. {id_str}")
|
|
||||||
|
|
||||||
print("\nAll IDs generated successfully!")
|
|
||||||
|
|
||||||
# Cleanup
|
|
||||||
close_id_generator()
|
|
||||||
|
|
|
||||||
|
|
@ -334,7 +334,8 @@ dependencies = [
|
||||||
{ name = "pydantic" },
|
{ name = "pydantic" },
|
||||||
{ name = "pydantic-settings" },
|
{ name = "pydantic-settings" },
|
||||||
{ name = "python-dotenv" },
|
{ name = "python-dotenv" },
|
||||||
{ name = "snowflake-id" },
|
{ name = "python-ulid" },
|
||||||
|
{ name = "pyyaml" },
|
||||||
{ name = "sqlalchemy" },
|
{ name = "sqlalchemy" },
|
||||||
{ name = "uvicorn", extra = ["standard"] },
|
{ name = "uvicorn", extra = ["standard"] },
|
||||||
]
|
]
|
||||||
|
|
@ -356,7 +357,8 @@ requires-dist = [
|
||||||
{ name = "pydantic", specifier = ">=2.9.0" },
|
{ name = "pydantic", specifier = ">=2.9.0" },
|
||||||
{ name = "pydantic-settings", specifier = ">=2.6.0" },
|
{ name = "pydantic-settings", specifier = ">=2.6.0" },
|
||||||
{ name = "python-dotenv", specifier = ">=1.0.0" },
|
{ name = "python-dotenv", specifier = ">=1.0.0" },
|
||||||
{ name = "snowflake-id", specifier = ">=1.0.2" },
|
{ name = "python-ulid", specifier = ">=2.7.0" },
|
||||||
|
{ name = "pyyaml", specifier = ">=6.0.0" },
|
||||||
{ name = "sqlalchemy", specifier = ">=2.0.36" },
|
{ name = "sqlalchemy", specifier = ">=2.0.36" },
|
||||||
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.32.0" },
|
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.32.0" },
|
||||||
]
|
]
|
||||||
|
|
@ -576,6 +578,15 @@ wheels = [
|
||||||
{ url = "https://files.pythonhosted.org/packages/14/1b/a298b06749107c305e1fe0f814c6c74aea7b2f1e10989cb30f544a1b3253/python_dotenv-1.2.1-py3-none-any.whl", hash = "sha256:b81ee9561e9ca4004139c6cbba3a238c32b03e4894671e181b671e8cb8425d61", size = 21230, upload-time = "2025-10-26T15:12:09.109Z" },
|
{ url = "https://files.pythonhosted.org/packages/14/1b/a298b06749107c305e1fe0f814c6c74aea7b2f1e10989cb30f544a1b3253/python_dotenv-1.2.1-py3-none-any.whl", hash = "sha256:b81ee9561e9ca4004139c6cbba3a238c32b03e4894671e181b671e8cb8425d61", size = 21230, upload-time = "2025-10-26T15:12:09.109Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "python-ulid"
|
||||||
|
version = "3.1.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/40/7e/0d6c82b5ccc71e7c833aed43d9e8468e1f2ff0be1b3f657a6fcafbb8433d/python_ulid-3.1.0.tar.gz", hash = "sha256:ff0410a598bc5f6b01b602851a3296ede6f91389f913a5d5f8c496003836f636", size = 93175, upload-time = "2025-08-18T16:09:26.305Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/6c/a0/4ed6632b70a52de845df056654162acdebaf97c20e3212c559ac43e7216e/python_ulid-3.1.0-py3-none-any.whl", hash = "sha256:e2cdc979c8c877029b4b7a38a6fba3bc4578e4f109a308419ff4d3ccf0a46619", size = 11577, upload-time = "2025-08-18T16:09:25.047Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pytokens"
|
name = "pytokens"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
|
|
@ -666,15 +677,6 @@ wheels = [
|
||||||
{ url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235, upload-time = "2024-02-25T23:20:01.196Z" },
|
{ url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235, upload-time = "2024-02-25T23:20:01.196Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "snowflake-id"
|
|
||||||
version = "1.0.2"
|
|
||||||
source = { registry = "https://pypi.org/simple" }
|
|
||||||
sdist = { url = "https://files.pythonhosted.org/packages/7a/d0/91bd3d2e54ea849e8c4e73681ef75c1c93f37a8c9f0627b1553522267e08/snowflake_id-1.0.2.tar.gz", hash = "sha256:4a4cd49508599aaa16488311f4b9121e9ac3bac57edff3e9f71b1d79086dbfe8", size = 4497, upload-time = "2024-04-17T13:36:05.552Z" }
|
|
||||||
wheels = [
|
|
||||||
{ url = "https://files.pythonhosted.org/packages/41/a4/ee0bdba1d1e98db21166381559d0061d752bbf66af2dd1cbbe4c2afdc4fa/snowflake_id-1.0.2-py3-none-any.whl", hash = "sha256:c3142752ed334b9d4632739a704461d13e97aa6fa71b65d5329829b4b5cc058c", size = 4795, upload-time = "2024-04-17T13:36:03.898Z" },
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sqlalchemy"
|
name = "sqlalchemy"
|
||||||
version = "2.0.44"
|
version = "2.0.44"
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue