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

feat: Add AIGC voice APIs, chat message system, and file upload endpoints
This commit is contained in:
Harold-Guo 2025-11-25 17:55:34 +08:00 committed by GitHub
commit 866a5579ed
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 1258 additions and 2 deletions

View file

@ -0,0 +1,243 @@
services:
# ============================================================================
# xiaozhi-server (Python WebSocket Server)
# ============================================================================
xiaozhi-esp32-server:
build:
context: ./xiaozhi-server/
dockerfile: Dockerfile
image: xiaozhi-esp32-server:local
container_name: xiaozhi-esp32-server
depends_on:
xiaozhi-esp32-server-db:
condition: service_healthy
xiaozhi-esp32-server-redis:
condition: service_healthy
restart: unless-stopped
networks:
- xiaozhi-network
ports:
# WebSocket server
- "8000:8000"
# HTTP server for vision analysis and OTA
- "8003:8003"
security_opt:
- seccomp:unconfined
environment:
- TZ=Asia/Shanghai
- PYTHONUNBUFFERED=1
- LOG_LEVEL=INFO
- REGION=LOCAL
healthcheck:
disable: true
volumes:
# Configuration directory
- ./xiaozhi-server/data:/opt/xiaozhi-esp32-server/data
# Custom config (optional override, uncomment if you need to customize)
- ./xiaozhi-server/custom_config.yaml:/opt/xiaozhi-esp32-server/custom_config.yaml
# Model files (important!)
- ./xiaozhi-server/models/SenseVoiceSmall:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall
- ./xiaozhi-server/models/snakers4_silero-vad:/opt/xiaozhi-esp32-server/models/snakers4_silero-vad
# Temporary files
- ./xiaozhi-server/tmp:/opt/xiaozhi-esp32-server/tmp
# Music files (optional)
- ./xiaozhi-server/music:/opt/xiaozhi-esp32-server/music
# Logs (optional, for debugging)
- ./xiaozhi-server/logs:/opt/xiaozhi-esp32-server/logs
# ============================================================================
# manager-web (Management Console + API)
# ============================================================================
xiaozhi-esp32-server-web:
# Build from local source (supports ARM64/Apple Silicon)
build:
context: ../
dockerfile: Dockerfile-web
image: xiaozhi-esp32-server-web:local
# Option: Use pre-built image from registry (x86 only)
# image: ghcr.nju.edu.cn/xinnan-tech/xiaozhi-esp32-server:web_latest
# platform: linux/amd64 # Uncomment to force x86 emulation on ARM64
container_name: xiaozhi-esp32-server-web
restart: unless-stopped
networks:
- xiaozhi-network
depends_on:
xiaozhi-esp32-server-db:
condition: service_healthy
xiaozhi-esp32-server-redis:
condition: service_healthy
ports:
# Management console and API
- "8002:8002"
environment:
- TZ=Asia/Shanghai
- SPRING_PROFILES_ACTIVE=dev
# Database connection
- SPRING_DATASOURCE_DRUID_URL=jdbc:mysql://xiaozhi-esp32-server-db:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&connectTimeout=30000&socketTimeout=30000&autoReconnect=true&failOverReadOnly=false&maxReconnects=10
- SPRING_DATASOURCE_DRUID_USERNAME=root
- SPRING_DATASOURCE_DRUID_PASSWORD=123456
# Redis connection
- SPRING_DATA_REDIS_HOST=xiaozhi-esp32-server-redis
- SPRING_DATA_REDIS_PORT=6379
- SPRING_DATA_REDIS_PASSWORD=
volumes:
# Upload files directory
- ./xiaozhi-server/uploadfile:/uploadfile
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
# ============================================================================
# MySQL Database
# ============================================================================
xiaozhi-esp32-server-db:
image: mysql:8.0
container_name: xiaozhi-esp32-server-db
restart: unless-stopped
networks:
- xiaozhi-network
ports:
# Expose MySQL port for local debugging (optional)
- "3307:3306"
volumes:
# Persistent database storage
- ./xiaozhi-server/mysql/data:/var/lib/mysql
# MySQL configuration (optional)
# - ./xiaozhi-server/mysql/conf:/etc/mysql/conf.d
environment:
- TZ=Asia/Shanghai
- MYSQL_ROOT_PASSWORD=123456
- MYSQL_DATABASE=xiaozhi_esp32_server
- MYSQL_INITDB_ARGS=--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
command:
- --character-set-server=utf8mb4
- --collation-server=utf8mb4_unicode_ci
- --default-authentication-plugin=mysql_native_password
- --max_connections=1000
- --max_allowed_packet=256M
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p123456"]
timeout: 45s
interval: 10s
retries: 10
start_period: 60s
# ============================================================================
# Redis Cache
# ============================================================================
xiaozhi-esp32-server-redis:
image: redis:7-alpine
container_name: xiaozhi-esp32-server-redis
restart: unless-stopped
networks:
- xiaozhi-network
ports:
# Expose Redis port for local debugging (optional)
- "6380:6379"
volumes:
# Persistent Redis data (optional)
- ./xiaozhi-server/redis/data:/data
environment:
- TZ=Asia/Shanghai
command: redis-server --appendonly yes --maxmemory 512mb --maxmemory-policy allkeys-lru
logging:
driver: "json-file"
options:
max-size: "5m"
max-file: "3"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 3
start_period: 10s
# ============================================================================
# live-agent-api Services
# ============================================================================
live-agent-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:
- ./live-agent-api/data/postgres:/var/lib/postgresql/data
- ./live-agent-api/init_db.sql:/docker-entrypoint-initdb.d/init_db.sql
networks:
- xiaozhi-network
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5
live-agent-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:
- "19000:9000"
- "19001:9001"
volumes:
- ./live-agent-api/data/minio:/data
networks:
- xiaozhi-network
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
interval: 10s
timeout: 5s
retries: 5
live-agent-api:
build:
context: ./live-agent-api
dockerfile: Dockerfile
container_name: live-agent-api
env_file:
- ./live-agent-api/.env
environment:
DATABASE_URL: postgresql+asyncpg://postgres:postgres@live-agent-postgres:5432/live_agent
S3_ENDPOINT_URL: http://live-agent-minio:9000
DEBUG: "True"
ports:
- "8080:8080"
networks:
- xiaozhi-network
depends_on:
live-agent-postgres:
condition: service_healthy
live-agent-minio:
condition: service_healthy
# ============================================================================
# Networks
# ============================================================================
networks:
xiaozhi-network:
driver: bridge
name: xiaozhi-network
# ============================================================================
# Volumes (optional - for named volumes instead of bind mounts)
# ============================================================================
# volumes:
# mysql-data:
# redis-data:

