Merge pull request #10 from Plaud-AI/feat/demo

feat: Initial implementation of Live Agent API backend service
This commit is contained in:
Harold-Guo 2025-11-21 16:49:20 +08:00 committed by GitHub
commit cc5608da79
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
44 changed files with 4818 additions and 0 deletions

View file

@ -0,0 +1,35 @@
# Live Agent API Environment Configuration
# Copy this file to .env and update the values
# ==================== S3/MinIO Configuration ====================
# For local development with MinIO
AWS_ACCESS_KEY_ID=minioadmin
AWS_SECRET_ACCESS_KEY=minioadmin
AWS_REGION=us-east-1
S3_BUCKET_NAME=live-agent-files
# For production with AWS S3, use your actual credentials:
# AWS_ACCESS_KEY_ID=your-aws-access-key
# AWS_SECRET_ACCESS_KEY=your-aws-secret-key
# AWS_REGION=ap-northeast-1
# S3_BUCKET_NAME=your-production-bucket
# ==================== Security ====================
SECRET_KEY=dev-secret-key-change-in-production
# ==================== Token Configuration ====================
TOKEN_EXPIRE_DAYS=7
# ==================== Server Configuration ====================
# These are optional, defaults are set in settings.py
# HOST=0.0.0.0
# PORT=8080
# DEBUG=False
# ==================== Database Configuration ====================
# This is overridden in docker-compose.yml for container environment
# For local development without Docker, use:
# DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/live_agent
FISH_API_KEY=your-fish-api-key

61
main/live-agent-api/.gitignore vendored Normal file
View file

@ -0,0 +1,61 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# Virtual Environment
.venv/
venv/
ENV/
env/
# Environment variables
.env
.env.local
.env.*.local
!.env.example
!env.example
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
.DS_Store
# Database
*.db
*.sqlite
# Logs
*.log
logs/
# Testing
.pytest_cache/
.coverage
htmlcov/
# Docker
docker-compose.override.yml
# Data volumes
data/

View file

@ -0,0 +1 @@
3.12

View file

