mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: dialogue api ready
This commit is contained in:
parent
d11aec58b1
commit
32a941d6f9
8 changed files with 526 additions and 1 deletions
|
|
@ -1,5 +1,5 @@
|
||||||
from fastapi import APIRouter
|
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()
|
api_router = APIRouter()
|
||||||
|
|
||||||
|
|
@ -38,3 +38,10 @@ api_router.include_router(
|
||||||
tags=["Internal"]
|
tags=["Internal"]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Chat routes
|
||||||
|
api_router.include_router(
|
||||||
|
chat.router,
|
||||||
|
prefix="/chat",
|
||||||
|
tags=["Chat"]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
|
||||||
106
main/live-agent-api/api/v1/chat.py
Normal file
106
main/live-agent-api/api/v1/chat.py
Normal file
|
|
@ -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
|
||||||
|
)
|
||||||
|
|
||||||
|
|
@ -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.template_id IS 'External unique identifier (e.g., ULID)';
|
||||||
COMMENT ON COLUMN agent_templates.voice_id IS 'Default voice ID for this template';
|
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 ====================
|
-- ==================== Functions ====================
|
||||||
-- Function to automatically update updated_at timestamp
|
-- Function to automatically update updated_at timestamp
|
||||||
CREATE OR REPLACE FUNCTION update_updated_at_column()
|
CREATE OR REPLACE FUNCTION update_updated_at_column()
|
||||||
|
|
|
||||||
|
|
@ -7,12 +7,14 @@ from .user import UserModel
|
||||||
from .agent import AgentModel
|
from .agent import AgentModel
|
||||||
from .agent_template import AgentTemplateModel
|
from .agent_template import AgentTemplateModel
|
||||||
from .voice import VoiceModel
|
from .voice import VoiceModel
|
||||||
|
from .chat import ChatMessageModel
|
||||||
|
|
||||||
# Import Repository classes
|
# Import Repository classes
|
||||||
from .user import User
|
from .user import User
|
||||||
from .agent import Agent
|
from .agent import Agent
|
||||||
from .agent_template import AgentTemplate
|
from .agent_template import AgentTemplate
|
||||||
from .voice import Voice
|
from .voice import Voice
|
||||||
|
from .chat import ChatMessage
|
||||||
from .file import FileRepository
|
from .file import FileRepository
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
|
|
@ -21,11 +23,13 @@ __all__ = [
|
||||||
"AgentModel",
|
"AgentModel",
|
||||||
"AgentTemplateModel",
|
"AgentTemplateModel",
|
||||||
"VoiceModel",
|
"VoiceModel",
|
||||||
|
"ChatMessageModel",
|
||||||
# Repository classes
|
# Repository classes
|
||||||
"User",
|
"User",
|
||||||
"Agent",
|
"Agent",
|
||||||
"AgentTemplate",
|
"AgentTemplate",
|
||||||
"Voice",
|
"Voice",
|
||||||
|
"ChatMessage",
|
||||||
"FileRepository",
|
"FileRepository",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
|
||||||
165
main/live-agent-api/repositories/chat.py
Normal file
165
main/live-agent-api/repositories/chat.py
Normal file
|
|
@ -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"<ChatMessageModel(id={self.id}, message_id={self.message_id}, agent_id={self.agent_id})>"
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 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()
|
||||||
|
|
||||||
|
|
@ -141,3 +141,46 @@ class FileRepository:
|
||||||
"""
|
"""
|
||||||
return await FileRepository.upload(s3, file, folder="voice_audios", custom_filename=entity_id)
|
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
|
||||||
|
|
||||||
|
|
|
||||||
40
main/live-agent-api/schemas/chat.py
Normal file
40
main/live-agent-api/schemas/chat.py
Normal file
|
|
@ -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")
|
||||||
|
|
||||||
129
main/live-agent-api/services/chat_service.py
Normal file
129
main/live-agent-api/services/chat_service.py
Normal file
|
|
@ -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()
|
||||||
Loading…
Reference in a new issue