View file

@ -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, files, chat
api_router = APIRouter()
@ -38,3 +38,17 @@ api_router.include_router(
tags=["Internal"]
)
# File upload routes (for App only)
api_router.include_router(
files.router,
prefix="/files",
tags=["Files"]
)
# Chat routes
api_router.include_router(
chat.router,
prefix="/chat",
tags=["Chat"]
)

View file

@ -1,9 +1,12 @@
from typing import Optional
from fastapi import APIRouter, Depends, Query, Form, File, UploadFile
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
from infra import get_db, get_s3
from infra.openai import get_openai
from services.agent_service import agent_service
from services.llm_service import llm_service
from utils.response import success_response
from api.auth import get_current_user_id
from schemas.agent import AgentResponse
@ -136,3 +139,41 @@ async def delete_agent(
)
return success_response(data={}, message="Agent deleted successfully")
@router.post("/instructions", summary="Optimize Agent Instruction")
async def optimize_instruction(
instruction: str = Form(..., description="Original instruction text"),
current_user_id: str = Depends(get_current_user_id),
openai_client = Depends(get_openai)
):
"""
Optimize agent instruction using LLM (streaming)
- **instruction**: Original instruction text from user
- Returns streaming optimized instruction text
The optimization process:
- Enhances role definition and clarity
- Adds behavior guidelines and tone specification
- Structures the instruction professionally
- Ensures helpful, focused, and actionable content
"""
async def instruction_generator():
"""Generate optimized instruction chunks"""
try:
async for chunk in llm_service.optimize_instruction_stream(
openai_client=openai_client,
original_instruction=instruction
):
yield chunk
except Exception as e:
# Error already yielded in service, just log
import logging
logging.error(f"Instruction optimization failed: {e}")
return StreamingResponse(
instruction_generator(),
media_type="text/plain; charset=utf-8"
)

View 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
)

View file

@ -0,0 +1,71 @@
"""
File upload API endpoints (for App only)
"""
from fastapi import APIRouter, File, UploadFile, Depends, Form, HTTPException
from infra import get_s3
from repositories import FileRepository
from utils.response import success_response
from api.auth import get_current_user_id
router = APIRouter()
@router.post("/upload", summary="Upload file to S3 (App only)")
async def upload_file(
file: UploadFile = File(..., description="File to upload (image, PDF, etc.)"),
agent_id: str = Form(..., description="Agent ID (required, for organizing files by agent)"),
current_user_id: str = Depends(get_current_user_id), # need user authentication
s3 = Depends(get_s3)
):
"""
Upload file to S3 storage (for App clients only)
Headers:
- Authorization: Bearer <token> (required)
Form Data:
- file: File to upload (required)
- agent_id: Agent ID (required, for organizing files by agent)
Returns:
- url: Public URL of uploaded file
- filename: Original filename
- size: File size in bytes
Example:
POST /api/live_agent/v1/files/upload
Headers:
Authorization: Bearer eyJhbGc...
Form Data:
file: [binary data]
agent_id: agent_01JD8X0000ABC
"""
# Validate agent_id format (basic validation)
if not agent_id or len(agent_id.strip()) == 0:
raise HTTPException(status_code=400, detail="agent_id cannot be empty")
folder = f"files/{agent_id}"
# Upload to S3 using FileRepository
name = file.filename.split('.')[0] if '.' in file.filename else file.filename
file_url = await FileRepository.upload(
s3=s3,
file=file,
folder=folder,
custom_filename=name
)
# file size
await file.seek(0)
content = await file.read()
file_size = len(content)
return success_response(
data={
"url": file_url,
"filename": file.filename,
"size": file_size
},
message="File uploaded successfully"
)

View file