@ -0,0 +1,19 @@
FROM python:3.12-slim
WORKDIR /app
# Install uv
RUN pip install uv
# Copy project files
COPY . /app/
# Install dependencies using uv
RUN uv sync --no-dev
# Expose port
EXPOSE 8080
# Run the application
CMD [".venv/bin/python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]

View file

View file

@ -0,0 +1,38 @@
from fastapi import Header, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi import Depends
from utils.security import verify_jwt_token
from utils.exceptions import UnauthorizedException
# Define Bearer token security scheme
security = HTTPBearer()
async def get_current_user_id(
credentials: HTTPAuthorizationCredentials = Depends(security)
) -> str:
"""
Get current user ID from JWT Bearer token (no database query)
This is the recommended dependency for most APIs that only need user_id.
It's faster because it doesn't query the database.
Usage:
Authorization: Bearer <jwt_token>
Flow:
1. Extract Bearer token from Authorization header
2. Verify JWT token (signature, expiration)
3. Extract and return user_id from token payload
"""
token = credentials.credentials
# Verify JWT token and extract payload
payload = verify_jwt_token(token)
if not payload:
raise UnauthorizedException("Invalid or expired token")
return payload['user_id']

View file

@ -0,0 +1,40 @@
from fastapi import APIRouter
from api.v1 import user, templates, agents, voices, internal
api_router = APIRouter()
# User authentication routes
api_router.include_router(
user.router,
prefix="/user",
tags=["Account","Authentication"]
)
# Template routes
api_router.include_router(
templates.router,
prefix="/templates",
tags=["Templates"]
)
# Agent routes
api_router.include_router(
agents.router,
prefix="/agents",
tags=["Agents"]
)
# Voice routes
api_router.include_router(
voices.router,
prefix="/voices",
tags=["Voices"]
)
# Internal routes (for xiaozhi-server)
api_router.include_router(
internal.router,
prefix="/internal",
tags=["Internal"]
)

View file

@ -0,0 +1,124 @@
from typing import Optional
from fastapi import APIRouter, Depends, Query, Form, File, UploadFile
from sqlalchemy.ext.asyncio import AsyncSession
from infra import get_db, get_s3
from services.agent_service import agent_service
from utils.response import success_response
from api.auth import get_current_user_id
router = APIRouter()
@router.get("", summary="Get user's agent list")
async def get_agent_list(
cursor: Optional[str] = Query(None, description="Pagination cursor"),
page_size: int = Query(10, ge=1, le=20, description="Number of items per page"),
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
Get user's agent list with cursor-based pagination
Cursor-based pagination prevents data drift when creating/deleting agents:
- **First request**: No cursor parameter needed
- **Subsequent requests**: Use `next_cursor` from previous response
- **Returns**: List of agents with `next_cursor` and `has_more` flag
Agents are ordered by creation time (newest first).
"""
agent_list = await agent_service.get_agent_list(
db=db,
owner_id=current_user_id,
cursor=cursor,
page_size=page_size
)
return success_response(data=agent_list.model_dump())
@router.get("/{agent_id}", summary="Get Agent Detail")
async def get_agent_detail(
agent_id: str,
db: AsyncSession = Depends(get_db)
):
"""Get agent detail"""
agent = await agent_service.get_agent_detail(db=db, agent_id=agent_id)
return success_response(data=agent.model_dump())
@router.post("", summary="Create Agent")
async def create_agent(
name: str = Form(...),
instruction: str = Form(...),
description: Optional[str] = Form(None),
voice_id: Optional[str] = Form(None),
voice_opening: Optional[str] = Form(None),
voice_closing: Optional[str] = Form(None),
avatar: Optional[UploadFile] = File(None),
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db),
s3 = Depends(get_s3)
):
"""Create a new agent"""
agent = await agent_service.create_agent(
db=db,
s3=s3,
owner_id=current_user_id,
name=name,
instruction=instruction,
description=description,
voice_id=voice_id,
voice_opening=voice_opening,
voice_closing=voice_closing,
avatar=avatar
)
return success_response(data=agent.model_dump())
@router.put("/{agent_id}", summary="Update Agent")
async def update_agent(
agent_id: str,
name: Optional[str] = Form(None),
description: Optional[str] = Form(None),
voice_id: Optional[str] = Form(None),
instruction: Optional[str] = Form(None),
voice_opening: Optional[str] = Form(None),
voice_closing: Optional[str] = Form(None),
avatar: Optional[UploadFile] = File(None),
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db),
s3 = Depends(get_s3)
):
"""Update agent"""
agent = await agent_service.update_agent(
db=db,
s3=s3,
agent_id=agent_id,
owner_id=current_user_id,
name=name,
description=description,
voice_id=voice_id,
instruction=instruction,
voice_opening=voice_opening,
voice_closing=voice_closing,
avatar=avatar
)
return success_response(data=agent.model_dump())
@router.delete("/{agent_id}", summary="Delete Agent")
async def delete_agent(
agent_id: str,
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db),
s3 = Depends(get_s3)
):
"""Delete agent"""
await agent_service.delete_agent(
db=db,
s3=s3,
agent_id=agent_id,
owner_id=current_user_id
)
return success_response(data={}, message="Agent deleted successfully")

View file

@ -0,0 +1,19 @@
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from infra import get_db
from services.agent_service import agent_service
from utils.response import success_response
router = APIRouter()
@router.get("/agents/{agent_id}/config", summary="Get a specified agent's config")
async def get_agent_config(
agent_id: str,
db: AsyncSession = Depends(get_db)
):
"""Get agent configuration for xiaozhi-server"""
config = await agent_service.get_agent_config(db=db, agent_id=agent_id)
return success_response(data=config.model_dump())

View file

@ -0,0 +1,18 @@
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from infra import get_db
from services.agent_service import agent_service
from utils.response import success_response
router = APIRouter()
@router.get("", summary="Get Agent Templates")
async def get_templates(
db: AsyncSession = Depends(get_db)
):
"""Get all agent templates"""
templates = await agent_service.get_templates(db)
return success_response(data={"templates": [t.model_dump() for t in templates]})

View file

@ -0,0 +1,88 @@
from fastapi import APIRouter, Depends, Header
from sqlalchemy.ext.asyncio import AsyncSession
from infra import get_db
from services.user_service import user_service
from schemas.user import (
UserRegisterRequest,
UserLoginRequest,
PasswordUpdateRequest,
UserInfo
)
from utils.response import success_response
from api.auth import get_current_user_id
from repositories import UserModel
router = APIRouter()
@router.post("/register", summary="Register a new user account under live agent system")
async def register(
request: UserRegisterRequest,
db: AsyncSession = Depends(get_db)
):
"""Register a new user account"""
await user_service.register(
db=db,
username=request.username,
password=request.password
)
return success_response(message="User account registered successfully")
@router.post("/login", summary="User Login for a token")
async def login(
request: UserLoginRequest,
db: AsyncSession = Depends(get_db)
):
"""User login for a token"""
login_response = await user_service.login(
db=db,
username=request.username,
password=request.password
)
return success_response(data=login_response.model_dump())
@router.get("/info", summary="Get User Info")
async def get_user_info(
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""Get current user information"""
user: UserModel = await user_service.get_user_info(db=db, user_id=current_user_id)
user_info = UserInfo(
user_id=user.user_id,
username=user.username,
created_at=user.created_at
)
return success_response(data=user_info.model_dump())
@router.post("/password", summary="Update Password")
async def update_password(
request: PasswordUpdateRequest,
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""Update user password"""
await user_service.update_password(
db=db,
user_id=current_user_id,
old_password=request.old_password,
new_password=request.new_password
)
return success_response(message="Password updated successfully")
@router.post("/logout", summary="User Logout")
async def logout(
token: str = Header(..., description="Authentication token"),
db: AsyncSession = Depends(get_db)
):
"""User logout"""
await user_service.logout(db=db, token=token)
return success_response(message="Logout successful")

View file

@ -0,0 +1,263 @@
from typing import Optional, List
from botocore.args import logger
from fastapi import APIRouter, Depends, Query, Form, File, UploadFile
from sqlalchemy.ext.asyncio import AsyncSession
from infra import get_db
from infra.fishaudio import get_fish_audio
from services.voice_service import voice_service
from schemas.voice import (
LiveAgentVoice,
DiscoverVoiceResponse,
AudioSample,
MyVoiceResponse,
VoiceUpdateRequest,
VoiceAddRequest
)
from utils.response import success_response
from api.auth import get_current_user_id
import logging
router = APIRouter()
logging.getLogger(__name__)
@router.get("/discover", summary="Get Discover Voices")
async def get_discover_voices(
title: Optional[str] = Query(None, description="Filter by voice title/name"),
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
language: Optional[str] = Query(None, description="Filter by language"),
fish_client = Depends(get_fish_audio)
):
"""
Get voices from Fish Audio platform (discover tab)
- Sorted by task_count (popularity)
- Supports filtering by title
"""
# Get raw data from service layer
fish_voices, has_more = await voice_service.get_discover_voices(
fish_client=fish_client,
title=title,
page=page,
page_size=page_size,
language=language
)
# Convert Fish Audio Voice objects to VoiceResponse in API layer
voices = []
for voice in fish_voices:
samples = []
for sample in voice.samples:
samples.append(AudioSample(
title=sample.title,
text=sample.text,
audio=sample.audio
))
logger.info(f"Voice Tags: {voice.tags}")
voices.append(LiveAgentVoice(
voice_id=voice.id,
name=voice.title,
desc=voice.description,
samples=samples,
created_at=voice.created_at,
))
# Build response
voice_list = DiscoverVoiceResponse(
voices=voices,
has_more=has_more
)
return success_response(data=voice_list.model_dump())
@router.get("/default", summary="Get Default Voices")
async def get_default_voices(
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
db: AsyncSession = Depends(get_db)
):
"""
Get platform default voices (default tab)
TODO: Implementation pending PM discussion tomorrow
"""
return success_response(data={})
@router.get("/", summary="Get My Voices")
async def get_my_voices(
cursor: Optional[str] = Query(None, description="Pagination cursor (ISO datetime from previous response)"),
page_size: int = Query(10, ge=1, le=50, description="Number of items per page"),
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
Get user's custom voices with cursor-based pagination
Cursor-based pagination prevents data drift when adding/removing voices:
- **First request**: No cursor parameter needed
- **Subsequent requests**: Use `next_cursor` from previous response
- **Returns**: List of voices with `next_cursor` and `has_more` flag
Voices are ordered by creation time (newest first).
Returns voices created/cloned/added by the current user.
"""
# Get raw data from service layer
voices, next_cursor, has_more = await voice_service.get_my_voices(
db=db,
owner_id=current_user_id,
cursor=cursor,
page_size=page_size
)
# Convert VoiceModel to VoiceResponse in API layer
voice_responses = []
for voice in voices:
voice_responses.append(LiveAgentVoice(
voice_id=voice.voice_id,
name=voice.name,
desc=voice.desc,
created_at=voice.created_at,
))
# Build response
voice_list = MyVoiceResponse(
voices=voice_responses,
next_cursor=next_cursor,
has_more=has_more
)
return success_response(data=voice_list.model_dump())
@router.post("/clone", summary="Clone Voice from Audio")
async def clone_voice(
audio_file: UploadFile = File(..., description="Audio file for cloning"),
text: Optional[str] = Form(None, description="Optional transcription text"),
fish_client = Depends(get_fish_audio)
):
"""
Clone a voice from uploaded audio file
- Supports both direct audio upload and recorded audio
- Text parameter is optional (required for recorded audio)
- Uses Fish Audio's fast training mode (typically 30s-2min)
"""
# Clone voice
voice_id, samples = await voice_service.clone_voice(
fish_client=fish_client,
audio_file=audio_file,
text=text
)
# Build response
if samples:
sample = AudioSample(
title=samples[0].title,
text=samples[0].text,
audio=samples[0].audio
)
else:
sample = None
return success_response(
data={
"voice_id": voice_id,
"sample": sample,
},
message="Voice cloned successfully"
)
@router.post("/add/{voice_id}", summary="Add Fish Voice to My Voices")
async def add_voice(
voice_id: str,
request: VoiceAddRequest,
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db),
fish_client = Depends(get_fish_audio)
):
"""
Add a Fish Audio voice to user's my voices
- Creates a reference to the Fish Audio voice
- Name is provided by client (from Fish voice title)
"""
voice = await voice_service.add_voice(
db=db,
fish_client=fish_client,
owner_id=current_user_id,
voice_id=voice_id,
name=request.name,
desc=request.desc
)
# Build response
return success_response(
data=LiveAgentVoice(
voice_id=voice.voice_id,
name=voice.name,
).model_dump(exclude_none=True),
message="Voice added successfully"
)
@router.put("/{voice_id}", summary="Update Voice")
async def update_voice(
voice_id: str,
request: VoiceUpdateRequest,
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
Update voice name and/or description
- Only the voice owner can update it
- At least one field (name or desc) must be provided
"""
# Check if at least one field is provided
if request.name is None and request.desc is None:
from utils.exceptions import BadRequestException
raise BadRequestException("At least one field (name or desc) must be provided")
voice = await voice_service.update_voice(
db=db,
voice_id=voice_id,
owner_id=current_user_id,
name=request.name,
desc=request.desc
)
return success_response(
data=LiveAgentVoice(
voice_id=voice.voice_id,
name=voice.name,
desc=voice.desc
).model_dump(exclude_none=True),
message="Voice updated successfully"
)
@router.delete("/{voice_id}", summary="Remove Voice from My Voices")
async def remove_voice(
voice_id: str,
current_user_id: str = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""
Remove a voice from user's my voices
- Only deletes the database record (reference)
- User must own the voice
"""
await voice_service.remove_voice(
db=db,
voice_id=voice_id,
owner_id=current_user_id
)
return success_response(
data={"voice_id": voice_id},
message="Voice removed successfully"
)

View file

@ -0,0 +1,4 @@
from .settings import Settings, settings
__all__ = ["Settings", "settings"]

View file

@ -0,0 +1,40 @@
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""Application settings loaded from environment variables"""
# Database Configuration
DATABASE_URL: str
# AWS S3 Configuration
AWS_ACCESS_KEY_ID: str
AWS_SECRET_ACCESS_KEY: str
AWS_REGION: str = "us-east-1"
S3_BUCKET_NAME: str
S3_ENDPOINT_URL: str | None = None
S3_PUBLIC_BASE_URL: str | None = None
# Security
SECRET_KEY: str
# Server Configuration
HOST: str = "0.0.0.0"
PORT: int = 8080
DEBUG: bool = False
# Token Configuration
TOKEN_EXPIRE_DAYS: int = 7
# Fish Audio Configuration
FISH_API_KEY: str
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=True
)
settings = Settings()

View file

@ -0,0 +1,58 @@
services:
postgres:
image: postgres:16-alpine
container_name: live-agent-postgres
environment:
POSTGRES_DB: live_agent
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
ports:
- "5432:5432"
volumes:
- ./data/postgres:/var/lib/postgresql/data
- ./init_db.sql:/docker-entrypoint-initdb.d/init_db.sql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5
minio:
image: minio/minio:latest
container_name: live-agent-minio
command: server /data --console-address ":9001"
environment:
MINIO_ROOT_USER: minioadmin
MINIO_ROOT_PASSWORD: minioadmin
ports:
- "9000:9000" # S3 API port
- "9001:9001" # Web console port
volumes:
- ./data/minio:/data
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
interval: 10s
timeout: 5s
retries: 5
api:
build: .
container_name: live-agent-api
env_file:
- .env
environment:
# Override container-specific settings
DATABASE_URL: postgresql+asyncpg://postgres:postgres@postgres:5432/live_agent
S3_ENDPOINT_URL: http://minio:9000
DEBUG: "True"
ports:
- "8080:8080"
depends_on:
postgres:
condition: service_healthy
minio:
condition: service_healthy
# All data volumes are now stored in ./data/ directory
# No named volumes needed

View file

@ -0,0 +1,46 @@
# Copy this file to .env and fill in your actual values
# Database Configuration
DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/live_agent
# AWS S3 / MinIO Configuration
# S3-compatible storage credentials
AWS_ACCESS_KEY_ID=minioadmin
AWS_SECRET_ACCESS_KEY=minioadmin
# AWS Region (use default for MinIO)
AWS_REGION=us-east-1
# S3 Bucket Name
S3_BUCKET_NAME=test-bucket
# S3 Endpoint URL
# For MinIO local development (outside Docker): http://localhost:9000
# For MinIO inside Docker: http://minio:9000
# For AWS S3: leave empty or comment out
S3_ENDPOINT_URL=http://localhost:9000
# S3 Public Base URL
# This is the URL prefix used to generate public file URLs
# For local MinIO: http://localhost:9000
# For production S3: https://s3.amazonaws.com or your CloudFront URL
S3_PUBLIC_BASE_URL=http://localhost:9000
# Security Configuration
# Secret key for JWT token signing and other security features
# Generate with: python -c "import secrets; print(secrets.token_urlsafe(32))"
SECRET_KEY=your-secret-key-here-change-in-production
# Token expiration time in days
TOKEN_EXPIRE_DAYS=7
# Server Configuration
HOST=0.0.0.0
PORT=8080
# Debug mode (set to False in production)
DEBUG=True
# External Services
FISH_API_KEY=your-fish-audio-api-key-here

View file

@ -0,0 +1,43 @@
"""
Infrastructure layer - Connection and session management for external services
"""
from .database import (
Base,
engine,
AsyncSessionLocal,
get_db,
init_db,
close_db,
utc_now,
)
from .s3 import (
get_s3,
init_s3,
close_s3,
)
from .fishaudio import (
get_fish_audio,
init_fish_audio,
close_fish_audio,
)
__all__ = [
# Database
"Base",
"engine",
"AsyncSessionLocal",
"get_db",
"init_db",
"close_db",
"utc_now",
# S3
"get_s3",
"init_s3",
"close_s3",
# Fish Audio
"get_fish_audio",
"init_fish_audio",
"close_fish_audio",
]

View file

@ -0,0 +1,62 @@
"""
Database infrastructure - MySQL connection and session management
"""
from datetime import datetime, timezone
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.orm import declarative_base
from config import settings
def utc_now() -> datetime:
"""Return current UTC time as timezone-aware datetime"""
return datetime.now(timezone.utc)
# Create async engine with connection pool
engine = create_async_engine(
settings.DATABASE_URL,
echo=settings.DEBUG,
pool_pre_ping=True,
pool_size=10,
max_overflow=20,
)
# Create async session factory
AsyncSessionLocal = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False,
)
# Create declarative base for ORM models
Base = declarative_base()
async def get_db() -> AsyncSession:
"""
Dependency to get database session
Usage:
@router.get("/users")
async def get_users(db: AsyncSession = Depends(get_db)):
...
"""
async with AsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()
async def init_db():
"""Initialize database tables (called in lifespan)"""
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async def close_db():
"""Close database connections (called in lifespan)"""
await engine.dispose()

View file

@ -0,0 +1,57 @@
"""
Fish Audio infrastructure - Fish Audio API client management
"""
from fishaudio import AsyncFishAudio
from config import settings
# Create Fish Audio client at module level
fish_audio_client = None
def get_fish_audio() -> AsyncFishAudio:
"""
Dependency to get Fish Audio client
Usage:
@router.get("/voices")
async def get_voices(fish_client = Depends(get_fish_audio)):
await fish_client.voices.list(...)
Returns:
Fish Audio async client
"""
if fish_audio_client is None:
raise RuntimeError("Fish Audio client not initialized. Call init_fish_audio() first.")
return fish_audio_client
async def init_fish_audio():
"""
Initialize Fish Audio client and verify API key
(called in lifespan startup)
"""
global fish_audio_client
try:
fish_audio_client = AsyncFishAudio(api_key=settings.FISH_API_KEY)
# Verify API key by checking account credits
await fish_audio_client.account.get_credits()
print("Fish Audio API connection verified")
except Exception as e:
print(f"Warning: Fish Audio API verification failed: {e}")
print("Fish Audio operations may not work properly")
# Still initialize the client for potential retry
fish_audio_client = AsyncFishAudio(api_key=settings.FISH_API_KEY)
async def close_fish_audio():
"""
Close Fish Audio client connections
(called in lifespan shutdown)
Note: AsyncFishAudio handles cleanup automatically,
but this function is provided for symmetry with other layers
"""
global fish_audio_client
fish_audio_client = None
print("Fish Audio client closed")

View file

@ -0,0 +1,60 @@
"""
S3 infrastructure - AWS S3 connection and session management
"""
import aioboto3
from config import settings
s3_session = aioboto3.Session()
_s3_client = None
async def get_s3() :
"""
Dependency to get S3 client
Returns:
S3 client
"""
if _s3_client is None:
raise RuntimeError("S3 client not initialized. Call init_s3() first.")
return _s3_client
async def init_s3():
"""
Initialize S3 connection and verify bucket access
(called in lifespan startup)
"""
global _s3_client
try:
_s3_client = await s3_session.client(
's3',
aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
region_name=settings.AWS_REGION,
endpoint_url=settings.S3_ENDPOINT_URL
).__aenter__()
# Verify bucket exists and accessible
await _s3_client.head_bucket(Bucket=settings.S3_BUCKET_NAME)
print(f"S3 connection verified: bucket '{settings.S3_BUCKET_NAME}'")
except Exception as e:
print(f"Warning: S3 connection verification failed: {e}")
print("S3 operations may not work properly")
raise
async def close_s3():
"""
Close S3 connections (called in lifespan shutdown)
Note: aioboto3 handles cleanup automatically via context managers,
but this function is provided for symmetry with database layer
"""
global _s3_client
if _s3_client:
await _s3_client.__aexit__(None, None, None)
_s3_client = None
print("S3 connections closed")

View file

@ -0,0 +1,153 @@
-- Active: 1763538755357@@127.0.0.1@5432@live_agent
-- Live Agent API Database Initialization Script
-- PostgreSQL 16
-- ==================== Extensions ====================
-- Enable required PostgreSQL extensions
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-- ==================== Table: user ====================
-- User account table
CREATE TABLE IF NOT EXISTS "user" (
id SERIAL PRIMARY KEY,
user_id VARCHAR(50) UNIQUE NOT NULL,
username VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
updated_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
);
-- Indexes for user table
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_userid ON "user"(user_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_username ON "user"(username);
-- Comments for user table
COMMENT ON TABLE "user" IS 'User account information';
COMMENT ON COLUMN "user".user_id IS 'External unique identifier (e.g., ULID)';
COMMENT ON COLUMN "user".username IS 'Unique username for login';
COMMENT ON COLUMN "user".password IS 'Hashed password';
-- ==================== Table: agents ====================
-- AI Agent configuration table
CREATE TABLE IF NOT EXISTS agents (
id SERIAL PRIMARY KEY,
agent_id VARCHAR(50) UNIQUE NOT NULL,
owner_id VARCHAR(50) NOT NULL,
name VARCHAR(100) NOT NULL,
avatar_url TEXT,
description TEXT,
voice_id VARCHAR(50),
instruction TEXT NOT NULL,
voice_opening TEXT,
voice_closing TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
updated_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
CONSTRAINT fk_agents_owner FOREIGN KEY (owner_id)
REFERENCES "user"(user_id) ON DELETE CASCADE
);
-- Indexes for agents table
CREATE UNIQUE INDEX IF NOT EXISTS idx_agents_agent_id ON agents(agent_id);
CREATE INDEX IF NOT EXISTS idx_agents_owner_id ON agents(owner_id);
-- Comments for agents table
COMMENT ON TABLE agents IS 'AI agent configurations';
COMMENT ON COLUMN agents.agent_id IS 'External unique identifier (e.g., ULID)';
COMMENT ON COLUMN agents.owner_id IS 'User ID of the agent owner';
COMMENT ON COLUMN agents.instruction IS 'System prompt/instruction for the agent';
COMMENT ON COLUMN agents.voice_opening IS 'Opening message when conversation starts';
COMMENT ON COLUMN agents.voice_closing IS 'Closing message when conversation ends';
-- ==================== Table: voices ====================
-- Voice configuration table
CREATE TABLE IF NOT EXISTS voices (
id SERIAL PRIMARY KEY,
voice_id VARCHAR(50) NOT NULL,
owner_id VARCHAR(50) NOT NULL,
name VARCHAR(100) NOT NULL,
"desc" TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
updated_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
CONSTRAINT fk_voices_owner FOREIGN KEY (owner_id)
REFERENCES "user"(user_id) ON DELETE CASCADE,
CONSTRAINT uk_voices_owner_voice UNIQUE (voice_id, owner_id)
);
-- Indexes for voices table
CREATE INDEX IF NOT EXISTS idx_voices_voice_id ON voices(voice_id);
CREATE INDEX IF NOT EXISTS idx_voices_owner_id ON voices(owner_id);
CREATE INDEX IF NOT EXISTS idx_voices_created_at ON voices(created_at);
-- Comments for voices table
COMMENT ON TABLE voices IS 'Voice configurations for agents';
COMMENT ON COLUMN voices.voice_id IS 'Fish Audio voice ID';
COMMENT ON COLUMN voices.owner_id IS 'User ID of voice owner';
COMMENT ON COLUMN voices.name IS 'Voice display name';
COMMENT ON COLUMN voices."desc" IS 'Voice description';
-- ==================== Table: agent_templates ====================
-- Pre-configured agent templates
CREATE TABLE IF NOT EXISTS agent_templates (
id SERIAL PRIMARY KEY,
template_id VARCHAR(50) UNIQUE NOT NULL,
name VARCHAR(100) NOT NULL,
avatar_url TEXT,
description TEXT,
voice_id VARCHAR(50),
instruction TEXT,
voice_opening TEXT,
voice_closing TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
updated_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
);
-- Indexes for agent_templates table
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_templates_template_id ON agent_templates(template_id);
-- Comments for agent_templates table
COMMENT ON TABLE agent_templates IS 'Pre-configured agent templates for quick setup';
COMMENT ON COLUMN agent_templates.template_id IS 'External unique identifier (e.g., ULID)';
COMMENT ON COLUMN agent_templates.voice_id IS 'Default voice ID for this template';
-- ==================== Functions ====================
-- Function to automatically update updated_at timestamp
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = CURRENT_TIMESTAMP AT TIME ZONE 'UTC';
RETURN NEW;
END;
$$ language 'plpgsql';
-- Create triggers for updated_at on user table
CREATE TRIGGER update_user_updated_at
BEFORE UPDATE ON "user"
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
-- Create triggers for updated_at on agents table
CREATE TRIGGER update_agents_updated_at
BEFORE UPDATE ON agents
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
-- Create triggers for updated_at on voices table
CREATE TRIGGER update_voices_updated_at
BEFORE UPDATE ON voices
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
-- Create triggers for updated_at on agent_templates table
CREATE TRIGGER update_agent_templates_updated_at
BEFORE UPDATE ON agent_templates
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
-- ==================== Grant Permissions ====================
-- Grant necessary permissions to postgres user
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO postgres;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO postgres;
-- ==================== Initialization Complete ====================
-- Database schema initialization completed successfully

View file

@ -0,0 +1,95 @@
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from config import settings
from infra import init_db, close_db, init_s3, close_s3, init_fish_audio, close_fish_audio
from api.v1 import api_router
from utils.exceptions import APIException
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan events"""
# Startup
print("Starting up Live Agent API...")
await init_db()
print("Database initialized")
await init_s3()
print("S3 connection initialized")
await init_fish_audio()
print("Fish Audio client initialized")
yield
# Shutdown
print("Shutting down Live Agent API...")
await close_db()
print("Database connections closed")
await close_s3()
print("S3 connections closed")
await close_fish_audio()
print("Fish Audio client closed")
# Create FastAPI application
app = FastAPI(
title="Live Agent API",
description="Live Agent API - Python FastAPI implementation",
version="0.1.0",
lifespan=lifespan
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # In production, specify allowed origins
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Exception handlers
@app.exception_handler(APIException)
async def api_exception_handler(request: Request, exc: APIException):
"""Handle custom API exceptions"""
return JSONResponse(
status_code=200, # Always return 200, error code in response body
content={
"code": exc.code,
"message": exc.message,
"data": {}
}
)
# Health check endpoint
@app.get("/health", tags=["Health"])
async def health_check():
"""Health check endpoint"""
return {
"code": 200,
"message": "success",
"data": {
"status": "healthy",
"service": "live-agent-api",
"version": "0.1.0"
}
}
# Include API router
app.include_router(api_router, prefix="/api/live_agent/v1")
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"app.main:app",
host=settings.HOST,
port=settings.PORT,
reload=settings.DEBUG
)

View file

@ -0,0 +1,31 @@
[project]
name = "live-agent-api"
version = "0.1.0"
description = "Live Agent Manager API - Python FastAPI implementation"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.115.0",
"uvicorn[standard]>=0.32.0",
"pydantic>=2.9.0",
"pydantic-settings>=2.6.0",
"sqlalchemy>=2.0.35",
"asyncpg>=0.30.0",
"bcrypt>=4.2.0",
"python-multipart>=0.0.12",
"boto3>=1.35.0",
"python-dotenv>=1.0.0",
"httpx>=0.27.0",
"python-ulid>=3.1.0",
"aioboto3>=15.5.0",
"pyjwt>=2.9.0",
"fish-audio-sdk>=1.1.0",
]
[project.optional-dependencies]
dev = [
"pytest>=8.3.0",
"pytest-asyncio>=0.24.0",
"pytest-cov>=5.0.0",
"black>=24.8.0",
"ruff>=0.7.0",
]

View file

@ -0,0 +1,31 @@
"""
Repositories package - ORM models and data access layer
"""
# Import ORM Models
from .user import UserModel
from .agent import AgentModel
from .agent_template import AgentTemplateModel
from .voice import VoiceModel
# Import Repository classes
from .user import User
from .agent import Agent
from .agent_template import AgentTemplate
from .voice import Voice
from .file import FileRepository
__all__ = [
# ORM Models
"UserModel",
"AgentModel",
"AgentTemplateModel",
"VoiceModel",
# Repository classes
"User",
"Agent",
"AgentTemplate",
"Voice",
"FileRepository",
]

View file

@ -0,0 +1,184 @@
from datetime import datetime
from typing import Optional, List, Tuple
from sqlalchemy import String, Text, TIMESTAMP, ForeignKey, Index, select, delete
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.ext.asyncio import AsyncSession
from infra.database import Base, utc_now
# ==================== ORM Model ====================
class AgentModel(Base):
__tablename__ = "agents"
# Primary key
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
# Agent unique identifier (external)
agent_id: Mapped[str] = mapped_column(String(50), unique=True, nullable=False)
# Foreign key to user table (user_id)
owner_id: Mapped[str] = mapped_column(
String(50),
ForeignKey("user.user_id", ondelete="CASCADE"),
nullable=False
)
# Agent info
name: Mapped[str] = mapped_column(String(100), nullable=False)
avatar_url: Mapped[str | None] = mapped_column(Text, nullable=True)
description: Mapped[str | None] = mapped_column(Text, nullable=True)
# Agent configuration
voice_id: Mapped[str | None] = mapped_column(String(50), nullable=True)
instruction: Mapped[str] = mapped_column(Text, nullable=False)
voice_opening: Mapped[str | None] = mapped_column(Text, nullable=True)
voice_closing: Mapped[str | None] = mapped_column(Text, nullable=True)
# Timestamps
created_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
onupdate=utc_now,
nullable=False
)
__table_args__ = (
Index('idx_agents_agent_id', 'agent_id', unique=True),
Index('idx_agents_owner_id', 'owner_id'),
)
def __repr__(self):
return f"<AgentModel(id={self.id}, agent_id={self.agent_id}>"
# ==================== Repository (CRUD Operations) ====================
class Agent:
"""
Agent Repository - Handles all database operations
"""
@staticmethod
async def get_by_id(db: AsyncSession, agent_id: str) -> Optional[AgentModel]:
"""Get agent by agent_id"""
result = await db.execute(select(AgentModel).where(AgentModel.agent_id == agent_id))
return result.scalar_one_or_none()
@staticmethod
async def get_agents_by_owner(
db: AsyncSession,
owner_id: str,
cursor: Optional[str] = None,
limit: int = 20
) -> Tuple[List[AgentModel], Optional[str], bool]:
"""
Get agents owned by a user with cursor-based pagination
Args:
db: Database session
owner_id: User ID
cursor: ISO datetime string of last item's created_at
limit: Number of items to return
Returns:
(agents, next_cursor, has_more)
"""
query = select(AgentModel).where(AgentModel.owner_id == owner_id)
# Apply cursor filter if provided
if cursor:
try:
cursor_time = datetime.fromisoformat(cursor)
# Get records created before cursor time
query = query.where(AgentModel.created_at < cursor_time)
except (ValueError, TypeError):
# Invalid cursor, ignore and start from beginning
pass
# Order by created_at DESC, agent_id DESC for stable sorting
# Fetch limit + 1 to check if there are more records
query = query.order_by(
AgentModel.created_at.desc(),
AgentModel.agent_id.desc()
).limit(limit + 1)
result = await db.execute(query)
agents: List[AgentModel] = result.scalars().all()
# Check if there are more records
has_more = len(agents) > limit
if has_more:
agents = agents[:limit]
# Generate next cursor from last item
next_cursor = None
if has_more and agents:
next_cursor = agents[-1].created_at.isoformat()
return agents, next_cursor, has_more
@staticmethod
async def create(
db: AsyncSession,
agent_id: str,
owner_id: str,
name: str,
instruction: str,
avatar_url: Optional[str] = None,
description: Optional[str] = None,
voice_id: Optional[str] = None,
voice_opening: Optional[str] = None,
voice_closing: Optional[str] = None
) -> AgentModel:
"""Create a new agent"""
agent = AgentModel(
agent_id=agent_id,
owner_id=owner_id,
name=name,
avatar_url=avatar_url,
description=description,
voice_id=voice_id,
instruction=instruction,
voice_opening=voice_opening,
voice_closing=voice_closing
)
db.add(agent)
await db.commit()
await db.refresh(agent)
return agent
@staticmethod
async def update(
db: AsyncSession,
agent_id: str,
**kwargs
) -> Optional[AgentModel]:
"""Update agent"""
agent = await Agent.get_by_id(db, agent_id)
if not agent:
return None
for key, value in kwargs.items():
if hasattr(agent, key):
setattr(agent, key, value)
await db.commit()
await db.refresh(agent)
return agent
@staticmethod
async def delete(db: AsyncSession, agent_id: str) -> bool:
"""Delete agent by agent_id"""
result = await db.execute(
delete(AgentModel).where(AgentModel.agent_id == agent_id)
)
await db.commit()
return result.rowcount > 0

View file

@ -0,0 +1,73 @@
from datetime import datetime
from typing import Optional, List
from sqlalchemy import String, Text, TIMESTAMP, Index, select
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.ext.asyncio import AsyncSession
from infra.database import Base, utc_now
# ==================== ORM Model ====================
class AgentTemplateModel(Base):
__tablename__ = "agent_templates"
# Primary key
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
# Template unique identifier (external)
template_id: Mapped[str] = mapped_column(String(50), unique=True, nullable=False)
# Template info
name: Mapped[str] = mapped_column(String(100), nullable=False)
avatar_url: Mapped[str | None] = mapped_column(Text, nullable=True)
description: Mapped[str | None] = mapped_column(Text, nullable=True)
# Template configuration
voice_id: Mapped[str | None] = mapped_column(String(50), nullable=True)
instruction: Mapped[str | None] = mapped_column(Text, nullable=True)
voice_opening: Mapped[str | None] = mapped_column(Text, nullable=True)
voice_closing: Mapped[str | None] = mapped_column(Text, nullable=True)
# Timestamps
created_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
onupdate=utc_now,
nullable=False
)
__table_args__ = (
Index('idx_agent_templates_template_id', 'template_id', unique=True),
)
def __repr__(self):
return f"<AgentTemplateModel(id={self.id}, template_id={self.template_id}, name={self.name})>"
# ==================== Repository (CRUD Operations) ====================
class AgentTemplate:
"""
AgentTemplate Repository - Handles all database operations
"""
@staticmethod
async def get_all(db: AsyncSession, limit: int = 10) -> List[AgentTemplateModel]:
"""
Get all templates
Args:
db: AsyncSession
limit: int
Returns:
List[AgentTemplateModel]
"""
stmt = select(AgentTemplateModel).limit(limit)
result = await db.execute(stmt)
return result.scalars().all()

