From 32a941d6f9e4a7592c24169b336142cf810678da Mon Sep 17 00:00:00 2001 From: Harold Date: Tue, 25 Nov 2025 16:52:25 +0800 Subject: [PATCH] feat: dialogue api ready --- main/live-agent-api/api/v1/__init__.py | 9 +- main/live-agent-api/api/v1/chat.py | 106 ++++++++++++ main/live-agent-api/init_db.sql | 31 ++++ main/live-agent-api/repositories/__init__.py | 4 + main/live-agent-api/repositories/chat.py | 165 +++++++++++++++++++ main/live-agent-api/repositories/file.py | 43 +++++ main/live-agent-api/schemas/chat.py | 40 +++++ main/live-agent-api/services/chat_service.py | 129 +++++++++++++++ 8 files changed, 526 insertions(+), 1 deletion(-) create mode 100644 main/live-agent-api/api/v1/chat.py create mode 100644 main/live-agent-api/repositories/chat.py create mode 100644 main/live-agent-api/schemas/chat.py create mode 100644 main/live-agent-api/services/chat_service.py diff --git a/main/live-agent-api/api/v1/__init__.py b/main/live-agent-api/api/v1/__init__.py index 2332adf7e..0f87c7755 100644 --- a/main/live-agent-api/api/v1/__init__.py +++ b/main/live-agent-api/api/v1/__init__.py @@ -1,5 +1,5 @@ from fastapi import APIRouter -from api.v1 import user, templates, agents, voices, internal +from api.v1 import user, templates, agents, voices, internal, chat api_router = APIRouter() @@ -38,3 +38,10 @@ api_router.include_router( tags=["Internal"] ) +# Chat routes +api_router.include_router( + chat.router, + prefix="/chat", + tags=["Chat"] +) + diff --git a/main/live-agent-api/api/v1/chat.py b/main/live-agent-api/api/v1/chat.py new file mode 100644 index 000000000..d9be0b103 --- /dev/null +++ b/main/live-agent-api/api/v1/chat.py @@ -0,0 +1,106 @@ +""" +Chat API endpoints - Message reporting and retrieval +""" +from fastapi import APIRouter, Depends, Query +from sqlalchemy.ext.asyncio import AsyncSession +from typing import Optional + +from infra import get_db, get_s3 +from services.chat_service import chat_service +from schemas.chat import ( + ReportChatMessageRequest, + ChatMessage, + ChatMessagesListResponse +) + +router = APIRouter() + + +@router.post("/report", response_model=ChatMessage) +async def report_message( + request: ReportChatMessageRequest, + db: AsyncSession = Depends(get_db), + s3 = Depends(get_s3) +): + """ + Report a new chat message from xiaozhi-server + + Process: + - Receives opus audio as base64 + - Uploads audio to S3 using FileRepository + - Stores message with S3 URLs in database + + Request Body: + - agent_id: Agent ID + - chat_type: 1=user, 2=agent + - content: List of message parts (text, image, file URLs) + - audio_base64: Optional opus audio in base64 format + + Returns: + Created message with S3 URLs + """ + return await chat_service.report_message(db=db, s3=s3, request=request) + + +@router.get("/{agent_id}/messages", response_model=ChatMessagesListResponse) +async def get_agent_messages( + agent_id: str, + cursor: Optional[str] = Query(None, description="Message ID (ULID) cursor for pagination"), + limit: int = Query(50, ge=1, le=100, description="Number of messages to fetch"), + include_audio: bool = Query(False, description="Load audio base64 from S3"), + db: AsyncSession = Depends(get_db), + s3 = Depends(get_s3) +): + """ + Get chat messages for an agent using cursor-based pagination (chat style) + + Features: + - Returns latest messages first (DESC order, newest at top) + - Scroll up to load older messages (typical chat UI behavior) + - Cursor-based pagination for efficient real-time chat + - Lazy audio loading (only when include_audio=True) + + Query Parameters: + - cursor: Message ID (ULID) to load messages before. If None, load latest messages + - limit: Number of messages to fetch (1-100, default 50) + - include_audio: If True, downloads opus from S3 and returns as base64 + + Returns: + - messages: List of chat messages (newest first in each batch) + - next_cursor: Message ID for loading older messages (None if no more history) + - has_more: Whether there are more older messages + + Example: + # First request - get latest 50 messages + GET /chat/agent_123/messages?limit=50 + Response: { + messages: [newest_msg, ..., oldest_msg_in_batch], + next_cursor: "01JD8X0000ABC", # ID of oldest message in this batch + has_more: true + } + + # Scroll up - load older messages before cursor + GET /chat/agent_123/messages?cursor=01JD8X0000ABC&limit=50 + Response: { + messages: [newer_old_msg, ..., older_msg], + next_cursor: "01JD8W0000XYZ", + has_more: true + } + + # Continue until has_more is false (reached the beginning of chat history) + """ + messages, next_cursor, has_more = await chat_service.get_agent_messages( + db=db, + s3=s3, + agent_id=agent_id, + cursor=cursor, + limit=limit, + include_audio=include_audio + ) + + return ChatMessagesListResponse( + messages=messages, + next_cursor=next_cursor, + has_more=has_more + ) + diff --git a/main/live-agent-api/init_db.sql b/main/live-agent-api/init_db.sql index db4e9c61a..4c33116f3 100644 --- a/main/live-agent-api/init_db.sql +++ b/main/live-agent-api/init_db.sql @@ -113,6 +113,37 @@ COMMENT ON TABLE agent_templates IS 'Pre-configured agent templates for quick se 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'; +-- ==================== Table: chat_messages ==================== +-- Chat messages table with unified content structure +CREATE TABLE IF NOT EXISTS chat_messages ( + id SERIAL PRIMARY KEY, + message_id VARCHAR(50) UNIQUE NOT NULL, + agent_id VARCHAR(50) NOT NULL, + role SMALLINT NOT NULL CHECK (role IN (1, 2)), + content JSONB NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), + CONSTRAINT fk_chat_messages_agent FOREIGN KEY (agent_id) + REFERENCES agents(agent_id) ON DELETE CASCADE +); + +-- Indexes for chat_messages table +-- Unique index for message_id (business key, used for API and S3 file naming) +CREATE UNIQUE INDEX IF NOT EXISTS idx_chat_messages_message_id ON chat_messages(message_id); +-- Single-column index for agent filtering +CREATE INDEX IF NOT EXISTS idx_chat_messages_agent_id ON chat_messages(agent_id); +-- Composite index for cursor-based pagination (agent_id + message_id for efficient range queries) +CREATE INDEX IF NOT EXISTS idx_chat_messages_agent_message_composite ON chat_messages(agent_id, message_id); +-- GIN index for JSONB content search (future feature: search by message type, content, etc.) +CREATE INDEX IF NOT EXISTS idx_chat_messages_content_gin ON chat_messages USING GIN (content); + +-- Comments for chat_messages table +COMMENT ON TABLE chat_messages IS 'Chat messages with unified content structure (text and S3 URLs)'; +COMMENT ON COLUMN chat_messages.message_id IS 'External unique identifier (ULID) for API and S3 file naming'; +COMMENT ON COLUMN chat_messages.agent_id IS 'Agent ID this message belongs to'; +COMMENT ON COLUMN chat_messages.role IS 'Message role: 1=user, 2=agent'; +COMMENT ON COLUMN chat_messages.content IS 'JSONB array: [{"message_type": "text|audio|image|file", "message_content": "text or S3 URL"}]'; +COMMENT ON COLUMN chat_messages.created_at IS 'Message creation timestamp (UTC)'; + -- ==================== Functions ==================== -- Function to automatically update updated_at timestamp CREATE OR REPLACE FUNCTION update_updated_at_column() diff --git a/main/live-agent-api/repositories/__init__.py b/main/live-agent-api/repositories/__init__.py index 9908149cf..817739a45 100644 --- a/main/live-agent-api/repositories/__init__.py +++ b/main/live-agent-api/repositories/__init__.py @@ -7,12 +7,14 @@ from .user import UserModel from .agent import AgentModel from .agent_template import AgentTemplateModel from .voice import VoiceModel +from .chat import ChatMessageModel # Import Repository classes from .user import User from .agent import Agent from .agent_template import AgentTemplate from .voice import Voice +from .chat import ChatMessage from .file import FileRepository __all__ = [ @@ -21,11 +23,13 @@ __all__ = [ "AgentModel", "AgentTemplateModel", "VoiceModel", + "ChatMessageModel", # Repository classes "User", "Agent", "AgentTemplate", "Voice", + "ChatMessage", "FileRepository", ] diff --git a/main/live-agent-api/repositories/chat.py b/main/live-agent-api/repositories/chat.py new file mode 100644 index 000000000..ddb8e2cfb --- /dev/null +++ b/main/live-agent-api/repositories/chat.py @@ -0,0 +1,165 @@ +""" +Chat messages repository - Database operations for chat messages +""" +from datetime import datetime +from typing import List, Optional, Tuple +from sqlalchemy import String, SmallInteger, TIMESTAMP, ForeignKey, Index, select, insert +from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.dialects.postgresql import JSONB + +from infra.database import Base, utc_now + + +# ==================== ORM Model ==================== + +class ChatMessageModel(Base): + __tablename__ = "chat_messages" + + # Primary key (internal) + id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + + # Business key (external, ULID) + message_id: Mapped[str] = mapped_column(String(50), unique=True, nullable=False) + + # Foreign key to agents table (agent_id) + agent_id: Mapped[str] = mapped_column( + String(50), + ForeignKey("agents.agent_id", ondelete="CASCADE"), + nullable=False + ) + + # Message type: 1=user, 2=agent + role: Mapped[int] = mapped_column(SmallInteger, nullable=False) + + # JSONB content: [{"message_type": "text|audio|image|file", "message_content": "..."}] + content: Mapped[List[dict]] = mapped_column(JSONB, nullable=False) + + # Timestamp + created_at: Mapped[datetime] = mapped_column( + TIMESTAMP(timezone=True), + default=utc_now, + nullable=False + ) + + __table_args__ = ( + Index('idx_chat_messages_message_id', 'message_id', unique=True), + Index('idx_chat_messages_agent_id', 'agent_id'), + Index('idx_chat_messages_agent_message_composite', 'agent_id', 'message_id'), + Index('idx_chat_messages_content_gin', 'content', postgresql_using='gin'), + ) + + def __repr__(self): + return f"" + + +# ==================== Repository (CRUD Operations) ==================== + +class ChatMessage: + """ + Chat Message Repository - Handles all database operations + """ + + @staticmethod + async def create( + db: AsyncSession, + message_id: str, + agent_id: str, + role: int, + content: List[dict] # Already processed with S3 URLs + ) -> ChatMessageModel: + """ + Create new chat message + + Args: + db: Database session + message_id: Message ID (ULID) + agent_id: Agent ID + role: 1=user, 2=agent + content: List of message parts with S3 URLs + + Returns: + Created message model + """ + message = ChatMessageModel( + message_id=message_id, + agent_id=agent_id, + role=role, + content=content + ) + db.add(message) + await db.commit() + await db.refresh(message) + return message + + @staticmethod + async def get_by_agent_cursor( + db: AsyncSession, + agent_id: str, + cursor: Optional[str] = None, + limit: int = 50 + ) -> Tuple[List[ChatMessageModel], Optional[str], bool]: + """ + Get messages by agent_id using cursor-based pagination (chat style) + + Behavior: + - First load (no cursor): Returns the latest messages (DESC order) + - Scroll up (with cursor): Returns older messages before the cursor + + Args: + db: Database session + agent_id: Agent ID + cursor: Message ID (ULID) to load messages before. If None, load latest messages + limit: Number of messages to fetch + + Returns: + Tuple of (messages, next_cursor, has_more) + """ + # Build query with cursor + query = select(ChatMessageModel).where(ChatMessageModel.agent_id == agent_id) + + # Apply cursor filter if provided - load messages BEFORE cursor (older messages) + if cursor: + query = query.where(ChatMessageModel.message_id < cursor) + + # Order by message_id DESC to get latest messages first + # Fetch limit + 1 to check if there are more records + query = query.order_by(ChatMessageModel.message_id.desc()).limit(limit + 1) + + result = await db.execute(query) + messages: List[ChatMessageModel] = result.scalars().all() + + # Check if there are more messages + has_more = len(messages) > limit + if has_more: + messages = messages[:limit] + + # Get next cursor (oldest message_id in current batch for loading earlier messages) + next_cursor = None + if has_more and messages: + next_cursor = messages[-1].message_id + + return messages, next_cursor, has_more + + @staticmethod + async def get_latest_by_agent( + db: AsyncSession, + agent_id: str + ) -> Optional[ChatMessageModel]: + """ + Get the latest message for a specific agent + + Args: + db: Database session + agent_id: Agent ID + + Returns: + Latest message model or None + """ + query = select(ChatMessageModel).where( + ChatMessageModel.agent_id == agent_id + ).order_by(ChatMessageModel.id.desc()).limit(1) + + result = await db.execute(query) + return result.scalar_one_or_none() + diff --git a/main/live-agent-api/repositories/file.py b/main/live-agent-api/repositories/file.py index 04c29b720..ff6312ee3 100644 --- a/main/live-agent-api/repositories/file.py +++ b/main/live-agent-api/repositories/file.py @@ -141,3 +141,46 @@ class FileRepository: """ return await FileRepository.upload(s3, file, folder="voice_audios", custom_filename=entity_id) + @staticmethod + async def upload_chat_audio( + s3, + audio_data: bytes, + agent_id: str, + message_id: str, + file_ext: str = "opus" + ) -> str: + """ + Upload chat audio to S3 (for chat messages) + + Args: + s3: S3 client + audio_data: Raw audio bytes (opus format) + agent_id: Agent ID for organizing files + message_id: Message ID (ULID) for unique filename + file_ext: Audio file extension (default: opus) + + Returns: + Public URL of uploaded audio + + Example: + url = await FileRepository.upload_chat_audio( + s3, audio_bytes, "agent_123", "01JD8X0000ABC" + ) + # Result: https://s3.../chat-audio/agent_123/01JD8X0000ABC.opus + """ + # Use message_id as filename (ULID is unique and time-ordered) + filename = f"{message_id}.{file_ext}" + s3_key = f"chat-audio/{agent_id}/{filename}" + + # Upload to S3 + await s3.put_object( + Bucket=settings.S3_BUCKET_NAME, + Key=s3_key, + Body=audio_data, + ContentType=f"audio/{file_ext}", + ) + + # Generate public URL + url = f"{settings.S3_PUBLIC_BASE_URL}/{settings.S3_BUCKET_NAME}/{s3_key}" + return url + diff --git a/main/live-agent-api/schemas/chat.py b/main/live-agent-api/schemas/chat.py new file mode 100644 index 000000000..25a63c932 --- /dev/null +++ b/main/live-agent-api/schemas/chat.py @@ -0,0 +1,40 @@ +""" +Chat messages schemas for API request/response validation +""" +from pydantic import BaseModel, Field +from typing import List, Literal, Optional +from datetime import datetime +import enum + + +class MessageBody(BaseModel): + """Individual message content part (text, audio, image, or file)""" + message_type: Literal["text", "audio", "image", "file"] + message_content: str | bytes # Text content or S3 URL + +class ChatRole(enum.Enum): + USER = 1 + AGENT = 2 + +class ReportChatMessageRequest(BaseModel): + """Request schema for reporting a chat message from dialogue server""" + agent_id: str = Field(..., max_length=50, description="Agent ID") + role: ChatRole = Field(..., description="1: user, 2: agent") + content: List[MessageBody] = Field(..., description="Message content parts") + + +class ChatMessage(BaseModel): + """Response schema for a single chat message""" + message_id: str + agent_id: str + role: ChatRole + content: List[MessageBody] + created_at: datetime + + +class ChatMessagesListResponse(BaseModel): + """Response schema for paginated chat messages (cursor-based, chat style)""" + messages: List[ChatMessage] + next_cursor: Optional[str] = Field(None, description="Message ID to load older messages (pass as cursor for next request)") + has_more: bool = Field(False, description="Whether there are more older messages available") + diff --git a/main/live-agent-api/services/chat_service.py b/main/live-agent-api/services/chat_service.py new file mode 100644 index 000000000..d900f737d --- /dev/null +++ b/main/live-agent-api/services/chat_service.py @@ -0,0 +1,129 @@ +""" +Chat service - Business logic for chat messages +""" +import base64 +from typing import List, Optional, Tuple +from sqlalchemy.ext.asyncio import AsyncSession +from copy import deepcopy + +from repositories.chat import ChatMessage as ChatMessageRepo +from repositories.file import FileRepository +from schemas.chat import ReportChatMessageRequest, ChatMessage as ChatMessageSchema +from utils.ulid import ULID + + +class ChatService: + """Service layer for chat message operations""" + + async def report_message( + self, + db: AsyncSession, + s3, + request: ReportChatMessageRequest + ) -> ChatMessageSchema: + """ + Handle message reporting from xiaozhi-server + + Process: + 1. Generate message_id (ULID) + 2. If audio exists: upload to S3 using message_id as filename + 3. Store message with S3 URLs in database + + Args: + db: Database session + s3: S3 client + request: Chat message report request + + Returns: + Created message response + """ + # Generate unique message_id (ULID - time-ordered and unique) + message_id = str(ULID()) + + contents = deepcopy(request.content) + + # Handle audio upload if present + for message in contents: + if message.message_type != "audio": + continue + + # Upload to S3 using FileRepository with message_id + audio_url = await FileRepository.upload_chat_audio( + s3, + message.message_content, + request.agent_id, + message_id=message_id, + file_ext="opus" + ) + + # Replace audio content with S3 URL + message.message_content = audio_url + + # Convert Pydantic models to dict for JSONB storage + content_dicts = [msg.model_dump() for msg in contents] + + # Store in database + chat_message = await ChatMessageRepo.create( + db=db, + message_id=message_id, + agent_id=request.agent_id, + role=request.role.value, + content=content_dicts + ) + + return ChatMessageSchema( + message_id=chat_message.message_id, + agent_id=chat_message.agent_id, + role=chat_message.role, + content=chat_message.content, + created_at=chat_message.created_at + ) + + async def get_agent_messages( + self, + db: AsyncSession, + s3, + agent_id: str, + cursor: Optional[str] = None, + limit: int = 50, + include_audio: bool = False + ) -> Tuple[List[ChatMessageSchema], Optional[str], bool]: + """ + Retrieve messages for an agent using cursor-based pagination + + Process: + 1. Fetch messages from database using cursor (message_id based) + 2. Return messages with S3 URLs (lazy loading) + + Args: + db: Database session + s3: S3 client + agent_id: Agent ID + cursor: Message ID (ULID) cursor for pagination + limit: Number of messages to fetch + include_audio: Whether to load audio from S3 (not used yet) + + Returns: + Tuple of (messages, next_cursor, has_more) + """ + messages, next_cursor, has_more = await ChatMessageRepo.get_by_agent_cursor( + db=db, + agent_id=agent_id, + cursor=cursor, + limit=limit + ) + response_messages: List[ChatMessageSchema] = [] + for message in messages: + response_messages.append(ChatMessageSchema( + message_id=message.message_id, + agent_id=message.agent_id, + role=message.role, + content=message.content, + created_at=message.created_at + )) + + return response_messages, next_cursor, has_more + + +# Global singleton instance +chat_service = ChatService()