@ -1,11 +1,14 @@
from typing import Optional, List
from botocore.args import logger
from fastapi import APIRouter, Depends, Query, Form, File, UploadFile
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
from infra import get_db, get_s3
from infra.fishaudio import get_fish_audio
from infra.openai import get_openai
from services.voice_service import voice_service
from services.llm_service import llm_service
from schemas.voice import (
LiveAgentVoice,
DiscoverVoiceResponse,
@ -265,4 +268,42 @@ async def remove_voice(
return success_response(
data={"voice_id": voice_id},
message="Voice removed successfully"
)
@router.post("/sample_text", summary="Generate Voice Sample Text")
async def generate_voice_sample_text(
language: str = Form(..., description="Language code (zh, en, ja, etc.)"),
current_user_id: str = Depends(get_current_user_id),
openai_client = Depends(get_openai)
):
"""
Generate expressive text sample for voice cloning (streaming)
- **language**: Target language code (zh, en, ja, ko, etc.)
- Returns streaming text with rich emotional expression
- Supports regenerate by calling again with same parameters
The generated text is optimized for voice cloning with:
- Varied tone and emotional expression
- Appropriate length (80-150 characters)
- Natural, engaging content
"""
async def text_generator():
"""Generate text chunks"""
try:
async for chunk in llm_service.generate_voice_sample_text_stream(
openai_client=openai_client,
language=language
):
yield chunk
except Exception as e:
# Error already yielded in service, just log
import logging
logging.error(f"Voice sample text generation failed: {e}")
return StreamingResponse(
text_generator(),
media_type="text/plain; charset=utf-8"
)

View file

@ -29,6 +29,11 @@ class Settings(BaseSettings):
# Fish Audio Configuration
FISH_API_KEY: str
# OpenAI Configuration
OPENAI_API_KEY: str
OPENAI_MODEL: str = "gpt-4o-mini"
OPENAI_BASE_URL: str = "https://api.openai.com/v1"
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",

View file

@ -44,3 +44,8 @@ DEBUG=True
# External Services
FISH_API_KEY=your-fish-audio-api-key-here
# OpenAI Configuration
OPENAI_API_KEY=sk-your-openai-api-key-here
OPENAI_MODEL=gpt-4o-mini
# OPENAI_BASE_URL=https://api.openai.com/v1

View file

@ -21,6 +21,11 @@ from .fishaudio import (
init_fish_audio,
close_fish_audio,
)
from .openai import (
get_openai,
init_openai,
close_openai,
)
__all__ = [
# Database
@ -39,5 +44,9 @@ __all__ = [
"get_fish_audio",
"init_fish_audio",
"close_fish_audio",
# OpenAI
"get_openai",
"init_openai",
"close_openai",
]

View file

@ -0,0 +1,31 @@
"""OpenAI client infrastructure"""
from openai import AsyncOpenAI
from config import settings
# Global OpenAI client instance
_openai_client: AsyncOpenAI | None = None
async def init_openai():
"""Initialize OpenAI client"""
global _openai_client
_openai_client = AsyncOpenAI(
api_key=settings.OPENAI_API_KEY,
base_url=settings.OPENAI_BASE_URL
)
async def close_openai():
"""Close OpenAI client"""
global _openai_client
if _openai_client:
await _openai_client.close()
_openai_client = None
def get_openai() -> AsyncOpenAI:
"""Get OpenAI client instance (dependency injection)"""
if _openai_client is None:
raise RuntimeError("OpenAI client not initialized")
return _openai_client

View file

@ -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()

View file

@ -4,7 +4,7 @@ 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 infra import init_db, close_db, init_s3, close_s3, init_fish_audio, close_fish_audio, init_openai, close_openai
from api.v1 import api_router
from utils.exceptions import APIException
@ -20,6 +20,8 @@ async def lifespan(app: FastAPI):
print("S3 connection initialized")
await init_fish_audio()
print("Fish Audio client initialized")
await init_openai()
print("OpenAI client initialized")
yield
@ -31,6 +33,8 @@ async def lifespan(app: FastAPI):
print("S3 connections closed")
await close_fish_audio()
print("Fish Audio client closed")
await close_openai()
print("OpenAI client closed")
# Create FastAPI application

View file

@ -19,6 +19,7 @@ dependencies = [
"aioboto3>=15.5.0",
"pyjwt>=2.9.0",
"fish-audio-sdk>=1.1.0",
"openai>=1.54.0",
]
[project.optional-dependencies]

View file

@ -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",
]

View 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()

View file

@ -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

View 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 # 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")

View file

@ -0,0 +1,135 @@
"""
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
# Decode base64 audio to bytes (service layer handles data transformation)
try:
audio_bytes = base64.b64decode(message.message_content)
except Exception as e:
raise ValueError(f"Invalid base64 audio data: {e}")
# Upload to S3 using FileRepository with message_id
audio_url = await FileRepository.upload_chat_audio(
s3,
audio_bytes,
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()

View file

@ -0,0 +1,157 @@
"""LLM service for text generation"""
from typing import AsyncGenerator
from openai import AsyncOpenAI
from config import settings
class LLMService:
"""Service for LLM-based text generation"""
# System prompts
VOICE_TEXT_SYSTEM_PROMPT = """You are a creative writer specializing in generating expressive text samples for voice cloning.
Your task: Generate vivid, emotionally rich text that showcases voice characteristics.
Requirements:
- Rich in tone variation (questions, exclamations, pauses, emotions)
- Natural emotional expression (joy, surprise, contemplation, warmth)
- Appropriate length: 80-150 characters for optimal voice capture
- Match the specified language and cultural context
- Use descriptive, sensory language
- Avoid monotone or flat sentences
Output ONLY the text sample, no explanations or metadata."""
INSTRUCTION_OPTIMIZATION_SYSTEM_PROMPT = """You are an expert AI prompt engineer specializing in agent instruction optimization.
Your task: Transform user's basic instruction into a professional, comprehensive agent system prompt.
Optimization guidelines:
1. **Role Definition**: Clearly define the agent's persona and expertise
2. **Behavior Guidelines**: Specify tone, communication style, and interaction patterns
3. **Task Scope**: Define what the agent should and shouldn't do
4. **Response Format**: Suggest how responses should be structured
5. **Helpful & On-Task**: Keep the agent focused, supportive, and practical
Output format:
- Write in second person ("You are...")
- Be clear, specific, and actionable
- Length: 100-300 words
- Professional yet accessible tone
Output ONLY the optimized instruction, no explanations or metadata."""
async def generate_voice_sample_text_stream(
self,
openai_client: AsyncOpenAI,
language: str
) -> AsyncGenerator[str, None]:
"""
Generate voice sample text with streaming
Args:
openai_client: OpenAI client instance
language: Target language code (zh, en, ja, etc.)
Yields:
Text chunks as they are generated
Raises:
Exception: If OpenAI API call fails
"""
# Map language codes to full names for better context
language_map = {
"zh": "Chinese (Simplified)",
"zh-CN": "Chinese (Simplified)",
"zh-TW": "Chinese (Traditional)",
"en": "English",
"en-US": "English (US)",
"en-GB": "English (UK)",
"ja": "Japanese",
"ko": "Korean",
"es": "Spanish",
"fr": "French",
"de": "German",
"it": "Italian",
"pt": "Portuguese",
"ru": "Russian",
"ar": "Arabic",
}
language_name = language_map.get(language.lower(), language)
user_prompt = f"Generate an expressive text sample in {language_name} for voice cloning."
try:
stream = await openai_client.chat.completions.create(
model=settings.OPENAI_MODEL,
messages=[
{"role": "system", "content": self.VOICE_TEXT_SYSTEM_PROMPT},
{"role": "user", "content": user_prompt}
],
temperature=0.9, # Higher temperature for more creativity
max_tokens=200,
stream=True
)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
yield chunk.choices[0].delta.content
except Exception as e:
# In streaming mode, we yield an error marker
error_message = f"[ERROR] Failed to generate text: {str(e)}"
yield f"\n\n{error_message}"
raise
async def optimize_instruction_stream(
self,
openai_client: AsyncOpenAI,
original_instruction: str
) -> AsyncGenerator[str, None]:
"""
Optimize agent instruction with streaming
Args:
openai_client: OpenAI client instance
original_instruction: Original instruction text from user
Yields:
Optimized instruction chunks as they are generated
Raises:
Exception: If OpenAI API call fails
"""
user_prompt = f"""Optimize this agent instruction:
Original instruction:
{original_instruction}
Provide an improved, professional version."""
try:
stream = await openai_client.chat.completions.create(
model=settings.OPENAI_MODEL,
messages=[
{"role": "system", "content": self.INSTRUCTION_OPTIMIZATION_SYSTEM_PROMPT},
{"role": "user", "content": user_prompt}
],
temperature=0.7, # Balanced creativity and consistency
max_tokens=500,
stream=True
)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
yield chunk.choices[0].delta.content
except Exception as e:
# In streaming mode, we yield an error marker
error_message = f"[ERROR] Failed to optimize instruction: {str(e)}"
yield f"\n\n{error_message}"
raise
# Singleton instance
llm_service = LLMService()

View file

@ -455,6 +455,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/19/8f/92bdd27b067204b99f396a1414d6342122f3e2663459baf787108a6b8b84/coverage-7.11.3-py3-none-any.whl", hash = "sha256:351511ae28e2509c8d8cae5311577ea7dd511ab8e746ffc8814a0896c3d33fbe", size = 208478, upload-time = "2025-11-10T00:13:14.908Z" },
]
[[package]]
name = "distro"
version = "1.9.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/fc/f8/98eea607f65de6527f8a2e8885fc8015d3e6f5775df186e443e0964a11c3/distro-1.9.0.tar.gz", hash = "sha256:2fa77c6fd8940f116ee1d6b94a2f90b13b5ea8d019b98bc8bafdcabcdd9bdbed", size = 60722, upload-time = "2023-12-24T09:54:32.31Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277, upload-time = "2023-12-24T09:54:30.421Z" },
]
[[package]]
name = "fastapi"
version = "0.121.2"
@ -712,6 +721,74 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },
]
[[package]]
name = "jiter"
version = "0.12.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/45/9d/e0660989c1370e25848bb4c52d061c71837239738ad937e83edca174c273/jiter-0.12.0.tar.gz", hash = "sha256:64dfcd7d5c168b38d3f9f8bba7fc639edb3418abcc74f22fdbe6b8938293f30b", size = 168294, upload-time = "2025-11-09T20:49:23.302Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/92/c9/5b9f7b4983f1b542c64e84165075335e8a236fa9e2ea03a0c79780062be8/jiter-0.12.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:305e061fa82f4680607a775b2e8e0bcb071cd2205ac38e6ef48c8dd5ebe1cf37", size = 314449, upload-time = "2025-11-09T20:47:22.999Z" },
{ url = "https://files.pythonhosted.org/packages/98/6e/e8efa0e78de00db0aee82c0cf9e8b3f2027efd7f8a71f859d8f4be8e98ef/jiter-0.12.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:5c1860627048e302a528333c9307c818c547f214d8659b0705d2195e1a94b274", size = 319855, upload-time = "2025-11-09T20:47:24.779Z" },
{ url = "https://files.pythonhosted.org/packages/20/26/894cd88e60b5d58af53bec5c6759d1292bd0b37a8b5f60f07abf7a63ae5f/jiter-0.12.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:df37577a4f8408f7e0ec3205d2a8f87672af8f17008358063a4d6425b6081ce3", size = 350171, upload-time = "2025-11-09T20:47:26.469Z" },
{ url = "https://files.pythonhosted.org/packages/f5/27/a7b818b9979ac31b3763d25f3653ec3a954044d5e9f5d87f2f247d679fd1/jiter-0.12.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:75fdd787356c1c13a4f40b43c2156276ef7a71eb487d98472476476d803fb2cf", size = 365590, upload-time = "2025-11-09T20:47:27.918Z" },
{ url = "https://files.pythonhosted.org/packages/ba/7e/e46195801a97673a83746170b17984aa8ac4a455746354516d02ca5541b4/jiter-0.12.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1eb5db8d9c65b112aacf14fcd0faae9913d07a8afea5ed06ccdd12b724e966a1", size = 479462, upload-time = "2025-11-09T20:47:29.654Z" },
{ url = "https://files.pythonhosted.org/packages/ca/75/f833bfb009ab4bd11b1c9406d333e3b4357709ed0570bb48c7c06d78c7dd/jiter-0.12.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:73c568cc27c473f82480abc15d1301adf333a7ea4f2e813d6a2c7d8b6ba8d0df", size = 378983, upload-time = "2025-11-09T20:47:31.026Z" },
{ url = "https://files.pythonhosted.org/packages/71/b3/7a69d77943cc837d30165643db753471aff5df39692d598da880a6e51c24/jiter-0.12.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4321e8a3d868919bcb1abb1db550d41f2b5b326f72df29e53b2df8b006eb9403", size = 361328, upload-time = "2025-11-09T20:47:33.286Z" },
{ url = "https://files.pythonhosted.org/packages/b0/ac/a78f90caf48d65ba70d8c6efc6f23150bc39dc3389d65bbec2a95c7bc628/jiter-0.12.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:0a51bad79f8cc9cac2b4b705039f814049142e0050f30d91695a2d9a6611f126", size = 386740, upload-time = "2025-11-09T20:47:34.703Z" },
{ url = "https://files.pythonhosted.org/packages/39/b6/5d31c2cc8e1b6a6bcf3c5721e4ca0a3633d1ab4754b09bc7084f6c4f5327/jiter-0.12.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:2a67b678f6a5f1dd6c36d642d7db83e456bc8b104788262aaefc11a22339f5a9", size = 520875, upload-time = "2025-11-09T20:47:36.058Z" },
{ url = "https://files.pythonhosted.org/packages/30/b5/4df540fae4e9f68c54b8dab004bd8c943a752f0b00efd6e7d64aa3850339/jiter-0.12.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:efe1a211fe1fd14762adea941e3cfd6c611a136e28da6c39272dbb7a1bbe6a86", size = 511457, upload-time = "2025-11-09T20:47:37.932Z" },
{ url = "https://files.pythonhosted.org/packages/07/65/86b74010e450a1a77b2c1aabb91d4a91dd3cd5afce99f34d75fd1ac64b19/jiter-0.12.0-cp312-cp312-win32.whl", hash = "sha256:d779d97c834b4278276ec703dc3fc1735fca50af63eb7262f05bdb4e62203d44", size = 204546, upload-time = "2025-11-09T20:47:40.47Z" },
{ url = "https://files.pythonhosted.org/packages/1c/c7/6659f537f9562d963488e3e55573498a442503ced01f7e169e96a6110383/jiter-0.12.0-cp312-cp312-win_amd64.whl", hash = "sha256:e8269062060212b373316fe69236096aaf4c49022d267c6736eebd66bbbc60bb", size = 205196, upload-time = "2025-11-09T20:47:41.794Z" },
{ url = "https://files.pythonhosted.org/packages/21/f4/935304f5169edadfec7f9c01eacbce4c90bb9a82035ac1de1f3bd2d40be6/jiter-0.12.0-cp312-cp312-win_arm64.whl", hash = "sha256:06cb970936c65de926d648af0ed3d21857f026b1cf5525cb2947aa5e01e05789", size = 186100, upload-time = "2025-11-09T20:47:43.007Z" },
{ url = "https://files.pythonhosted.org/packages/3d/a6/97209693b177716e22576ee1161674d1d58029eb178e01866a0422b69224/jiter-0.12.0-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:6cc49d5130a14b732e0612bc76ae8db3b49898732223ef8b7599aa8d9810683e", size = 313658, upload-time = "2025-11-09T20:47:44.424Z" },
{ url = "https://files.pythonhosted.org/packages/06/4d/125c5c1537c7d8ee73ad3d530a442d6c619714b95027143f1b61c0b4dfe0/jiter-0.12.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:37f27a32ce36364d2fa4f7fdc507279db604d27d239ea2e044c8f148410defe1", size = 318605, upload-time = "2025-11-09T20:47:45.973Z" },
{ url = "https://files.pythonhosted.org/packages/99/bf/a840b89847885064c41a5f52de6e312e91fa84a520848ee56c97e4fa0205/jiter-0.12.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bbc0944aa3d4b4773e348cda635252824a78f4ba44328e042ef1ff3f6080d1cf", size = 349803, upload-time = "2025-11-09T20:47:47.535Z" },
{ url = "https://files.pythonhosted.org/packages/8a/88/e63441c28e0db50e305ae23e19c1d8fae012d78ed55365da392c1f34b09c/jiter-0.12.0-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:da25c62d4ee1ffbacb97fac6dfe4dcd6759ebdc9015991e92a6eae5816287f44", size = 365120, upload-time = "2025-11-09T20:47:49.284Z" },
{ url = "https://files.pythonhosted.org/packages/0a/7c/49b02714af4343970eb8aca63396bc1c82fa01197dbb1e9b0d274b550d4e/jiter-0.12.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:048485c654b838140b007390b8182ba9774621103bd4d77c9c3f6f117474ba45", size = 479918, upload-time = "2025-11-09T20:47:50.807Z" },
{ url = "https://files.pythonhosted.org/packages/69/ba/0a809817fdd5a1db80490b9150645f3aae16afad166960bcd562be194f3b/jiter-0.12.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:635e737fbb7315bef0037c19b88b799143d2d7d3507e61a76751025226b3ac87", size = 379008, upload-time = "2025-11-09T20:47:52.211Z" },
{ url = "https://files.pythonhosted.org/packages/5f/c3/c9fc0232e736c8877d9e6d83d6eeb0ba4e90c6c073835cc2e8f73fdeef51/jiter-0.12.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4e017c417b1ebda911bd13b1e40612704b1f5420e30695112efdbed8a4b389ed", size = 361785, upload-time = "2025-11-09T20:47:53.512Z" },
{ url = "https://files.pythonhosted.org/packages/96/61/61f69b7e442e97ca6cd53086ddc1cf59fb830549bc72c0a293713a60c525/jiter-0.12.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:89b0bfb8b2bf2351fba36bb211ef8bfceba73ef58e7f0c68fb67b5a2795ca2f9", size = 386108, upload-time = "2025-11-09T20:47:54.893Z" },
{ url = "https://files.pythonhosted.org/packages/e9/2e/76bb3332f28550c8f1eba3bf6e5efe211efda0ddbbaf24976bc7078d42a5/jiter-0.12.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:f5aa5427a629a824a543672778c9ce0c5e556550d1569bb6ea28a85015287626", size = 519937, upload-time = "2025-11-09T20:47:56.253Z" },
{ url = "https://files.pythonhosted.org/packages/84/d6/fa96efa87dc8bff2094fb947f51f66368fa56d8d4fc9e77b25d7fbb23375/jiter-0.12.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:ed53b3d6acbcb0fd0b90f20c7cb3b24c357fe82a3518934d4edfa8c6898e498c", size = 510853, upload-time = "2025-11-09T20:47:58.32Z" },
{ url = "https://files.pythonhosted.org/packages/8a/28/93f67fdb4d5904a708119a6ab58a8f1ec226ff10a94a282e0215402a8462/jiter-0.12.0-cp313-cp313-win32.whl", hash = "sha256:4747de73d6b8c78f2e253a2787930f4fffc68da7fa319739f57437f95963c4de", size = 204699, upload-time = "2025-11-09T20:47:59.686Z" },
{ url = "https://files.pythonhosted.org/packages/c4/1f/30b0eb087045a0abe2a5c9c0c0c8da110875a1d3be83afd4a9a4e548be3c/jiter-0.12.0-cp313-cp313-win_amd64.whl", hash = "sha256:e25012eb0c456fcc13354255d0338cd5397cce26c77b2832b3c4e2e255ea5d9a", size = 204258, upload-time = "2025-11-09T20:48:01.01Z" },
{ url = "https://files.pythonhosted.org/packages/2c/f4/2b4daf99b96bce6fc47971890b14b2a36aef88d7beb9f057fafa032c6141/jiter-0.12.0-cp313-cp313-win_arm64.whl", hash = "sha256:c97b92c54fe6110138c872add030a1f99aea2401ddcdaa21edf74705a646dd60", size = 185503, upload-time = "2025-11-09T20:48:02.35Z" },
{ url = "https://files.pythonhosted.org/packages/39/ca/67bb15a7061d6fe20b9b2a2fd783e296a1e0f93468252c093481a2f00efa/jiter-0.12.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:53839b35a38f56b8be26a7851a48b89bc47e5d88e900929df10ed93b95fea3d6", size = 317965, upload-time = "2025-11-09T20:48:03.783Z" },
{ url = "https://files.pythonhosted.org/packages/18/af/1788031cd22e29c3b14bc6ca80b16a39a0b10e611367ffd480c06a259831/jiter-0.12.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:94f669548e55c91ab47fef8bddd9c954dab1938644e715ea49d7e117015110a4", size = 345831, upload-time = "2025-11-09T20:48:05.55Z" },
{ url = "https://files.pythonhosted.org/packages/05/17/710bf8472d1dff0d3caf4ced6031060091c1320f84ee7d5dcbed1f352417/jiter-0.12.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:351d54f2b09a41600ffea43d081522d792e81dcfb915f6d2d242744c1cc48beb", size = 361272, upload-time = "2025-11-09T20:48:06.951Z" },
{ url = "https://files.pythonhosted.org/packages/fb/f1/1dcc4618b59761fef92d10bcbb0b038b5160be653b003651566a185f1a5c/jiter-0.12.0-cp313-cp313t-win_amd64.whl", hash = "sha256:2a5e90604620f94bf62264e7c2c038704d38217b7465b863896c6d7c902b06c7", size = 204604, upload-time = "2025-11-09T20:48:08.328Z" },
{ url = "https://files.pythonhosted.org/packages/d9/32/63cb1d9f1c5c6632a783c0052cde9ef7ba82688f7065e2f0d5f10a7e3edb/jiter-0.12.0-cp313-cp313t-win_arm64.whl", hash = "sha256:88ef757017e78d2860f96250f9393b7b577b06a956ad102c29c8237554380db3", size = 185628, upload-time = "2025-11-09T20:48:09.572Z" },
{ url = "https://files.pythonhosted.org/packages/a8/99/45c9f0dbe4a1416b2b9a8a6d1236459540f43d7fb8883cff769a8db0612d/jiter-0.12.0-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:c46d927acd09c67a9fb1416df45c5a04c27e83aae969267e98fba35b74e99525", size = 312478, upload-time = "2025-11-09T20:48:10.898Z" },
{ url = "https://files.pythonhosted.org/packages/4c/a7/54ae75613ba9e0f55fcb0bc5d1f807823b5167cc944e9333ff322e9f07dd/jiter-0.12.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:774ff60b27a84a85b27b88cd5583899c59940bcc126caca97eb2a9df6aa00c49", size = 318706, upload-time = "2025-11-09T20:48:12.266Z" },
{ url = "https://files.pythonhosted.org/packages/59/31/2aa241ad2c10774baf6c37f8b8e1f39c07db358f1329f4eb40eba179c2a2/jiter-0.12.0-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c5433fab222fb072237df3f637d01b81f040a07dcac1cb4a5c75c7aa9ed0bef1", size = 351894, upload-time = "2025-11-09T20:48:13.673Z" },
{ url = "https://files.pythonhosted.org/packages/54/4f/0f2759522719133a9042781b18cc94e335b6d290f5e2d3e6899d6af933e3/jiter-0.12.0-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f8c593c6e71c07866ec6bfb790e202a833eeec885022296aff6b9e0b92d6a70e", size = 365714, upload-time = "2025-11-09T20:48:15.083Z" },
{ url = "https://files.pythonhosted.org/packages/dc/6f/806b895f476582c62a2f52c453151edd8a0fde5411b0497baaa41018e878/jiter-0.12.0-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:90d32894d4c6877a87ae00c6b915b609406819dce8bc0d4e962e4de2784e567e", size = 478989, upload-time = "2025-11-09T20:48:16.706Z" },
{ url = "https://files.pythonhosted.org/packages/86/6c/012d894dc6e1033acd8db2b8346add33e413ec1c7c002598915278a37f79/jiter-0.12.0-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:798e46eed9eb10c3adbbacbd3bdb5ecd4cf7064e453d00dbef08802dae6937ff", size = 378615, upload-time = "2025-11-09T20:48:18.614Z" },
{ url = "https://files.pythonhosted.org/packages/87/30/d718d599f6700163e28e2c71c0bbaf6dace692e7df2592fd793ac9276717/jiter-0.12.0-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b3f1368f0a6719ea80013a4eb90ba72e75d7ea67cfc7846db2ca504f3df0169a", size = 364745, upload-time = "2025-11-09T20:48:20.117Z" },
{ url = "https://files.pythonhosted.org/packages/8f/85/315b45ce4b6ddc7d7fceca24068543b02bdc8782942f4ee49d652e2cc89f/jiter-0.12.0-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:65f04a9d0b4406f7e51279710b27484af411896246200e461d80d3ba0caa901a", size = 386502, upload-time = "2025-11-09T20:48:21.543Z" },
{ url = "https://files.pythonhosted.org/packages/74/0b/ce0434fb40c5b24b368fe81b17074d2840748b4952256bab451b72290a49/jiter-0.12.0-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:fd990541982a24281d12b67a335e44f117e4c6cbad3c3b75c7dea68bf4ce3a67", size = 519845, upload-time = "2025-11-09T20:48:22.964Z" },
{ url = "https://files.pythonhosted.org/packages/e8/a3/7a7a4488ba052767846b9c916d208b3ed114e3eb670ee984e4c565b9cf0d/jiter-0.12.0-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:b111b0e9152fa7df870ecaebb0bd30240d9f7fff1f2003bcb4ed0f519941820b", size = 510701, upload-time = "2025-11-09T20:48:24.483Z" },
{ url = "https://files.pythonhosted.org/packages/c3/16/052ffbf9d0467b70af24e30f91e0579e13ded0c17bb4a8eb2aed3cb60131/jiter-0.12.0-cp314-cp314-win32.whl", hash = "sha256:a78befb9cc0a45b5a5a0d537b06f8544c2ebb60d19d02c41ff15da28a9e22d42", size = 205029, upload-time = "2025-11-09T20:48:25.749Z" },
{ url = "https://files.pythonhosted.org/packages/e4/18/3cf1f3f0ccc789f76b9a754bdb7a6977e5d1d671ee97a9e14f7eb728d80e/jiter-0.12.0-cp314-cp314-win_amd64.whl", hash = "sha256:e1fe01c082f6aafbe5c8faf0ff074f38dfb911d53f07ec333ca03f8f6226debf", size = 204960, upload-time = "2025-11-09T20:48:27.415Z" },
{ url = "https://files.pythonhosted.org/packages/02/68/736821e52ecfdeeb0f024b8ab01b5a229f6b9293bbdb444c27efade50b0f/jiter-0.12.0-cp314-cp314-win_arm64.whl", hash = "sha256:d72f3b5a432a4c546ea4bedc84cce0c3404874f1d1676260b9c7f048a9855451", size = 185529, upload-time = "2025-11-09T20:48:29.125Z" },
{ url = "https://files.pythonhosted.org/packages/30/61/12ed8ee7a643cce29ac97c2281f9ce3956eb76b037e88d290f4ed0d41480/jiter-0.12.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e6ded41aeba3603f9728ed2b6196e4df875348ab97b28fc8afff115ed42ba7a7", size = 318974, upload-time = "2025-11-09T20:48:30.87Z" },
{ url = "https://files.pythonhosted.org/packages/2d/c6/f3041ede6d0ed5e0e79ff0de4c8f14f401bbf196f2ef3971cdbe5fd08d1d/jiter-0.12.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a947920902420a6ada6ad51892082521978e9dd44a802663b001436e4b771684", size = 345932, upload-time = "2025-11-09T20:48:32.658Z" },
{ url = "https://files.pythonhosted.org/packages/d5/5d/4d94835889edd01ad0e2dbfc05f7bdfaed46292e7b504a6ac7839aa00edb/jiter-0.12.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:add5e227e0554d3a52cf390a7635edaffdf4f8fce4fdbcef3cc2055bb396a30c", size = 367243, upload-time = "2025-11-09T20:48:34.093Z" },
{ url = "https://files.pythonhosted.org/packages/fd/76/0051b0ac2816253a99d27baf3dda198663aff882fa6ea7deeb94046da24e/jiter-0.12.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3f9b1cda8fcb736250d7e8711d4580ebf004a46771432be0ae4796944b5dfa5d", size = 479315, upload-time = "2025-11-09T20:48:35.507Z" },
{ url = "https://files.pythonhosted.org/packages/70/ae/83f793acd68e5cb24e483f44f482a1a15601848b9b6f199dacb970098f77/jiter-0.12.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:deeb12a2223fe0135c7ff1356a143d57f95bbf1f4a66584f1fc74df21d86b993", size = 380714, upload-time = "2025-11-09T20:48:40.014Z" },
{ url = "https://files.pythonhosted.org/packages/b1/5e/4808a88338ad2c228b1126b93fcd8ba145e919e886fe910d578230dabe3b/jiter-0.12.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c596cc0f4cb574877550ce4ecd51f8037469146addd676d7c1a30ebe6391923f", size = 365168, upload-time = "2025-11-09T20:48:41.462Z" },
{ url = "https://files.pythonhosted.org/packages/0c/d4/04619a9e8095b42aef436b5aeb4c0282b4ff1b27d1db1508df9f5dc82750/jiter-0.12.0-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5ab4c823b216a4aeab3fdbf579c5843165756bd9ad87cc6b1c65919c4715f783", size = 387893, upload-time = "2025-11-09T20:48:42.921Z" },
{ url = "https://files.pythonhosted.org/packages/17/ea/d3c7e62e4546fdc39197fa4a4315a563a89b95b6d54c0d25373842a59cbe/jiter-0.12.0-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:e427eee51149edf962203ff8db75a7514ab89be5cb623fb9cea1f20b54f1107b", size = 520828, upload-time = "2025-11-09T20:48:44.278Z" },
{ url = "https://files.pythonhosted.org/packages/cc/0b/c6d3562a03fd767e31cb119d9041ea7958c3c80cb3d753eafb19b3b18349/jiter-0.12.0-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:edb868841f84c111255ba5e80339d386d937ec1fdce419518ce1bd9370fac5b6", size = 511009, upload-time = "2025-11-09T20:48:45.726Z" },
{ url = "https://files.pythonhosted.org/packages/aa/51/2cb4468b3448a8385ebcd15059d325c9ce67df4e2758d133ab9442b19834/jiter-0.12.0-cp314-cp314t-win32.whl", hash = "sha256:8bbcfe2791dfdb7c5e48baf646d37a6a3dcb5a97a032017741dea9f817dca183", size = 205110, upload-time = "2025-11-09T20:48:47.033Z" },
{ url = "https://files.pythonhosted.org/packages/b2/c5/ae5ec83dec9c2d1af805fd5fe8f74ebded9c8670c5210ec7820ce0dbeb1e/jiter-0.12.0-cp314-cp314t-win_amd64.whl", hash = "sha256:2fa940963bf02e1d8226027ef461e36af472dea85d36054ff835aeed944dd873", size = 205223, upload-time = "2025-11-09T20:48:49.076Z" },
{ url = "https://files.pythonhosted.org/packages/97/9a/3c5391907277f0e55195550cf3fa8e293ae9ee0c00fb402fec1e38c0c82f/jiter-0.12.0-cp314-cp314t-win_arm64.whl", hash = "sha256:506c9708dd29b27288f9f8f1140c3cb0e3d8ddb045956d7757b1fa0e0f39a473", size = 185564, upload-time = "2025-11-09T20:48:50.376Z" },
{ url = "https://files.pythonhosted.org/packages/cb/f5/12efb8ada5f5c9edc1d4555fe383c1fb2eac05ac5859258a72d61981d999/jiter-0.12.0-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:e8547883d7b96ef2e5fe22b88f8a4c8725a56e7f4abafff20fd5272d634c7ecb", size = 309974, upload-time = "2025-11-09T20:49:17.187Z" },
{ url = "https://files.pythonhosted.org/packages/85/15/d6eb3b770f6a0d332675141ab3962fd4a7c270ede3515d9f3583e1d28276/jiter-0.12.0-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:89163163c0934854a668ed783a2546a0617f71706a2551a4a0666d91ab365d6b", size = 304233, upload-time = "2025-11-09T20:49:18.734Z" },
{ url = "https://files.pythonhosted.org/packages/8c/3e/e7e06743294eea2cf02ced6aa0ff2ad237367394e37a0e2b4a1108c67a36/jiter-0.12.0-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d96b264ab7d34bbb2312dedc47ce07cd53f06835eacbc16dde3761f47c3a9e7f", size = 338537, upload-time = "2025-11-09T20:49:20.317Z" },
{ url = "https://files.pythonhosted.org/packages/2f/9c/6753e6522b8d0ef07d3a3d239426669e984fb0eba15a315cdbc1253904e4/jiter-0.12.0-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c24e864cb30ab82311c6425655b0cdab0a98c5d973b065c66a3f020740c2324c", size = 346110, upload-time = "2025-11-09T20:49:21.817Z" },
]
[[package]]
name = "jmespath"
version = "1.0.1"
@ -733,6 +810,7 @@ dependencies = [
{ name = "fastapi" },
{ name = "fish-audio-sdk" },
{ name = "httpx" },
{ name = "openai" },
{ name = "pydantic" },
{ name = "pydantic-settings" },
{ name = "pyjwt" },
@ -762,6 +840,7 @@ requires-dist = [
{ name = "fastapi", specifier = ">=0.115.0" },
{ name = "fish-audio-sdk", specifier = ">=1.1.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "openai", specifier = ">=1.54.0" },
{ name = "pydantic", specifier = ">=2.9.0" },
{ name = "pydantic-settings", specifier = ">=2.6.0" },
{ name = "pyjwt", specifier = ">=2.9.0" },
@ -885,6 +964,25 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" },
]
[[package]]
name = "openai"
version = "2.8.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "anyio" },
{ name = "distro" },
{ name = "httpx" },
{ name = "jiter" },
{ name = "pydantic" },
{ name = "sniffio" },
{ name = "tqdm" },
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/d5/e4/42591e356f1d53c568418dc7e30dcda7be31dd5a4d570bca22acb0525862/openai-2.8.1.tar.gz", hash = "sha256:cb1b79eef6e809f6da326a7ef6038719e35aa944c42d081807bfa1be8060f15f", size = 602490, upload-time = "2025-11-17T22:39:59.549Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/55/4f/dbc0c124c40cb390508a82770fb9f6e3ed162560181a85089191a851c59a/openai-2.8.1-py3-none-any.whl", hash = "sha256:c6c3b5a04994734386e8dad3c00a393f56d3b68a27cd2e8acae91a59e4122463", size = 1022688, upload-time = "2025-11-17T22:39:57.675Z" },
]
[[package]]
name = "ormsgpack"
version = "1.12.0"
@ -1396,6 +1494,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/a3/e0/021c772d6a662f43b63044ab481dc6ac7592447605b5b35a957785363122/starlette-0.49.3-py3-none-any.whl", hash = "sha256:b579b99715fdc2980cf88c8ec96d3bf1ce16f5a8051a7c2b84ef9b1cdecaea2f", size = 74340, upload-time = "2025-11-01T15:12:24.387Z" },
]
[[package]]
name = "tqdm"
version = "4.67.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "colorama", marker = "sys_platform == 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a8/4b/29b4ef32e036bb34e4ab51796dd745cdba7ed47ad142a9f4a1eb8e0c744d/tqdm-4.67.1.tar.gz", hash = "sha256:f8aef9c52c08c13a65f30ea34f4e5aac3fd1a34959879d7e59e63027286627f2", size = 169737, upload-time = "2024-11-24T20:12:22.481Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d0/30/dc54f88dd4a2b5dc8a0279bdd7270e735851848b762aeb1c1184ed1f6b14/tqdm-4.67.1-py3-none-any.whl", hash = "sha256:26445eca388f82e72884e0d580d5464cd801a3ea01e63e5601bdff9ba6a48de2", size = 78540, upload-time = "2024-11-24T20:12:19.698Z" },
]
[[package]]
name = "typing-extensions"
version = "4.15.0"