View file

@ -0,0 +1,143 @@
"""
File repository - S3 storage operations
(Similar to User/Agent repositories but for file storage instead of database)
"""
from typing import Optional
from fastapi import UploadFile
from config import settings
from utils.ulid import ULID
class FileRepository:
"""
File storage operations repository
Handles S3 operations similar to how other repositories handle database operations.
All methods are static and accept S3 client as first parameter (dependency injection).
"""
@staticmethod
async def upload(
s3, # S3 client from Depends(get_s3)
file: UploadFile,
folder: str = "uploads",
custom_filename: Optional[str] = None
) -> str:
"""
Upload file to S3 and return public URL
Args:
s3: S3 client (injected via Depends)
file: File to upload
folder: S3 folder path
custom_filename: Optional custom filename (e.g., agent_id, voice_id)
If provided, uses this instead of generating ULID
Returns:
Public URL of uploaded file
Example:
# With custom filename (entity_id based)
url = await FileRepository.upload(s3, file, "avatars", custom_filename="agent_123")
# Result: avatars/agent_123.jpg
# With auto-generated filename
url = await FileRepository.upload(s3, file, "avatars")
# Result: avatars/01JD8X0000ABC123DEF456GH.jpg
"""
# Get file extension
file_ext = file.filename.split('.')[-1] if '.' in file.filename else ''
# Generate filename
if custom_filename:
# Use custom filename (e.g., agent_id or voice_id)
filename = f"{custom_filename}.{file_ext}" if file_ext else custom_filename
else:
# Generate unique filename using ULID
filename = f"{ULID()}.{file_ext}" if file_ext else str(ULID())
s3_key = f"{folder}/{filename}"
# Read file content
content = await file.read()
await file.seek(0) # Reset file pointer for potential reuse
# Upload to S3
await s3.put_object(
Bucket=settings.S3_BUCKET_NAME,
Key=s3_key,
Body=content,
ContentType=file.content_type or 'application/octet-stream',
)
# Generate public URL
url = f"{settings.S3_PUBLIC_BASE_URL}/{settings.S3_BUCKET_NAME}/{s3_key}"
return url
@staticmethod
async def delete(s3, url: str) -> bool:
"""
Delete file from S3 by URL
Args:
s3: S3 client
url: Full S3 URL
Returns:
True if successful, False otherwise
"""
try:
# Extract S3 key from URL
key = url.split(f"{settings.S3_PUBLIC_BASE_URL}/{settings.S3_BUCKET_NAME}/")[-1]
await s3.delete_object(
Bucket=settings.S3_BUCKET_NAME,
Key=key
)
return True
except Exception as e:
print(f"Error deleting file from S3: {e}")
return False
# ========== Business-specific convenience methods ==========
@staticmethod
async def upload_avatar(s3, file: UploadFile, entity_id: str) -> str:
"""
Upload agent/user avatar to S3
Args:
s3: S3 client
file: Avatar file to upload
entity_id: Entity ID (agent_id or user_id) used as filename
Returns:
Public URL of uploaded avatar
Example:
url = await FileRepository.upload_avatar(s3, file, "agent_01JD8X0000ABC")
# Result: avatars/agent_01JD8X0000ABC.jpg
"""
return await FileRepository.upload(s3, file, folder="agent_avatars", custom_filename=entity_id)
@staticmethod
async def upload_voice(s3, file: UploadFile, entity_id: str) -> str:
"""
Upload voice audio file to S3
Args:
s3: S3 client
file: Audio file to upload
entity_id: Entity ID (voice_id) used as filename
Returns:
Public URL of uploaded audio
Example:
url = await FileRepository.upload_audio(s3, file, "voice_01JD8X0000XYZ")
# Result: audio/voice_01JD8X0000XYZ.mp3
"""
return await FileRepository.upload(s3, file, folder="voice_audios", custom_filename=entity_id)

View file

@ -0,0 +1,106 @@
from datetime import datetime
from typing import Optional
from sqlalchemy import String, Integer, TIMESTAMP, Index, select
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.ext.asyncio import AsyncSession
from infra.database import Base, utc_now
# ==================== ORM Model ====================
class UserModel(Base):
__tablename__ = "user"
# Primary key
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
# User unique identifier (external)
user_id: Mapped[str] = mapped_column(String(50), unique=True, nullable=False)
# User credentials and info
username: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
password: Mapped[str] = mapped_column(String(255), nullable=False)
# Timestamps
created_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
onupdate=utc_now,
nullable=False
)
__table_args__ = (
Index('idx_user_userid', 'user_id', unique=True),
Index('idx_user_username', 'username', unique=True),
)
def __repr__(self):
return f"<UserModel(id={self.id}, user_id={self.user_id})>"
# ==================== Repository (CRUD Operations) ====================
class User:
"""
User Repository - Handles all database operations
"""
@staticmethod
async def get_by_user_id(db: AsyncSession, user_id: str) -> Optional[UserModel]:
"""Get user by user_id"""
result = await db.execute(select(UserModel).where(UserModel.user_id == user_id))
return result.scalar_one_or_none()
@staticmethod
async def get_by_username(db: AsyncSession, username: str) -> Optional[UserModel]:
"""Get user by username"""
result = await db.execute(select(UserModel).where(UserModel.username == username))
return result.scalar_one_or_none()
@staticmethod
async def create(
db: AsyncSession,
user_id: str,
username: str,
hashed_password: str
) -> UserModel:
"""Create a new user"""
user = UserModel(
user_id=user_id,
username=username,
password=hashed_password,
)
db.add(user)
await db.commit()
await db.refresh(user)
return user
@staticmethod
async def update_password(
db: AsyncSession,
user_id: str,
new_hashed_password: str
) -> Optional[UserModel]:
"""Update user password"""
user = await User.get_by_user_id(db, user_id)
if not user:
return None
user.password = new_hashed_password
await db.commit()
await db.refresh(user)
return user
@staticmethod
async def is_username_taken(db: AsyncSession, username: str) -> bool:
"""Check if username is already taken"""
user = await User.get_by_username(db, username)
return user is not None

View file

@ -0,0 +1,224 @@
from datetime import datetime
from typing import Optional, List, Tuple
from sqlalchemy import String, Text, TIMESTAMP, ForeignKey, Index, select, func, update
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.ext.asyncio import AsyncSession
from infra.database import Base, utc_now
# ==================== ORM Model ====================
class VoiceModel(Base):
__tablename__ = "voices"
# Primary key
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
# Fish Audio voice ID (not unique, can be shared by multiple users)
voice_id: Mapped[str] = mapped_column(String(50), nullable=False)
# Foreign key to user table (user_id)
owner_id: Mapped[str] = mapped_column(
String(50),
ForeignKey("user.user_id", ondelete="CASCADE"),
nullable=False
)
# Voice info
name: Mapped[str] = mapped_column(String(100), nullable=False)
desc: Mapped[str] = mapped_column(Text, nullable=False)
# Timestamps
created_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
default=utc_now,
onupdate=utc_now,
nullable=False
)
__table_args__ = (
Index('idx_voices_voice_id', 'voice_id'),
Index('idx_voices_owner_id', 'owner_id'),
Index('idx_voices_created_at', 'created_at'),
# Composite unique constraint: same voice can be added by different users
Index('uk_voices_owner_voice', 'voice_id', 'owner_id', unique=True),
)
def __repr__(self):
return f"<VoiceModel(id={self.id}, voice_id={self.voice_id}, name={self.name})>"
# ==================== Repository (CRUD Operations) ====================
class Voice:
"""
Voice Repository - Handles all database operations
"""
@staticmethod
async def get_by_id(db: AsyncSession, voice_id: str) -> Optional[VoiceModel]:
"""Get voice by voice_id"""
result = await db.execute(select(VoiceModel).where(VoiceModel.voice_id == voice_id))
return result.scalar_one_or_none()
@staticmethod
async def get_list(
db: AsyncSession,
owner_id: Optional[str] = None,
cursor: Optional[str] = None,
limit: int = 100
) -> Tuple[List[VoiceModel], Optional[str], bool]:
"""
Get voices with cursor-based pagination
Args:
db: Database session
owner_id: Filter by owner ID
cursor: ISO datetime string of last item's created_at
limit: Number of items to return
Returns:
(voices, next_cursor, has_more)
"""
query = select(VoiceModel)
if owner_id:
# All voices accessible by user
query = query.where(
VoiceModel.owner_id == owner_id
)
# Apply cursor filter if provided
if cursor:
try:
cursor_time = datetime.fromisoformat(cursor)
# Get records created before cursor time
query = query.where(VoiceModel.created_at < cursor_time)
except (ValueError, TypeError):
# Invalid cursor, ignore and start from beginning
pass
# Order by created_at DESC, voice_id DESC for stable sorting
# Fetch limit + 1 to check if there are more records
query = query.order_by(
VoiceModel.created_at.desc(),
VoiceModel.voice_id.desc()
).limit(limit + 1)
result = await db.execute(query)
voices = list(result.scalars().all())
# Check if there are more records
has_more = len(voices) > limit
if has_more:
voices = voices[:limit]
# Generate next cursor from last item
next_cursor = None
if has_more and voices:
next_cursor = voices[-1].created_at.isoformat()
return voices, next_cursor, has_more
async def count(
db: AsyncSession,
owner_id: Optional[str] = None
) -> int:
"""Count voices with owner_id"""
stmt = (
select(func.count())
.select_from(VoiceModel)
.where(VoiceModel.owner_id == owner_id)
)
result = await db.execute(stmt)
return result.scalar_one()
@staticmethod
async def get_by_voice_and_owner(
db: AsyncSession,
voice_id: str,
owner_id: str
) -> Optional[VoiceModel]:
"""Get voice by voice_id and owner_id (composite key)"""
stmt = (
select(VoiceModel)
.where(VoiceModel.voice_id == voice_id)
.where(VoiceModel.owner_id == owner_id)
)
result = await db.execute(stmt)
return result.scalar_one_or_none()
@staticmethod
async def create(
db: AsyncSession,
voice_id: str,
owner_id: str,
name: str,
desc: str
) -> VoiceModel:
"""Create a new voice"""
voice = VoiceModel(
voice_id=voice_id,
owner_id=owner_id,
name=name,
desc=desc
)
db.add(voice)
await db.commit()
await db.refresh(voice)
return voice
@staticmethod
async def update(
db: AsyncSession,
voice_id: str,
owner_id: str,
name: str,
desc: str
) -> VoiceModel:
"""Update a voice"""
stmt = (
update(VoiceModel)
.where(VoiceModel.voice_id == voice_id)
.where(VoiceModel.owner_id == owner_id)
.values(name=name, desc=desc)
.returning(VoiceModel)
)
result =await db.execute(stmt)
await db.commit()
return result.scalar_one()
@staticmethod
async def delete(
db: AsyncSession,
voice_id: str,
owner_id: str
) -> bool:
"""
Delete a voice (only if owned by user)
Returns:
True if deleted, False if not found or not owned
"""
result = await db.execute(
select(VoiceModel).where(
VoiceModel.voice_id == voice_id,
VoiceModel.owner_id == owner_id
)
)
voice = result.scalar_one_or_none()
if not voice:
return False
await db.delete(voice)
await db.commit()
return True

View file

View file

@ -0,0 +1,62 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
from fastapi import UploadFile
# ==================== Template Schemas ====================
class AgentTemplateResponse(BaseModel):
"""Agent template response"""
template_id: str
name: str
avatar_url: Optional[str] = None
description: Optional[str] = None
voice_id: Optional[str] = None
instruction: Optional[str] = None
voice_opening: Optional[str] = None
voice_closing: Optional[str] = None
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
# ==================== Agent Response Schemas ====================
class AgentResponse(BaseModel):
"""Agent response"""
agent_id: str
name: str
avatar_url: Optional[str] = None
description: Optional[str] = None
voice_id: Optional[str] = None
instruction: str
voice_opening: Optional[str] = None
voice_closing: Optional[str] = None
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
class AgentListResponse(BaseModel):
"""Agent list response with cursor-based pagination"""
agents: list[AgentResponse]
next_cursor: Optional[str] = None
has_more: bool = False
class AgentConfigResponse(BaseModel):
"""Agent configuration for xiaozhi-server"""
agent_id: str
name: str
voice_id: Optional[str] = None
instruction: str
voice_opening: Optional[str] = None
voice_closing: Optional[str] = None
class Config:
from_attributes = True

View file

@ -0,0 +1,51 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
# ==================== Request Schemas ====================
class UserRegisterRequest(BaseModel):
"""User registration request"""
username: str = Field(..., min_length=3, max_length=50)
password: str = Field(..., min_length=6, max_length=128)
class UserLoginRequest(BaseModel):
"""User login request"""
username: str
password: str
class PasswordUpdateRequest(BaseModel):
"""Password update request"""
old_password: str
new_password: str = Field(..., min_length=6, max_length=128)
# ==================== Response Schemas ====================
class UserInfo(BaseModel):
"""User information response"""
user_id: str
username: str
created_at: datetime
class Config:
from_attributes = True
class LoginResponse(BaseModel):
"""Login response"""
token: str
expire: int # seconds
user: UserInfo
class TokenInfo(BaseModel):
"""Token information"""
user_id: str
username: str
token: str
expire_date: datetime

View file

@ -0,0 +1,80 @@
from datetime import datetime
from typing import Optional, List
from pydantic import BaseModel, Field
from fishaudio.types import Sample
# ==================== Request Schemas ====================
class VoiceCloneRequest(BaseModel):
"""Voice clone request"""
name: str = Field(..., min_length=1, max_length=100)
reference_text: Optional[str] = None
tags: Optional[List[str]] = None
class VoiceUpdateRequest(BaseModel):
"""Voice update request"""
name: str = Field(None, min_length=1, max_length=100, description="Voice name")
desc: str = Field(None, max_length=500, description="Voice description")
class VoiceAddRequest(BaseModel):
"""Voice add request"""
name: str = Field(..., min_length=1, max_length=100, description="Voice name")
desc: str = Field(..., max_length=500, description="Voice description")
# ==================== Response Schemas ====================
class AudioSample(BaseModel):
"""Audio sample"""
title: str
text: str
audio: str
class LiveAgentVoice(BaseModel):
"""Voice Entity for Live Agent"""
voice_id: str
name: str
desc: Optional[str] = None
samples: Optional[List[AudioSample]] = None
created_at: datetime
class FishAudioVoiceResponse(BaseModel):
"""Fish Audio voice response (for discover tab)"""
voice_id: str
name: str
tags: Optional[List[str]] = None
preview_url: Optional[str] = None
author_id: Optional[str] = None
author_name: Optional[str] = None
like_count: Optional[int] = None
task_count: Optional[int] = None
class DiscoverVoiceResponse(BaseModel):
"""Voice list response"""
voices: List[LiveAgentVoice]
has_more: bool
class MyVoiceResponse(BaseModel):
"""My voice response with cursor-based pagination"""
voices: List[LiveAgentVoice]
next_cursor: Optional[str] = None
has_more: bool = False
class VoiceCloneStatusResponse(BaseModel):
"""Voice clone status response"""
voice_id: str
status: str # processing | completed | failed
error_message: Optional[str] = None
voice: Optional[LiveAgentVoice] = None
class Config:
from_attributes = True

View file

View file

@ -0,0 +1,196 @@
from typing import Optional, List
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import UploadFile
from repositories import AgentModel, Agent, AgentTemplate, FileRepository
from utils.exceptions import NotFoundException, BadRequestException
from utils.ulid import generate_agent_id
from schemas.agent import (
AgentResponse,
AgentListResponse,
AgentTemplateResponse,
AgentConfigResponse
)
class AgentService:
"""Agent service layer"""
async def get_templates(self, db: AsyncSession) -> List[AgentTemplateResponse]:
"""Get all agent templates"""
templates = await AgentTemplate.get_all(db)
return [AgentTemplateResponse.model_validate(t) for t in templates]
async def get_agent_list(
self,
db: AsyncSession,
owner_id: str,
cursor: Optional[str] = None,
page_size: int = 10
) -> AgentListResponse:
"""
Get user's agent list with cursor-based pagination
Args:
db: Database session
owner_id: User ID
cursor: Pagination cursor (ISO datetime string)
page_size: Number of items per page
Returns:
AgentListResponse with agents, next_cursor, and has_more
"""
agents, next_cursor, has_more = await Agent.get_agents_by_owner(
db,
owner_id=owner_id,
cursor=cursor,
limit=page_size
)
agent_responses = [AgentResponse.model_validate(a) for a in agents]
return AgentListResponse(
agents=agent_responses,
next_cursor=next_cursor,
has_more=has_more
)
async def get_agent_detail(
self,
db: AsyncSession,
agent_id: str
) -> AgentResponse:
"""Get agent detail"""
agent = await Agent.get_by_id(db, agent_id)
if not agent:
raise NotFoundException("Agent not found")
return AgentResponse.model_validate(agent)
async def create_agent(
self,
db: AsyncSession,
s3,
owner_id: str,
name: str,
instruction: str,
description: Optional[str] = None,
voice_id: Optional[str] = None,
voice_opening: Optional[str] = None,
voice_closing: Optional[str] = None,
avatar: Optional[UploadFile] = None
) -> AgentResponse:
"""Create a new agent"""
# Generate agent_id first
agent_id = generate_agent_id()
# Upload avatar if provided
avatar_url = None
if avatar:
avatar_url = await FileRepository.upload_avatar(s3, avatar, agent_id)
# Create agent
agent = await Agent.create(
db=db,
agent_id=agent_id,
owner_id=owner_id,
name=name,
instruction=instruction,
avatar_url=avatar_url,
description=description,
voice_id=voice_id,
voice_opening=voice_opening,
voice_closing=voice_closing
)
return AgentResponse.model_validate(agent)
async def update_agent(
self,
db: AsyncSession,
s3, # S3 client from dependency injection
agent_id: str,
owner_id: str,
name: Optional[str] = None,
description: Optional[str] = None,
voice_id: Optional[str] = None,
instruction: Optional[str] = None,
voice_opening: Optional[str] = None,
voice_closing: Optional[str] = None,
avatar: Optional[UploadFile] = None
) -> AgentResponse:
"""Update agent"""
# Get existing agent
agent = await Agent.get_by_id(db, agent_id)
if not agent:
raise NotFoundException("Agent not found")
# Check ownership
if agent.owner_id != owner_id:
raise BadRequestException("You don't have permission to update this agent")
# Prepare update data
update_data = {}
if name is not None:
update_data['name'] = name
if description is not None:
update_data['description'] = description
if voice_id is not None:
update_data['voice_id'] = voice_id
if instruction is not None:
update_data['instruction'] = instruction
if voice_opening is not None:
update_data['voice_opening'] = voice_opening
if voice_closing is not None:
update_data['voice_closing'] = voice_closing
# Upload new avatar if provided (using agent_id as filename)
# Note: Since we use agent_id as filename, uploading will automatically
# overwrite the old avatar file, so no need to delete it first
if avatar:
avatar_url = await FileRepository.upload_avatar(s3, avatar, agent_id)
update_data['avatar_url'] = avatar_url
# Update agent
updated_agent = await Agent.update(db, agent_id, **update_data)
if not updated_agent:
raise NotFoundException("Agent not found")
return AgentResponse.model_validate(updated_agent)
async def delete_agent(
self,
db: AsyncSession,
s3, # S3 client from dependency injection
agent_id: str,
owner_id: str
) -> None:
"""Delete agent"""
# Get agent
agent = await Agent.get_by_id(db, agent_id)
if not agent:
raise NotFoundException("Agent not found")
# Check ownership
if agent.owner_id != owner_id:
raise BadRequestException("You don't have permission to delete this agent")
# Delete avatar from S3 if exists
if agent.avatar_url:
await FileRepository.delete(s3, agent.avatar_url)
# Delete agent
await Agent.delete(db, agent_id)
async def get_agent_config(
self,
db: AsyncSession,
agent_id: str
) -> AgentConfigResponse:
"""Get agent configuration for xiaozhi-server"""
agent = await Agent.get_by_id(db, agent_id)
if not agent:
raise NotFoundException("Agent not found")
return AgentConfigResponse.model_validate(agent)
agent_service = AgentService()

View file

@ -0,0 +1,115 @@
from sqlalchemy.ext.asyncio import AsyncSession
from repositories import UserModel, User
from utils.security import hash_password, verify_password, generate_jwt_token
from utils.exceptions import BadRequestException, UnauthorizedException, ConflictException
from utils.ulid import generate_user_id
from schemas.user import UserInfo, LoginResponse
from config import settings
class UserService:
"""User service layer"""
async def register(
self,
db: AsyncSession,
username: str,
password: str
) -> None:
"""Register a new user"""
# Check if username already exists
if await User.is_username_taken(db, username):
raise ConflictException("Username already taken")
# Hash password
hashed_password = hash_password(password)
# Generate user_id
user_id = generate_user_id()
# Create user
await User.create(
db=db,
user_id=user_id,
username=username,
hashed_password=hashed_password
)
async def login(
self,
db: AsyncSession,
username: str,
password: str
) -> LoginResponse:
"""User login and return JWT token"""
# Get user by username
user = await User.get_by_username(db, username)
if not user:
raise UnauthorizedException("Invalid username or password, please check and try again")
# Verify password
if not verify_password(password, user.password):
raise UnauthorizedException("Invalid username or password, please check and try again")
# Generate JWT token
token = generate_jwt_token(user.user_id, user.username)
# Prepare response
user_info = UserInfo(
user_id=user.user_id,
username=user.username,
created_at=user.created_at
)
return LoginResponse(
token=token,
expire=settings.TOKEN_EXPIRE_DAYS * 24 * 60 * 60, # 7 days in seconds
user=user_info
)
async def logout(self, db: AsyncSession, token: str) -> None:
"""
User logout
Note: With JWT, tokens cannot be invalidated on the server side.
The token will remain valid until it expires.
For production, consider implementing a token blacklist with Redis.
"""
# JWT tokens are stateless and cannot be revoked
# This is a placeholder for future blacklist implementation
pass
async def update_password(
self,
db: AsyncSession,
user_id: str,
old_password: str,
new_password: str
) -> None:
"""Update user password"""
# Get user
user = await User.get_by_user_id(db, user_id)
if not user:
raise UnauthorizedException("User not found")
# Verify old password
if not verify_password(old_password, user.password):
raise BadRequestException("Invalid old password")
# Hash new password
new_hashed_password = hash_password(new_password)
# Update password
await User.update_password(db, user_id, new_hashed_password)
async def get_user_info(self, db: AsyncSession, user_id: str) -> UserModel:
# Get user from database
user = await User.get_by_user_id(db, user_id)
if not user:
raise UnauthorizedException("User not found")
return user
user_service = UserService()

View file

@ -0,0 +1,236 @@
from typing import Optional, List, Tuple
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import UploadFile
from fishaudio import AsyncFishAudio
from fishaudio.types import PaginatedResponse, Voice as FishVoice, Sample as FishSample
from repositories import VoiceModel, Voice
from utils.ulid import generate_voice_id
class VoiceService:
"""Voice service layer"""
async def get_discover_voices(
self,
fish_client: AsyncFishAudio,
title: Optional[str] = None,
page: int = 1,
page_size: int = 20,
language: Optional[str] = None
) -> Tuple[List[FishVoice], bool]:
"""
Get voices from Fish Audio platform (discover tab)
Sorted by task_count (popularity)
Returns:
Tuple of (voice_list, total_count)
"""
# Call Fish Audio API to list voices
response: PaginatedResponse[FishVoice] = await fish_client.voices.list(
page_size=page_size,
page_number=page,
title=title,
sort_by="task_count", # Sort by popularity
language=language
)
has_more = response.total > page * page_size
return response.items, has_more
async def get_default_voices(
self,
db: AsyncSession,
page: int = 1,
page_size: int = 20
) -> List[VoiceModel]:
"""
Get platform default voices (default tab)
TODO: Implement after PM discussion
Returns:
List of VoiceModel objects
"""
skip = (page - 1) * page_size
voices = await Voice.get_list(
db,
owner_id=None,
category="default",
skip=skip,
limit=page_size
)
return voices
async def get_my_voices(
self,
db: AsyncSession,
owner_id: str,
cursor: Optional[str] = None,
page_size: int = 20
) -> Tuple[List[VoiceModel], Optional[str], bool]:
"""
Get user's custom voices with cursor-based pagination
Args:
db: Database session
owner_id: User ID
cursor: Pagination cursor (ISO datetime string)
page_size: Number of items per page
Returns:
Tuple of (voices, next_cursor, has_more)
"""
voices, next_cursor, has_more = await Voice.get_list(
db,
owner_id=owner_id,
cursor=cursor,
limit=page_size
)
return voices, next_cursor, has_more
async def clone_voice(
self,
fish_client: AsyncFishAudio,
audio_file: UploadFile,
text: Optional[str] = None
) -> Tuple[str, List[FishSample]]:
"""
Clone a voice using Fish Audio API
Args:
db: Database session
fish_client: Fish Audio client
name: Voice name
owner_id: User ID
name: Voice name
audio_file: Audio file to clone
text: Optional transcription text
Returns:
Created VoiceModel
"""
# Read audio file content
audio_content = await audio_file.read()
voice_id = generate_voice_id()
# Call Fish Audio API to clone voice
fish_voice: FishVoice = await fish_client.voices.create(
title=f"live_agent_{voice_id}",
voices=[audio_content],
texts=[text] if text else None,
train_mode="fast",
visibility="private",
enhance_audio_quality=True
)
return fish_voice.id, fish_voice.samples
async def add_voice(
self,
db: AsyncSession,
fish_client: AsyncFishAudio,
owner_id: str,
voice_id: str,
name: str,
desc: str,
) -> VoiceModel:
"""
Add a Fish Audio voice to user's my voices
Args:
db: Database session
fish_client: Fish Audio client
owner_id: User ID
voice_id: Audio voice ID
name: Voice name
desc: Voice description
Returns:
Created VoiceModel
"""
# Verify the Fish voice exists and get its info
fish_voice = await fish_client.voices.get(voice_id)
if not fish_voice:
from utils.exceptions import NotFoundException
raise NotFoundException(f"Fish voice {voice_id} not found")
# Create voice record in database using Fish voice ID directly
voice = await Voice.create(
db=db,
voice_id=voice_id, # Use Fish Audio voice ID directly
owner_id=owner_id,
name=name,
desc=desc
)
return voice
async def remove_voice(
self,
db: AsyncSession,
voice_id: str,
owner_id: str
) -> bool:
"""
Remove a voice from user's my voices
Args:
db: Database session
voice_id: Internal voice ID
owner_id: User ID
Returns:
True if deleted, False if not found
"""
deleted = await Voice.delete(db=db, voice_id=voice_id, owner_id=owner_id)
if not deleted:
from utils.exceptions import NotFoundException
raise NotFoundException(f"Voice {voice_id} not found or not owned by user")
return True
async def update_voice(
self,
db: AsyncSession,
voice_id: str,
owner_id: str,
name: str,
desc: str
) -> VoiceModel:
"""
Update voice name and/or description
Args:
db: Database session
voice_id: Voice ID
owner_id: User ID
name: New voice name
desc: New voice description
Returns:
Updated VoiceModel
"""
# Get existing voice
voice = await Voice.get_by_voice_and_owner(
db=db,
voice_id=voice_id,
owner_id=owner_id
)
if not voice:
from utils.exceptions import NotFoundException
raise NotFoundException(f"Voice {voice_id} not found or not owned by user")
# Update only provided fields
new_voice = await Voice.update(
db=db,
voice_id=voice_id,
owner_id=owner_id,
name=name,
desc=desc
)
return new_voice
voice_service = VoiceService()

View file

View file

@ -0,0 +1,48 @@
"""Utility modules for the application"""
from .security import (
hash_password,
verify_password,
generate_jwt_token,
verify_jwt_token,
)
from .response import success_response, error_response, APIResponse
from .exceptions import (
APIException,
NotFoundException,
ConflictException,
UnauthorizedException,
BadRequestException,
ForbiddenException,
)
from .ulid import (
generate_user_id,
generate_agent_id,
generate_template_id,
generate_voice_id,
)
__all__ = [
# Security
"hash_password",
"verify_password",
"generate_jwt_token",
"verify_jwt_token",
# Response
"success_response",
"error_response",
"APIResponse",
# Exceptions
"APIException",
"NotFoundException",
"ConflictException",
"UnauthorizedException",
"BadRequestException",
"ForbiddenException",
# ULID Generators
"generate_user_id",
"generate_agent_id",
"generate_template_id",
"generate_voice_id",
]

View file

@ -0,0 +1,37 @@
class APIException(Exception):
"""Base API exception"""
def __init__(self, code: int, message: str):
self.code = code
self.message = message
super().__init__(self.message)
class UnauthorizedException(APIException):
"""Unauthorized exception (401)"""
def __init__(self, message: str = "Unauthorized"):
super().__init__(401, message)
class NotFoundException(APIException):
"""Not found exception (404)"""
def __init__(self, message: str = "Resource not found"):
super().__init__(404, message)
class BadRequestException(APIException):
"""Bad request exception (400)"""
def __init__(self, message: str = "Bad request"):
super().__init__(400, message)
class ForbiddenException(APIException):
"""Forbidden exception (403)"""
def __init__(self, message: str = "Forbidden"):
super().__init__(403, message)
class ConflictException(APIException):
"""Conflict exception (409)"""
def __init__(self, message: str = "Resource already exists"):
super().__init__(409, message)

View file

@ -0,0 +1,28 @@
from typing import Any, Optional
from pydantic import BaseModel
class APIResponse(BaseModel):
"""Unified API response format"""
code: int
message: str
data: Optional[Any] = None
def success_response(data: Any = {}, message: str = "success") -> dict:
"""Create success response"""
return {
"code": 200,
"message": message,
"data": data
}
def error_response(code: int, message: str) -> dict:
"""Create error response"""
return {
"code": code,
"message": message,
"data": None
}

View file

@ -0,0 +1,64 @@
import bcrypt
import jwt
from datetime import datetime, timedelta, timezone
from typing import Optional
from config import settings
def hash_password(password: str) -> str:
"""Hash password using bcrypt"""
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed.decode('utf-8')
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verify password against hash"""
return bcrypt.checkpw(
plain_password.encode('utf-8'),
hashed_password.encode('utf-8')
)
def generate_jwt_token(user_id: str, username: str) -> str:
"""
Generate JWT token for authentication
Args:
user_id: User's unique identifier
username: User's username
Returns:
JWT token string
"""
now = datetime.now(timezone.utc)
payload = {
'user_id': user_id,
'username': username,
'exp': now + timedelta(days=settings.TOKEN_EXPIRE_DAYS),
'iat': now
}
return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
def verify_jwt_token(token: str) -> Optional[dict]:
"""
Verify JWT token and return payload
Args:
token: JWT token string
Returns:
Decoded payload dict if valid, None otherwise
"""
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
return payload
except jwt.ExpiredSignatureError:
# Token has expired
return None
except jwt.InvalidTokenError:
# Token is invalid (tampered, malformed, etc.)
return None

View file

@ -0,0 +1,46 @@
from ulid import ULID
def generate_user_id() -> str:
"""
Generate unique user ID with 'user_' prefix and ULID
Format: user_01JD8X0000ABC123DEF456GH (31 chars total)
- Prefix: user_
- ULID: 26 chars (128-bit unique, time-sortable)
"""
return f"user_{ULID()}"
def generate_agent_id() -> str:
"""
Generate unique agent ID with 'agent_' prefix and ULID
Format: agent_01JD8X0000ABC123DEF456GH (32 chars total)
- Prefix: agent_
- ULID: 26 chars (128-bit unique, time-sortable)
"""
return f"agent_{ULID()}"
def generate_template_id() -> str:
"""
Generate unique template ID with 'template_' prefix and ULID
Format: template_01JD8X0000ABC123DEF456GH (35 chars total)
- Prefix: template_
- ULID: 26 chars (128-bit unique, time-sortable)
"""
return f"template_{ULID()}"
def generate_voice_id() -> str:
"""
Generate unique voice ID with 'voice_' prefix and ULID
Format: voice_01JD8X0000ABC123DEF456GH (32 chars total)
- Prefix: voice_
- ULID: 26 chars (128-bit unique, time-sortable)
"""
return f"voice_{ULID()}"

1739
main/live-agent-api/uv.lock Normal file

File diff suppressed because it is too large Load diff