mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge origin/main into feat_config
This commit is contained in:
commit
da99af4703
37 changed files with 925 additions and 169 deletions
|
|
@ -29,3 +29,18 @@ FISH_API_KEY=your-fish-api-key
|
||||||
OPENAI_API_KEY=your-openai-key
|
OPENAI_API_KEY=your-openai-key
|
||||||
GROQ_API_KEY=your-groq-api-key
|
GROQ_API_KEY=your-groq-api-key
|
||||||
OPENAI_MODEL=
|
OPENAI_MODEL=
|
||||||
|
|
||||||
|
# MemU Configuration
|
||||||
|
MEMU_API_KEY=
|
||||||
|
MEMU_BASE_URL=https://api.memu.so
|
||||||
|
|
||||||
|
# OpenRouter Configuration
|
||||||
|
OPENROUTER_API_KEY=your-openrouter-api-key-here
|
||||||
|
OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
|
||||||
|
QUICK_PERSONA_MODEL=
|
||||||
|
OPTIMIZE_PERSONA_MODEL=
|
||||||
|
|
||||||
|
# Groq Configuration (for STT)
|
||||||
|
GROQ_API_KEY=gsk-your-groq-api-key-here
|
||||||
|
GROQ_BASE_URL=https://api.groq.com/openai/v1
|
||||||
|
GROQ_STT_MODEL=whisper-large-v3-turbo
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
from fastapi import APIRouter
|
from fastapi import APIRouter
|
||||||
from api.v1 import user, templates, agents, voices, internal, files, chat, memories, devices
|
from api.v1 import user, templates, agents, voices, internal, files, chat, memories, devices, stt
|
||||||
|
|
||||||
api_router = APIRouter()
|
api_router = APIRouter()
|
||||||
|
|
||||||
|
|
@ -65,3 +65,10 @@ api_router.include_router(
|
||||||
prefix="/devices",
|
prefix="/devices",
|
||||||
tags=["Devices"]
|
tags=["Devices"]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# STT routes
|
||||||
|
api_router.include_router(
|
||||||
|
stt.router,
|
||||||
|
prefix="/stt",
|
||||||
|
tags=["STT"]
|
||||||
|
)
|
||||||
|
|
|
||||||
|
|
@ -10,10 +10,12 @@ from services.llm_service import llm_service
|
||||||
from utils.response import success_response
|
from utils.response import success_response
|
||||||
from api.auth import get_current_user_id
|
from api.auth import get_current_user_id
|
||||||
from schemas.agent import AgentResponse, BindableAgentResponse, BindableAgentListResponse
|
from schemas.agent import AgentResponse, BindableAgentResponse, BindableAgentListResponse
|
||||||
|
from config import get_logger
|
||||||
import base64
|
import base64
|
||||||
import logging
|
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -201,7 +203,7 @@ async def generate_persona(
|
||||||
avatar_base64 = base64.b64encode(content).decode("utf-8")
|
avatar_base64 = base64.b64encode(content).decode("utf-8")
|
||||||
avatar_media_type = avatar.content_type or "image/jpeg"
|
avatar_media_type = avatar.content_type or "image/jpeg"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.warning(f"Failed to process avatar: {e}")
|
logger.warning(f"Failed to process avatar: {e}")
|
||||||
|
|
||||||
if mode == "optimize":
|
if mode == "optimize":
|
||||||
# Optimize mode: streaming with SSE format, requires existing instruction
|
# Optimize mode: streaming with SSE format, requires existing instruction
|
||||||
|
|
@ -220,7 +222,7 @@ async def generate_persona(
|
||||||
# SSE format: data: <content>\n\n
|
# SSE format: data: <content>\n\n
|
||||||
yield f"data: {chunk}\n\n"
|
yield f"data: {chunk}\n\n"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error(f"Persona optimization failed: {e}")
|
logger.error(f"Persona optimization failed: {e}")
|
||||||
yield f"data: [ERROR] {str(e)}\n\n"
|
yield f"data: [ERROR] {str(e)}\n\n"
|
||||||
|
|
||||||
return StreamingResponse(
|
return StreamingResponse(
|
||||||
|
|
@ -238,6 +240,6 @@ async def generate_persona(
|
||||||
)
|
)
|
||||||
return success_response(data=result)
|
return success_response(data=result)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error(f"Persona generation failed: {e}")
|
logger.error(f"Persona generation failed: {e}")
|
||||||
raise HTTPException(status_code=500, detail=f"Generation failed: {str(e)}")
|
raise HTTPException(status_code=500, detail=f"Generation failed: {str(e)}")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,6 @@ from infra import get_db, get_s3
|
||||||
from services.chat_service import chat_service
|
from services.chat_service import chat_service
|
||||||
from schemas.chat import (
|
from schemas.chat import (
|
||||||
ReportChatMessageRequest,
|
ReportChatMessageRequest,
|
||||||
ChatMessage,
|
|
||||||
ChatMessagesListResponse
|
ChatMessagesListResponse
|
||||||
)
|
)
|
||||||
from utils.response import success_response
|
from utils.response import success_response
|
||||||
|
|
@ -46,7 +45,7 @@ async def report_message(
|
||||||
@router.get("/{agent_id}/messages", summary="Get chat messages for an agent")
|
@router.get("/{agent_id}/messages", summary="Get chat messages for an agent")
|
||||||
async def get_agent_messages(
|
async def get_agent_messages(
|
||||||
agent_id: str,
|
agent_id: str,
|
||||||
cursor: Optional[str] = Query(None, description="Message ID (ULID) cursor for pagination"),
|
cursor: Optional[str] = Query(None, description="Composite cursor (message_time) for pagination"),
|
||||||
limit: int = Query(50, ge=1, le=100, description="Number of messages to fetch"),
|
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"),
|
include_audio: bool = Query(False, description="Load audio base64 from S3"),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
|
|
@ -56,19 +55,19 @@ async def get_agent_messages(
|
||||||
Get chat messages for an agent using cursor-based pagination (chat style)
|
Get chat messages for an agent using cursor-based pagination (chat style)
|
||||||
|
|
||||||
Features:
|
Features:
|
||||||
- Returns latest messages first (DESC order, newest at top)
|
- Returns latest messages first (DESC order by message_time, newest at top)
|
||||||
- Scroll up to load older messages (typical chat UI behavior)
|
- Scroll up to load older messages (typical chat UI behavior)
|
||||||
- Cursor-based pagination for efficient real-time chat
|
- Cursor-based pagination using message_time for correct ordering
|
||||||
- Lazy audio loading (only when include_audio=True)
|
- Lazy audio loading (only when include_audio=True)
|
||||||
|
|
||||||
Query Parameters:
|
Query Parameters:
|
||||||
- cursor: Message ID (ULID) to load messages before. If None, load latest messages
|
- cursor: ISO format timestamp to load messages before. If None, load latest messages
|
||||||
- limit: Number of messages to fetch (1-100, default 50)
|
- limit: Number of messages to fetch (1-100, default 50)
|
||||||
- include_audio: If True, downloads opus from S3 and returns as base64
|
- include_audio: If True, downloads opus from S3 and returns as base64
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
- messages: List of chat messages (newest first in each batch)
|
- messages: List of chat messages (newest first in each batch, ordered by message_time)
|
||||||
- next_cursor: Message ID for loading older messages (None if no more history)
|
- next_cursor: ISO timestamp for loading older messages (None if no more history)
|
||||||
- has_more: Whether there are more older messages
|
- has_more: Whether there are more older messages
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
@ -76,15 +75,15 @@ async def get_agent_messages(
|
||||||
GET /chat/agent_123/messages?limit=50
|
GET /chat/agent_123/messages?limit=50
|
||||||
Response: {
|
Response: {
|
||||||
messages: [newest_msg, ..., oldest_msg_in_batch],
|
messages: [newest_msg, ..., oldest_msg_in_batch],
|
||||||
next_cursor: "01JD8X0000ABC", # ID of oldest message in this batch
|
next_cursor: "2024-01-15T10:30:00+00:00",
|
||||||
has_more: true
|
has_more: true
|
||||||
}
|
}
|
||||||
|
|
||||||
# Scroll up - load older messages before cursor
|
# Scroll up - load older messages before cursor
|
||||||
GET /chat/agent_123/messages?cursor=01JD8X0000ABC&limit=50
|
GET /chat/agent_123/messages?cursor=2024-01-15T10:30:00%2B00:00&limit=50
|
||||||
Response: {
|
Response: {
|
||||||
messages: [newer_old_msg, ..., older_msg],
|
messages: [newer_old_msg, ..., older_msg],
|
||||||
next_cursor: "01JD8W0000XYZ",
|
next_cursor: "2024-01-15T09:15:00+00:00",
|
||||||
has_more: true
|
has_more: true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
83
main/live-agent-api/api/v1/stt.py
Normal file
83
main/live-agent-api/api/v1/stt.py
Normal file
|
|
@ -0,0 +1,83 @@
|
||||||
|
"""
|
||||||
|
STT (Speech-to-Text) API endpoints
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, File, UploadFile, Depends, HTTPException
|
||||||
|
|
||||||
|
from infra import get_groq
|
||||||
|
from services.stt_service import stt_service
|
||||||
|
from utils.response import success_response
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/transcribe", summary="Transcribe audio to text")
|
||||||
|
async def transcribe(
|
||||||
|
audio: UploadFile = File(..., description="Audio file to transcribe (wav, mp3, opus, flac, etc.)"),
|
||||||
|
groq_client = Depends(get_groq)
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
Transcribe audio file to text using Groq Whisper
|
||||||
|
|
||||||
|
Supported audio formats:
|
||||||
|
- wav, mp3, opus, flac, m4a, webm, and more
|
||||||
|
|
||||||
|
Form Data:
|
||||||
|
- audio: Audio file to transcribe (required)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- text: Transcribed text
|
||||||
|
- language: Detected language code (e.g., 'en', 'zh')
|
||||||
|
- duration: Audio duration in seconds
|
||||||
|
|
||||||
|
Example:
|
||||||
|
POST /api/live_agent/v1/stt/transcribe
|
||||||
|
Form Data:
|
||||||
|
audio: [audio file binary data]
|
||||||
|
|
||||||
|
Response:
|
||||||
|
{
|
||||||
|
"code": 200,
|
||||||
|
"message": "success",
|
||||||
|
"data": {
|
||||||
|
"transcription": "Hello, this is a test."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
# Validate audio file
|
||||||
|
if not audio.filename:
|
||||||
|
raise HTTPException(status_code=400, detail="No audio file provided")
|
||||||
|
|
||||||
|
# Supported audio formats (Whisper supports many formats)
|
||||||
|
supported_formats = {
|
||||||
|
"audio/mpeg", "audio/mp3", "audio/wav", "audio/wave",
|
||||||
|
"audio/ogg", "audio/opus", "audio/flac", "audio/m4a",
|
||||||
|
"audio/webm", "audio/x-wav", "audio/x-m4a"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check content type if available
|
||||||
|
if audio.content_type and audio.content_type not in supported_formats:
|
||||||
|
# Still allow processing if extension looks valid
|
||||||
|
allowed_extensions = {".mp3", ".wav", ".opus", ".flac", ".m4a", ".webm", ".ogg"}
|
||||||
|
file_ext = "." + audio.filename.split(".")[-1].lower() if "." in audio.filename else ""
|
||||||
|
if file_ext not in allowed_extensions:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Unsupported audio format: {audio.content_type}. Supported: {', '.join(allowed_extensions)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Transcribe audio
|
||||||
|
text = await stt_service.transcribe(
|
||||||
|
groq_client=groq_client,
|
||||||
|
audio_file=audio
|
||||||
|
)
|
||||||
|
|
||||||
|
return success_response(
|
||||||
|
data={
|
||||||
|
"trancription": text,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
|
|
@ -1,5 +1,4 @@
|
||||||
from typing import Optional, List
|
from typing import Optional, List
|
||||||
from botocore.args import logger
|
|
||||||
from fastapi import APIRouter, Depends, Query, Form, File, UploadFile
|
from fastapi import APIRouter, Depends, Query, Form, File, UploadFile
|
||||||
from fastapi.responses import StreamingResponse
|
from fastapi.responses import StreamingResponse
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
@ -19,13 +18,11 @@ from schemas.voice import (
|
||||||
)
|
)
|
||||||
from utils.response import success_response
|
from utils.response import success_response
|
||||||
from api.auth import get_current_user_id
|
from api.auth import get_current_user_id
|
||||||
|
from config import get_logger
|
||||||
|
|
||||||
import logging
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
logging.getLogger(__name__)
|
|
||||||
|
|
||||||
@router.get("/discover", summary="Get Discover Voices")
|
@router.get("/discover", summary="Get Discover Voices")
|
||||||
async def get_discover_voices(
|
async def get_discover_voices(
|
||||||
title: Optional[str] = Query(None, description="Filter by voice title/name"),
|
title: Optional[str] = Query(None, description="Filter by voice title/name"),
|
||||||
|
|
@ -304,8 +301,7 @@ async def generate_voice_sample_text(
|
||||||
yield chunk
|
yield chunk
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Error already yielded in service, just log
|
# Error already yielded in service, just log
|
||||||
import logging
|
logger.error(f"Voice sample text generation failed: {e}")
|
||||||
logging.error(f"Voice sample text generation failed: {e}")
|
|
||||||
|
|
||||||
return StreamingResponse(
|
return StreamingResponse(
|
||||||
text_generator(),
|
text_generator(),
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
from .settings import Settings, settings
|
from .settings import Settings, settings
|
||||||
|
from .logger import setup_logging, get_logger
|
||||||
|
|
||||||
__all__ = ["Settings", "settings"]
|
__all__ = ["Settings", "settings", "setup_logging", "get_logger"]
|
||||||
|
|
||||||
|
|
|
||||||
109
main/live-agent-api/config/logger.py
Normal file
109
main/live-agent-api/config/logger.py
Normal file
|
|
@ -0,0 +1,109 @@
|
||||||
|
"""Loguru logger configuration for Live Agent API"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
API_VERSION = "0.1.0"
|
||||||
|
_logger_initialized = False
|
||||||
|
|
||||||
|
|
||||||
|
def setup_logging(
|
||||||
|
log_level: str = "INFO",
|
||||||
|
log_dir: str = "logs",
|
||||||
|
log_file: str = "api.log",
|
||||||
|
enable_file_logging: bool = True
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Setup global loguru logger configuration
|
||||||
|
|
||||||
|
Args:
|
||||||
|
log_level: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
|
||||||
|
log_dir: Directory to store log files
|
||||||
|
log_file: Log file name
|
||||||
|
enable_file_logging: Whether to enable file logging
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Configured logger instance
|
||||||
|
"""
|
||||||
|
global _logger_initialized
|
||||||
|
|
||||||
|
if _logger_initialized:
|
||||||
|
return logger
|
||||||
|
|
||||||
|
# Console log format with colors
|
||||||
|
console_format = (
|
||||||
|
"<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
|
||||||
|
"<level>{level: <8}</level> | "
|
||||||
|
"<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
|
||||||
|
"<level>{message}</level>"
|
||||||
|
)
|
||||||
|
|
||||||
|
# File log format without colors
|
||||||
|
file_format = (
|
||||||
|
"{time:YYYY-MM-DD HH:mm:ss.SSS} | "
|
||||||
|
"{level: <8} | "
|
||||||
|
"{name}:{function}:{line} | "
|
||||||
|
"{message}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Remove default logger
|
||||||
|
logger.remove()
|
||||||
|
|
||||||
|
# Add console handler
|
||||||
|
logger.add(
|
||||||
|
sys.stdout,
|
||||||
|
format=console_format,
|
||||||
|
level=log_level,
|
||||||
|
colorize=True,
|
||||||
|
backtrace=True,
|
||||||
|
diagnose=True
|
||||||
|
)
|
||||||
|
|
||||||
|
# Add file handler if enabled
|
||||||
|
if enable_file_logging:
|
||||||
|
os.makedirs(log_dir, exist_ok=True)
|
||||||
|
log_file_path = os.path.join(log_dir, log_file)
|
||||||
|
|
||||||
|
logger.add(
|
||||||
|
log_file_path,
|
||||||
|
format=file_format,
|
||||||
|
level=log_level,
|
||||||
|
rotation="50 MB", # Rotate when file reaches 50MB
|
||||||
|
retention="7 days", # Keep logs for 7 days
|
||||||
|
compression="zip", # Compress rotated logs
|
||||||
|
encoding="utf-8",
|
||||||
|
enqueue=True, # Async-safe
|
||||||
|
backtrace=True,
|
||||||
|
diagnose=True
|
||||||
|
)
|
||||||
|
|
||||||
|
_logger_initialized = True
|
||||||
|
logger.info(f"Logger initialized - Level: {log_level}, File logging: {enable_file_logging}")
|
||||||
|
|
||||||
|
return logger
|
||||||
|
|
||||||
|
|
||||||
|
def get_logger(name: str = None):
|
||||||
|
"""
|
||||||
|
Get a logger instance with optional name binding
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
from config.logger import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
logger.info("This is an info message")
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name: Optional name to bind to logger (typically __name__)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Logger instance
|
||||||
|
"""
|
||||||
|
if not _logger_initialized:
|
||||||
|
setup_logging()
|
||||||
|
|
||||||
|
if name:
|
||||||
|
return logger.bind(module=name)
|
||||||
|
|
||||||
|
return logger
|
||||||
|
|
||||||
|
|
@ -44,6 +44,11 @@ class Settings(BaseSettings):
|
||||||
QUICK_PERSONA_MODEL: str = "google/gemini-2.5-flash"
|
QUICK_PERSONA_MODEL: str = "google/gemini-2.5-flash"
|
||||||
OPTIMIZE_PERSONA_MODEL: str = "google/gemini-3-pro-preview"
|
OPTIMIZE_PERSONA_MODEL: str = "google/gemini-3-pro-preview"
|
||||||
|
|
||||||
|
# Groq Configuration (for STT)
|
||||||
|
GROQ_API_KEY: str
|
||||||
|
GROQ_BASE_URL: str = "https://api.groq.com/openai/v1"
|
||||||
|
GROQ_STT_MODEL: str = "whisper-large-v3"
|
||||||
|
|
||||||
model_config = SettingsConfigDict(
|
model_config = SettingsConfigDict(
|
||||||
env_file=".env",
|
env_file=".env",
|
||||||
env_file_encoding="utf-8",
|
env_file_encoding="utf-8",
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,11 @@ from .openai import (
|
||||||
init_openai,
|
init_openai,
|
||||||
close_openai,
|
close_openai,
|
||||||
)
|
)
|
||||||
|
from .groq import (
|
||||||
|
get_groq,
|
||||||
|
init_groq,
|
||||||
|
close_groq,
|
||||||
|
)
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
# Database
|
# Database
|
||||||
|
|
@ -48,5 +53,9 @@ __all__ = [
|
||||||
"get_openai",
|
"get_openai",
|
||||||
"init_openai",
|
"init_openai",
|
||||||
"close_openai",
|
"close_openai",
|
||||||
|
# Groq
|
||||||
|
"get_groq",
|
||||||
|
"init_groq",
|
||||||
|
"close_groq",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
|
||||||
31
main/live-agent-api/infra/groq.py
Normal file
31
main/live-agent-api/infra/groq.py
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
"""Groq client infrastructure for STT"""
|
||||||
|
from openai import AsyncOpenAI
|
||||||
|
from config import settings
|
||||||
|
|
||||||
|
# Global Groq client instance (using OpenAI SDK with Groq base URL)
|
||||||
|
_groq_client: AsyncOpenAI | None = None
|
||||||
|
|
||||||
|
|
||||||
|
async def init_groq():
|
||||||
|
"""Initialize Groq client"""
|
||||||
|
global _groq_client
|
||||||
|
_groq_client = AsyncOpenAI(
|
||||||
|
api_key=settings.GROQ_API_KEY,
|
||||||
|
base_url=settings.GROQ_BASE_URL
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def close_groq():
|
||||||
|
"""Close Groq client"""
|
||||||
|
global _groq_client
|
||||||
|
if _groq_client:
|
||||||
|
await _groq_client.close()
|
||||||
|
_groq_client = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_groq() -> AsyncOpenAI:
|
||||||
|
"""Get Groq client instance (dependency injection)"""
|
||||||
|
if _groq_client is None:
|
||||||
|
raise RuntimeError("Groq client not initialized")
|
||||||
|
return _groq_client
|
||||||
|
|
||||||
|
|
@ -123,6 +123,7 @@ CREATE TABLE IF NOT EXISTS chat_messages (
|
||||||
agent_id VARCHAR(50) NOT NULL,
|
agent_id VARCHAR(50) NOT NULL,
|
||||||
role SMALLINT NOT NULL CHECK (role IN (1, 2)),
|
role SMALLINT NOT NULL CHECK (role IN (1, 2)),
|
||||||
content JSONB NOT NULL,
|
content JSONB NOT NULL,
|
||||||
|
message_time TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
|
created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'),
|
||||||
CONSTRAINT fk_chat_messages_agent FOREIGN KEY (agent_id)
|
CONSTRAINT fk_chat_messages_agent FOREIGN KEY (agent_id)
|
||||||
REFERENCES agents(agent_id) ON DELETE CASCADE
|
REFERENCES agents(agent_id) ON DELETE CASCADE
|
||||||
|
|
@ -135,6 +136,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_chat_messages_message_id ON chat_messages(
|
||||||
CREATE INDEX IF NOT EXISTS idx_chat_messages_agent_id ON chat_messages(agent_id);
|
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)
|
-- 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);
|
CREATE INDEX IF NOT EXISTS idx_chat_messages_agent_message_composite ON chat_messages(agent_id, message_id);
|
||||||
|
-- Composite index for message_time based pagination (agent_id + message_time for correct ordering)
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_chat_messages_agent_message_time ON chat_messages(agent_id, message_time);
|
||||||
-- GIN index for JSONB content search (future feature: search by message type, content, etc.)
|
-- 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);
|
CREATE INDEX IF NOT EXISTS idx_chat_messages_content_gin ON chat_messages USING GIN (content);
|
||||||
|
|
||||||
|
|
@ -144,7 +147,8 @@ COMMENT ON COLUMN chat_messages.message_id IS 'External unique identifier (ULID)
|
||||||
COMMENT ON COLUMN chat_messages.agent_id IS 'Agent ID this message belongs to';
|
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.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.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)';
|
COMMENT ON COLUMN chat_messages.message_time IS 'When message actually occurred (for correct ordering)';
|
||||||
|
COMMENT ON COLUMN chat_messages.created_at IS 'When message was stored in database (UTC)';
|
||||||
|
|
||||||
-- ==================== Table: devices ====================
|
-- ==================== Table: devices ====================
|
||||||
-- Device registry table
|
-- Device registry table
|
||||||
|
|
|
||||||
|
|
@ -3,38 +3,64 @@ from fastapi import FastAPI, Request
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
from config import settings
|
from config import settings, setup_logging, get_logger
|
||||||
from infra import init_db, close_db, init_s3, close_s3, init_fish_audio, close_fish_audio, init_openai, close_openai
|
from infra import init_db, close_db, init_s3, close_s3, init_fish_audio, close_fish_audio, init_openai, close_openai, init_groq, close_groq
|
||||||
from api.v1 import api_router
|
from api.v1 import api_router
|
||||||
from utils.exceptions import APIException
|
from utils.exceptions import APIException
|
||||||
|
|
||||||
|
# Initialize logger at application startup
|
||||||
|
setup_logging(
|
||||||
|
log_level="INFO" if not settings.DEBUG else "DEBUG",
|
||||||
|
log_dir="logs",
|
||||||
|
log_file="api.log",
|
||||||
|
enable_file_logging=True
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# Configure logging at application startup
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||||
|
handlers=[
|
||||||
|
logging.StreamHandler(sys.stdout)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
"""Application lifespan events"""
|
"""Application lifespan events"""
|
||||||
# Startup
|
# Startup
|
||||||
print("Starting up Live Agent API...")
|
logger.info("Starting up Live Agent API...")
|
||||||
await init_db()
|
await init_db()
|
||||||
print("Database initialized")
|
logger.info("Database initialized")
|
||||||
await init_s3()
|
await init_s3()
|
||||||
print("S3 connection initialized")
|
logger.info("S3 connection initialized")
|
||||||
await init_fish_audio()
|
await init_fish_audio()
|
||||||
print("Fish Audio client initialized")
|
logger.info("Fish Audio client initialized")
|
||||||
await init_openai()
|
await init_openai()
|
||||||
print("OpenAI client initialized")
|
logger.info("OpenAI client initialized")
|
||||||
|
await init_groq()
|
||||||
|
logger.info("Groq client initialized")
|
||||||
|
|
||||||
yield
|
yield
|
||||||
|
|
||||||
# Shutdown
|
# Shutdown
|
||||||
print("Shutting down Live Agent API...")
|
logger.info("Shutting down Live Agent API...")
|
||||||
await close_db()
|
await close_db()
|
||||||
print("Database connections closed")
|
logger.info("Database connections closed")
|
||||||
await close_s3()
|
await close_s3()
|
||||||
print("S3 connections closed")
|
logger.info("S3 connections closed")
|
||||||
await close_fish_audio()
|
await close_fish_audio()
|
||||||
print("Fish Audio client closed")
|
logger.info("Fish Audio client closed")
|
||||||
await close_openai()
|
await close_openai()
|
||||||
print("OpenAI client closed")
|
logger.info("OpenAI client closed")
|
||||||
|
await close_groq()
|
||||||
|
logger.info("Groq client closed")
|
||||||
|
|
||||||
|
|
||||||
# Create FastAPI application
|
# Create FastAPI application
|
||||||
|
|
|
||||||
26
main/live-agent-api/migrations/add_message_time.sql
Normal file
26
main/live-agent-api/migrations/add_message_time.sql
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
-- Migration: Add message_time column to chat_messages table
|
||||||
|
-- Purpose: Support correct message ordering based on when message actually occurred
|
||||||
|
|
||||||
|
-- Step 1: Add message_time column (nullable first for existing data)
|
||||||
|
ALTER TABLE chat_messages
|
||||||
|
ADD COLUMN IF NOT EXISTS message_time TIMESTAMPTZ;
|
||||||
|
|
||||||
|
-- Step 2: Backfill existing data - use created_at as message_time for historical records
|
||||||
|
UPDATE chat_messages
|
||||||
|
SET message_time = created_at
|
||||||
|
WHERE message_time IS NULL;
|
||||||
|
|
||||||
|
-- Step 3: Set NOT NULL constraint and default value
|
||||||
|
ALTER TABLE chat_messages
|
||||||
|
ALTER COLUMN message_time SET NOT NULL,
|
||||||
|
ALTER COLUMN message_time SET DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC');
|
||||||
|
|
||||||
|
-- Step 4: Create index for efficient ordering queries
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_chat_messages_agent_message_time
|
||||||
|
ON chat_messages(agent_id, message_time);
|
||||||
|
|
||||||
|
-- Step 5: Add column comment
|
||||||
|
COMMENT ON COLUMN chat_messages.message_time IS 'When message actually occurred (for correct ordering)';
|
||||||
|
|
||||||
|
-- Migration completed
|
||||||
|
|
||||||
|
|
@ -20,6 +20,7 @@ dependencies = [
|
||||||
"pyjwt>=2.9.0",
|
"pyjwt>=2.9.0",
|
||||||
"fish-audio-sdk>=1.1.0",
|
"fish-audio-sdk>=1.1.0",
|
||||||
"openai>=1.54.0",
|
"openai>=1.54.0",
|
||||||
|
"loguru>=0.7.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
|
|
|
||||||
|
|
@ -234,16 +234,17 @@ class Agent:
|
||||||
latest_message_content, latest_message_time, sort_time)
|
latest_message_content, latest_message_time, sort_time)
|
||||||
"""
|
"""
|
||||||
# Subquery: get latest message per agent using DISTINCT ON
|
# Subquery: get latest message per agent using DISTINCT ON
|
||||||
|
# Use message_time for ordering (when message actually occurred)
|
||||||
latest_msg_subq = (
|
latest_msg_subq = (
|
||||||
select(
|
select(
|
||||||
ChatMessageModel.agent_id,
|
ChatMessageModel.agent_id,
|
||||||
ChatMessageModel.message_id,
|
ChatMessageModel.message_id,
|
||||||
ChatMessageModel.role,
|
ChatMessageModel.role,
|
||||||
ChatMessageModel.content,
|
ChatMessageModel.content,
|
||||||
ChatMessageModel.created_at.label('message_time')
|
ChatMessageModel.message_time.label('message_time')
|
||||||
)
|
)
|
||||||
.distinct(ChatMessageModel.agent_id)
|
.distinct(ChatMessageModel.agent_id)
|
||||||
.order_by(ChatMessageModel.agent_id, ChatMessageModel.message_id.desc())
|
.order_by(ChatMessageModel.agent_id, ChatMessageModel.message_time.desc())
|
||||||
.subquery('latest_messages')
|
.subquery('latest_messages')
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -272,7 +273,12 @@ class Agent:
|
||||||
# Apply cursor filter
|
# Apply cursor filter
|
||||||
if cursor:
|
if cursor:
|
||||||
try:
|
try:
|
||||||
cursor_time = datetime.fromisoformat(cursor)
|
# Handle URL encoding issues: '+' in URL becomes space
|
||||||
|
cursor_str = cursor.replace(' ', '+')
|
||||||
|
cursor_time = datetime.fromisoformat(cursor_str)
|
||||||
|
# Ensure timezone-aware for proper comparison
|
||||||
|
if cursor_time.tzinfo is None:
|
||||||
|
cursor_time = cursor_time.replace(tzinfo=timezone.utc)
|
||||||
query = query.where(sort_time_expr < cursor_time)
|
query = query.where(sort_time_expr < cursor_time)
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
pass
|
pass
|
||||||
|
|
@ -288,12 +294,12 @@ class Agent:
|
||||||
if has_more:
|
if has_more:
|
||||||
rows = rows[:limit]
|
rows = rows[:limit]
|
||||||
|
|
||||||
# Generate next cursor from last item's sort_time
|
# Generate next cursor from last item's sort_time (keep timezone info)
|
||||||
next_cursor = None
|
next_cursor = None
|
||||||
if has_more and rows:
|
if has_more and rows:
|
||||||
last_sort_time = rows[-1].sort_time
|
last_sort_time = rows[-1].sort_time
|
||||||
if last_sort_time:
|
if last_sort_time:
|
||||||
next_cursor = last_sort_time.replace(tzinfo=None).isoformat()
|
next_cursor = last_sort_time.isoformat()
|
||||||
|
|
||||||
return rows, next_cursor, has_more
|
return rows, next_cursor, has_more
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
"""
|
"""
|
||||||
Chat messages repository - Database operations for chat messages
|
Chat messages repository - Database operations for chat messages
|
||||||
"""
|
"""
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
from typing import List, Optional, Tuple
|
from typing import List, Optional, Tuple
|
||||||
from sqlalchemy import String, SmallInteger, TIMESTAMP, ForeignKey, Index, select, insert
|
from sqlalchemy import String, SmallInteger, TIMESTAMP, ForeignKey, Index, select, insert
|
||||||
from sqlalchemy.orm import Mapped, mapped_column
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
@ -35,7 +35,14 @@ class ChatMessageModel(Base):
|
||||||
# JSONB content: [{"message_type": "text|audio|image|file", "message_content": "..."}]
|
# JSONB content: [{"message_type": "text|audio|image|file", "message_content": "..."}]
|
||||||
content: Mapped[List[dict]] = mapped_column(JSONB, nullable=False)
|
content: Mapped[List[dict]] = mapped_column(JSONB, nullable=False)
|
||||||
|
|
||||||
# Timestamp
|
# Message time - when message actually occurred (for correct ordering)
|
||||||
|
message_time: Mapped[datetime] = mapped_column(
|
||||||
|
TIMESTAMP(timezone=True),
|
||||||
|
default=utc_now,
|
||||||
|
nullable=False
|
||||||
|
)
|
||||||
|
|
||||||
|
# Timestamp - when message was stored in database
|
||||||
created_at: Mapped[datetime] = mapped_column(
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
TIMESTAMP(timezone=True),
|
TIMESTAMP(timezone=True),
|
||||||
default=utc_now,
|
default=utc_now,
|
||||||
|
|
@ -47,6 +54,7 @@ class ChatMessageModel(Base):
|
||||||
Index('idx_chat_messages_agent_id', 'agent_id'),
|
Index('idx_chat_messages_agent_id', 'agent_id'),
|
||||||
Index('idx_chat_messages_agent_message_composite', 'agent_id', 'message_id'),
|
Index('idx_chat_messages_agent_message_composite', 'agent_id', 'message_id'),
|
||||||
Index('idx_chat_messages_content_gin', 'content', postgresql_using='gin'),
|
Index('idx_chat_messages_content_gin', 'content', postgresql_using='gin'),
|
||||||
|
Index('idx_chat_messages_agent_message_time', 'agent_id', 'message_time'),
|
||||||
)
|
)
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
|
|
@ -66,7 +74,8 @@ class ChatMessage:
|
||||||
message_id: str,
|
message_id: str,
|
||||||
agent_id: str,
|
agent_id: str,
|
||||||
role: int,
|
role: int,
|
||||||
content: List[dict] # Already processed with S3 URLs
|
content: List[dict], # Already processed with S3 URLs
|
||||||
|
message_time: datetime = None # When message actually occurred
|
||||||
) -> ChatMessageModel:
|
) -> ChatMessageModel:
|
||||||
"""
|
"""
|
||||||
Create new chat message
|
Create new chat message
|
||||||
|
|
@ -77,6 +86,7 @@ class ChatMessage:
|
||||||
agent_id: Agent ID
|
agent_id: Agent ID
|
||||||
role: 1=user, 2=agent
|
role: 1=user, 2=agent
|
||||||
content: List of message parts with S3 URLs
|
content: List of message parts with S3 URLs
|
||||||
|
message_time: When message actually occurred (for ordering)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Created message model
|
Created message model
|
||||||
|
|
@ -85,7 +95,8 @@ class ChatMessage:
|
||||||
message_id=message_id,
|
message_id=message_id,
|
||||||
agent_id=agent_id,
|
agent_id=agent_id,
|
||||||
role=role,
|
role=role,
|
||||||
content=content
|
content=content,
|
||||||
|
message_time=message_time or utc_now()
|
||||||
)
|
)
|
||||||
db.add(message)
|
db.add(message)
|
||||||
await db.commit()
|
await db.commit()
|
||||||
|
|
@ -103,13 +114,13 @@ class ChatMessage:
|
||||||
Get messages by agent_id using cursor-based pagination (chat style)
|
Get messages by agent_id using cursor-based pagination (chat style)
|
||||||
|
|
||||||
Behavior:
|
Behavior:
|
||||||
- First load (no cursor): Returns the latest messages (DESC order)
|
- First load (no cursor): Returns the latest messages (DESC order by message_time)
|
||||||
- Scroll up (with cursor): Returns older messages before the cursor
|
- Scroll up (with cursor): Returns older messages before the cursor timestamp
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
db: Database session
|
db: Database session
|
||||||
agent_id: Agent ID
|
agent_id: Agent ID
|
||||||
cursor: Message ID (ULID) to load messages before. If None, load latest messages
|
cursor: ISO format timestamp to load messages before. If None, load latest messages
|
||||||
limit: Number of messages to fetch
|
limit: Number of messages to fetch
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
|
|
@ -118,13 +129,24 @@ class ChatMessage:
|
||||||
# Build query with cursor
|
# Build query with cursor
|
||||||
query = select(ChatMessageModel).where(ChatMessageModel.agent_id == agent_id)
|
query = select(ChatMessageModel).where(ChatMessageModel.agent_id == agent_id)
|
||||||
|
|
||||||
# Apply cursor filter if provided - load messages BEFORE cursor (older messages)
|
# Apply cursor filter if provided - load messages BEFORE cursor timestamp (older messages)
|
||||||
if cursor:
|
if cursor:
|
||||||
query = query.where(ChatMessageModel.message_id < cursor)
|
try:
|
||||||
|
# Parse ISO format timestamp
|
||||||
|
# Handle URL encoding issues: '+' in URL becomes space, so convert space back to '+'
|
||||||
|
cursor_str = cursor.replace(' ', '+')
|
||||||
|
cursor_time = datetime.fromisoformat(cursor_str)
|
||||||
|
# Ensure timezone-aware for proper comparison
|
||||||
|
if cursor_time.tzinfo is None:
|
||||||
|
cursor_time = cursor_time.replace(tzinfo=timezone.utc)
|
||||||
|
query = query.where(ChatMessageModel.message_time < cursor_time)
|
||||||
|
except (ValueError, TypeError) as e:
|
||||||
|
# Invalid cursor format, ignore and load latest
|
||||||
|
pass
|
||||||
|
|
||||||
# Order by message_id DESC to get latest messages first
|
# Order by message_time DESC to get latest messages first
|
||||||
# Fetch limit + 1 to check if there are more records
|
# Fetch limit + 1 to check if there are more records
|
||||||
query = query.order_by(ChatMessageModel.message_id.desc()).limit(limit + 1)
|
query = query.order_by(ChatMessageModel.message_time.desc()).limit(limit + 1)
|
||||||
|
|
||||||
result = await db.execute(query)
|
result = await db.execute(query)
|
||||||
messages: List[ChatMessageModel] = result.scalars().all()
|
messages: List[ChatMessageModel] = result.scalars().all()
|
||||||
|
|
@ -134,10 +156,10 @@ class ChatMessage:
|
||||||
if has_more:
|
if has_more:
|
||||||
messages = messages[:limit]
|
messages = messages[:limit]
|
||||||
|
|
||||||
# Get next cursor (oldest message_id in current batch for loading earlier messages)
|
# Get next cursor (message_time of oldest message in batch)
|
||||||
next_cursor = None
|
next_cursor = None
|
||||||
if has_more and messages:
|
if has_more and messages:
|
||||||
next_cursor = messages[-1].message_id
|
next_cursor = messages[-1].message_time.isoformat()
|
||||||
|
|
||||||
return messages, next_cursor, has_more
|
return messages, next_cursor, has_more
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
"""
|
"""
|
||||||
Chat messages schemas for API request/response validation
|
Chat messages schemas for API request/response validation
|
||||||
"""
|
"""
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field, field_serializer
|
||||||
from typing import List, Literal, Optional
|
from typing import List, Literal, Optional
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import enum
|
import enum
|
||||||
|
|
@ -21,6 +21,7 @@ class ReportChatMessageRequest(BaseModel):
|
||||||
agent_id: str = Field(..., max_length=50, description="Agent ID")
|
agent_id: str = Field(..., max_length=50, description="Agent ID")
|
||||||
role: int = Field(..., ge=1, le=2, description="1: user, 2: agent")
|
role: int = Field(..., ge=1, le=2, description="1: user, 2: agent")
|
||||||
content: List[MessageBody] = Field(..., description="Message content parts")
|
content: List[MessageBody] = Field(..., description="Message content parts")
|
||||||
|
message_time: int = Field(..., description="Unix timestamp when message actually occurred (for correct ordering)")
|
||||||
|
|
||||||
|
|
||||||
class ChatMessage(BaseModel):
|
class ChatMessage(BaseModel):
|
||||||
|
|
@ -29,12 +30,17 @@ class ChatMessage(BaseModel):
|
||||||
agent_id: str
|
agent_id: str
|
||||||
role: int # 1: user, 2: agent
|
role: int # 1: user, 2: agent
|
||||||
content: List[MessageBody]
|
content: List[MessageBody]
|
||||||
created_at: datetime
|
message_time: datetime # When message actually occurred (for ordering)
|
||||||
|
|
||||||
|
@field_serializer('message_time')
|
||||||
|
def serialize_message_time(self, value: datetime) -> str:
|
||||||
|
"""Serialize datetime to ISO format with timezone"""
|
||||||
|
return value.isoformat()
|
||||||
|
|
||||||
|
|
||||||
class ChatMessagesListResponse(BaseModel):
|
class ChatMessagesListResponse(BaseModel):
|
||||||
"""Response schema for paginated chat messages (cursor-based, chat style)"""
|
"""Response schema for paginated chat messages (cursor-based, chat style)"""
|
||||||
messages: List[ChatMessage]
|
messages: List[ChatMessage]
|
||||||
next_cursor: Optional[str] = Field(None, description="Message ID to load older messages (pass as cursor for next request)")
|
next_cursor: Optional[str] = Field(None, description="ISO timestamp to load older messages (pass as cursor for next request)")
|
||||||
has_more: bool = Field(False, description="Whether there are more older messages available")
|
has_more: bool = Field(False, description="Whether there are more older messages available")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
Chat service - Business logic for chat messages
|
Chat service - Business logic for chat messages
|
||||||
"""
|
"""
|
||||||
import base64
|
import base64
|
||||||
|
from datetime import datetime, timezone
|
||||||
from typing import List, Optional, Tuple
|
from typing import List, Optional, Tuple
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
|
|
@ -68,13 +69,19 @@ class ChatService:
|
||||||
# Convert Pydantic models to dict for JSONB storage
|
# Convert Pydantic models to dict for JSONB storage
|
||||||
content_dicts = [msg.model_dump() for msg in contents]
|
content_dicts = [msg.model_dump() for msg in contents]
|
||||||
|
|
||||||
|
# Convert message_time from unix timestamp to datetime
|
||||||
|
message_time = None
|
||||||
|
if request.message_time:
|
||||||
|
message_time = datetime.fromtimestamp(request.message_time, tz=timezone.utc)
|
||||||
|
|
||||||
# Store in database
|
# Store in database
|
||||||
chat_message = await ChatMessageRepo.create(
|
chat_message = await ChatMessageRepo.create(
|
||||||
db=db,
|
db=db,
|
||||||
message_id=message_id,
|
message_id=message_id,
|
||||||
agent_id=request.agent_id,
|
agent_id=request.agent_id,
|
||||||
role=request.role,
|
role=request.role,
|
||||||
content=content_dicts
|
content=content_dicts,
|
||||||
|
message_time=message_time
|
||||||
)
|
)
|
||||||
|
|
||||||
return ChatMessageSchema(
|
return ChatMessageSchema(
|
||||||
|
|
@ -82,7 +89,7 @@ class ChatService:
|
||||||
agent_id=chat_message.agent_id,
|
agent_id=chat_message.agent_id,
|
||||||
role=chat_message.role,
|
role=chat_message.role,
|
||||||
content=chat_message.content,
|
content=chat_message.content,
|
||||||
created_at=chat_message.created_at
|
message_time=chat_message.message_time,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def get_agent_messages(
|
async def get_agent_messages(
|
||||||
|
|
@ -125,7 +132,7 @@ class ChatService:
|
||||||
agent_id=message.agent_id,
|
agent_id=message.agent_id,
|
||||||
role=message.role,
|
role=message.role,
|
||||||
content=message.content,
|
content=message.content,
|
||||||
created_at=message.created_at
|
message_time=message.message_time,
|
||||||
))
|
))
|
||||||
|
|
||||||
return response_messages, next_cursor, has_more
|
return response_messages, next_cursor, has_more
|
||||||
|
|
|
||||||
|
|
@ -2,9 +2,10 @@
|
||||||
import json
|
import json
|
||||||
from typing import AsyncGenerator, Optional
|
from typing import AsyncGenerator, Optional
|
||||||
from openai import AsyncOpenAI
|
from openai import AsyncOpenAI
|
||||||
from config import settings
|
from config import settings, get_logger
|
||||||
|
import time
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
class LLMService:
|
class LLMService:
|
||||||
"""Service for LLM-based text generation"""
|
"""Service for LLM-based text generation"""
|
||||||
|
|
||||||
|
|
@ -232,6 +233,7 @@ Create a richer, more detailed persona."""
|
||||||
|
|
||||||
async for chunk in stream:
|
async for chunk in stream:
|
||||||
if chunk.choices and chunk.choices[0].delta.content:
|
if chunk.choices and chunk.choices[0].delta.content:
|
||||||
|
logger.info(f"Optimize persona chunk time: {time.time()}")
|
||||||
yield chunk.choices[0].delta.content
|
yield chunk.choices[0].delta.content
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
|
||||||
54
main/live-agent-api/services/stt_service.py
Normal file
54
main/live-agent-api/services/stt_service.py
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
"""STT service for audio transcription using Groq Whisper"""
|
||||||
|
from openai import AsyncOpenAI
|
||||||
|
from fastapi import UploadFile
|
||||||
|
from config import settings
|
||||||
|
|
||||||
|
# TODO: WE CAN ADD MORE CONTEXT HERE FOR BETTER TRANSCRIPTION
|
||||||
|
TRANCRIPTION_PROMPT = "Hello, 这是一个测试。We discuss the plan, 请加上标点符号。"
|
||||||
|
|
||||||
|
class STTService:
|
||||||
|
"""Service for audio-to-text transcription"""
|
||||||
|
|
||||||
|
async def transcribe(
|
||||||
|
self,
|
||||||
|
groq_client: AsyncOpenAI,
|
||||||
|
audio_file: UploadFile
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
Transcribe audio file to text using Groq Whisper
|
||||||
|
|
||||||
|
Args:
|
||||||
|
groq_client: Groq client instance (OpenAI SDK with Groq base URL)
|
||||||
|
audio_file: Audio file uploaded by user
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict with text, language, duration
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
Exception: If Groq API call fails
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# Read audio file content
|
||||||
|
audio_content = await audio_file.read()
|
||||||
|
|
||||||
|
# Reset file pointer for potential reuse
|
||||||
|
await audio_file.seek(0)
|
||||||
|
|
||||||
|
# Call Groq Whisper API using OpenAI SDK
|
||||||
|
text = await groq_client.audio.transcriptions.create(
|
||||||
|
model=settings.GROQ_STT_MODEL,
|
||||||
|
file=(audio_file.filename, audio_content),
|
||||||
|
response_format="text", # only need transcribed text now
|
||||||
|
prompt=TRANCRIPTION_PROMPT,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Extract transcription results
|
||||||
|
return text
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"Failed to transcribe audio: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
# Singleton instance
|
||||||
|
stt_service = STTService()
|
||||||
|
|
||||||
|
|
@ -810,6 +810,7 @@ dependencies = [
|
||||||
{ name = "fastapi" },
|
{ name = "fastapi" },
|
||||||
{ name = "fish-audio-sdk" },
|
{ name = "fish-audio-sdk" },
|
||||||
{ name = "httpx" },
|
{ name = "httpx" },
|
||||||
|
{ name = "loguru" },
|
||||||
{ name = "openai" },
|
{ name = "openai" },
|
||||||
{ name = "pydantic" },
|
{ name = "pydantic" },
|
||||||
{ name = "pydantic-settings" },
|
{ name = "pydantic-settings" },
|
||||||
|
|
@ -840,6 +841,7 @@ requires-dist = [
|
||||||
{ name = "fastapi", specifier = ">=0.115.0" },
|
{ name = "fastapi", specifier = ">=0.115.0" },
|
||||||
{ name = "fish-audio-sdk", specifier = ">=1.1.0" },
|
{ name = "fish-audio-sdk", specifier = ">=1.1.0" },
|
||||||
{ name = "httpx", specifier = ">=0.27.0" },
|
{ name = "httpx", specifier = ">=0.27.0" },
|
||||||
|
{ name = "loguru", specifier = ">=0.7.0" },
|
||||||
{ name = "openai", specifier = ">=1.54.0" },
|
{ name = "openai", specifier = ">=1.54.0" },
|
||||||
{ name = "pydantic", specifier = ">=2.9.0" },
|
{ name = "pydantic", specifier = ">=2.9.0" },
|
||||||
{ name = "pydantic-settings", specifier = ">=2.6.0" },
|
{ name = "pydantic-settings", specifier = ">=2.6.0" },
|
||||||
|
|
@ -856,6 +858,19 @@ requires-dist = [
|
||||||
]
|
]
|
||||||
provides-extras = ["dev"]
|
provides-extras = ["dev"]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "loguru"
|
||||||
|
version = "0.7.3"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "colorama", marker = "sys_platform == 'win32'" },
|
||||||
|
{ name = "win32-setctime", marker = "sys_platform == 'win32'" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/3a/05/a1dae3dffd1116099471c643b8924f5aa6524411dc6c63fdae648c4f1aca/loguru-0.7.3.tar.gz", hash = "sha256:19480589e77d47b8d85b2c827ad95d49bf31b0dcde16593892eb51dd18706eb6", size = 63559, upload-time = "2024-12-06T11:20:56.608Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/0c/29/0348de65b8cc732daa3e33e67806420b2ae89bdce2b04af740289c5c6c8c/loguru-0.7.3-py3-none-any.whl", hash = "sha256:31a33c10c8e1e10422bfd431aeb5d351c7cf7fa671e3c4df004162264b28220c", size = 61595, upload-time = "2024-12-06T11:20:54.538Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "multidict"
|
name = "multidict"
|
||||||
version = "6.7.0"
|
version = "6.7.0"
|
||||||
|
|
@ -1693,6 +1708,15 @@ wheels = [
|
||||||
{ url = "https://files.pythonhosted.org/packages/fa/a8/5b41e0da817d64113292ab1f8247140aac61cbf6cfd085d6a0fa77f4984f/websockets-15.0.1-py3-none-any.whl", hash = "sha256:f7a866fbc1e97b5c617ee4116daaa09b722101d4a3c170c787450ba409f9736f", size = 169743, upload-time = "2025-03-05T20:03:39.41Z" },
|
{ url = "https://files.pythonhosted.org/packages/fa/a8/5b41e0da817d64113292ab1f8247140aac61cbf6cfd085d6a0fa77f4984f/websockets-15.0.1-py3-none-any.whl", hash = "sha256:f7a866fbc1e97b5c617ee4116daaa09b722101d4a3c170c787450ba409f9736f", size = 169743, upload-time = "2025-03-05T20:03:39.41Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "win32-setctime"
|
||||||
|
version = "1.2.0"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/b3/8f/705086c9d734d3b663af0e9bb3d4de6578d08f46b1b101c2442fd9aecaa2/win32_setctime-1.2.0.tar.gz", hash = "sha256:ae1fdf948f5640aae05c511ade119313fb6a30d7eabe25fef9764dca5873c4c0", size = 4867, upload-time = "2024-12-07T15:28:28.314Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/e1/07/c6fe3ad3e685340704d314d765b7912993bcb8dc198f0e7a89382d37974b/win32_setctime-1.2.0-py3-none-any.whl", hash = "sha256:95d644c4e708aba81dc3704a116d8cbc974d70b3bdb8be1d150e36be6e9d1390", size = 4083, upload-time = "2024-12-07T15:28:26.465Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wrapt"
|
name = "wrapt"
|
||||||
version = "1.17.3"
|
version = "1.17.3"
|
||||||
|
|
|
||||||
|
|
@ -114,6 +114,7 @@ def report_chat_message(
|
||||||
agent_id: str,
|
agent_id: str,
|
||||||
role: int,
|
role: int,
|
||||||
content_items: List[Dict[str, str]],
|
content_items: List[Dict[str, str]],
|
||||||
|
message_time: int = None,
|
||||||
config: dict = None
|
config: dict = None
|
||||||
) -> Optional[dict]:
|
) -> Optional[dict]:
|
||||||
"""
|
"""
|
||||||
|
|
@ -129,6 +130,7 @@ def report_chat_message(
|
||||||
{"message_type": "image", "message_content": "s3_url"},
|
{"message_type": "image", "message_content": "s3_url"},
|
||||||
{"message_type": "file", "message_content": "s3_url"}
|
{"message_type": "file", "message_content": "s3_url"}
|
||||||
]
|
]
|
||||||
|
message_time: Unix timestamp when message actually occurred (for correct ordering)
|
||||||
config: System config (optional if client already initialized)
|
config: System config (optional if client already initialized)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
|
|
@ -148,6 +150,10 @@ def report_chat_message(
|
||||||
"content": content_items
|
"content": content_items
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Add message_time if provided (for correct message ordering)
|
||||||
|
if message_time is not None:
|
||||||
|
payload["message_time"] = message_time
|
||||||
|
|
||||||
result = LiveAgentApiClient._request("POST", "/chat/report", json=payload)
|
result = LiveAgentApiClient._request("POST", "/chat/report", json=payload)
|
||||||
|
|
||||||
if result.get("code") == 200:
|
if result.get("code") == 200:
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ from core.providers.tts.default import DefaultTTS
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from core.utils.dialogue import Message, Dialogue
|
from core.utils.dialogue import Message, Dialogue
|
||||||
from core.providers.asr.dto.dto import InterfaceType
|
from core.providers.asr.dto.dto import InterfaceType
|
||||||
|
from core.providers.tts.dto.dto import MessageTag
|
||||||
from core.handle.textHandle import handleTextMessage
|
from core.handle.textHandle import handleTextMessage
|
||||||
from core.providers.tools.unified_tool_handler import UnifiedToolHandler
|
from core.providers.tools.unified_tool_handler import UnifiedToolHandler
|
||||||
from plugins_func.loadplugins import auto_import_modules
|
from plugins_func.loadplugins import auto_import_modules
|
||||||
|
|
@ -168,6 +169,9 @@ class ConnectionHandler:
|
||||||
self._voice_closing = None
|
self._voice_closing = None
|
||||||
self._language = None
|
self._language = None
|
||||||
|
|
||||||
|
# reconnected flag
|
||||||
|
self.reconnected: bool = False
|
||||||
|
|
||||||
async def handle_connection(self, ws):
|
async def handle_connection(self, ws):
|
||||||
try:
|
try:
|
||||||
# 获取并验证headers
|
# 获取并验证headers
|
||||||
|
|
@ -189,6 +193,9 @@ class ConnectionHandler:
|
||||||
# 认证通过,继续处理
|
# 认证通过,继续处理
|
||||||
self.websocket = ws
|
self.websocket = ws
|
||||||
|
|
||||||
|
# check if the connection is reconnected by the mobile-end
|
||||||
|
self.reconnected = self.headers.get("reconnected", "0") == "1"
|
||||||
|
self.logger.bind(tag=TAG).info(f"reconnected: {self.reconnected}")
|
||||||
# 检查是否来自MQTT连接
|
# 检查是否来自MQTT连接
|
||||||
request_path = ws.request.path
|
request_path = ws.request.path
|
||||||
self.conn_from_mqtt_gateway = request_path.endswith("?from=mqtt_gateway")
|
self.conn_from_mqtt_gateway = request_path.endswith("?from=mqtt_gateway")
|
||||||
|
|
@ -450,12 +457,13 @@ class ConnectionHandler:
|
||||||
self.logger.bind(tag=TAG).info(f"send the opening message: {self._voice_opening}")
|
self.logger.bind(tag=TAG).info(f"send the opening message: {self._voice_opening}")
|
||||||
|
|
||||||
opening_sentence_id = str(uuid.uuid4().hex)
|
opening_sentence_id = str(uuid.uuid4().hex)
|
||||||
|
message_tag = MessageTag.OPENING
|
||||||
# FIRST: Start session
|
# FIRST: Start session
|
||||||
self.tts.tts_text_queue.put(TTSMessageDTO(
|
self.tts.tts_text_queue.put(TTSMessageDTO(
|
||||||
sentence_id=opening_sentence_id,
|
sentence_id=opening_sentence_id,
|
||||||
sentence_type=SentenceType.FIRST,
|
sentence_type=SentenceType.FIRST,
|
||||||
content_type=ContentType.ACTION,
|
content_type=ContentType.ACTION,
|
||||||
|
message_tag=message_tag,
|
||||||
))
|
))
|
||||||
|
|
||||||
self.tts.tts_text_queue.put(TTSMessageDTO(
|
self.tts.tts_text_queue.put(TTSMessageDTO(
|
||||||
|
|
@ -463,6 +471,7 @@ class ConnectionHandler:
|
||||||
sentence_type=SentenceType.MIDDLE,
|
sentence_type=SentenceType.MIDDLE,
|
||||||
content_type=ContentType.TEXT,
|
content_type=ContentType.TEXT,
|
||||||
content_detail=self._voice_opening,
|
content_detail=self._voice_opening,
|
||||||
|
message_tag=message_tag,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -470,6 +479,7 @@ class ConnectionHandler:
|
||||||
sentence_id=opening_sentence_id,
|
sentence_id=opening_sentence_id,
|
||||||
sentence_type=SentenceType.LAST,
|
sentence_type=SentenceType.LAST,
|
||||||
content_type=ContentType.ACTION,
|
content_type=ContentType.ACTION,
|
||||||
|
message_tag=message_tag,
|
||||||
))
|
))
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
@ -1194,14 +1204,10 @@ class ConnectionHandler:
|
||||||
try:
|
try:
|
||||||
# 从队列获取数据,设置超时以便定期检查停止事件
|
# 从队列获取数据,设置超时以便定期检查停止事件
|
||||||
item = self.report_queue.get(timeout=1)
|
item = self.report_queue.get(timeout=1)
|
||||||
if item is None: # 检测毒丸对象
|
if item is None: # detect poison pill object
|
||||||
|
self.report_queue.task_done()
|
||||||
break
|
break
|
||||||
try:
|
try:
|
||||||
# 检查线程池状态
|
|
||||||
if self.executor is None:
|
|
||||||
continue
|
|
||||||
# 提交任务到线程池
|
|
||||||
# self.executor.submit(self._process_report, *item)
|
|
||||||
self._process_report(*item)
|
self._process_report(*item)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}")
|
self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}")
|
||||||
|
|
@ -1210,6 +1216,21 @@ class ConnectionHandler:
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"聊天记录上报工作线程异常: {e}")
|
self.logger.bind(tag=TAG).error(f"聊天记录上报工作线程异常: {e}")
|
||||||
|
|
||||||
|
# stop_event is set, continue processing remaining messages in report_queue
|
||||||
|
self.logger.bind(tag=TAG).info("processing remaining report messages...")
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
item = self.report_queue.get(timeout=1)
|
||||||
|
if item is None: # detect poison pill object
|
||||||
|
self.report_queue.task_done()
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
self._process_report(*item)
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"processing remaining report messages failed: {e}")
|
||||||
|
except queue.Empty:
|
||||||
|
continue
|
||||||
|
|
||||||
self.logger.bind(tag=TAG).info("聊天记录上报线程已退出")
|
self.logger.bind(tag=TAG).info("聊天记录上报线程已退出")
|
||||||
|
|
||||||
def _process_report(self, role, text, audio_data, report_time, attachments=None):
|
def _process_report(self, role, text, audio_data, report_time, attachments=None):
|
||||||
|
|
@ -1256,9 +1277,21 @@ class ConnectionHandler:
|
||||||
if self.stop_event:
|
if self.stop_event:
|
||||||
self.stop_event.set()
|
self.stop_event.set()
|
||||||
|
|
||||||
# 清空任务队列
|
# clear TTS text queue and audio queue, except report_queue
|
||||||
self.clear_queues()
|
self.clear_queues()
|
||||||
|
|
||||||
|
# process remaining messages in report_queue
|
||||||
|
if self._report_enabled and self.report_queue:
|
||||||
|
try:
|
||||||
|
self.logger.bind(tag=TAG).info("waiting for report queue to be processed...")
|
||||||
|
# send poison pill object to notify report_worker to exit and process remaining messages
|
||||||
|
self.report_queue.put(None)
|
||||||
|
# wait for all messages to be processed
|
||||||
|
self.report_queue.join()
|
||||||
|
self.logger.bind(tag=TAG).info("report queue processed")
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).warning(f"waiting for report queue timeout or failed: {e}")
|
||||||
|
|
||||||
# 关闭WebSocket连接
|
# 关闭WebSocket连接
|
||||||
try:
|
try:
|
||||||
if ws:
|
if ws:
|
||||||
|
|
@ -1317,17 +1350,16 @@ class ConnectionHandler:
|
||||||
self.stop_event.set()
|
self.stop_event.set()
|
||||||
|
|
||||||
def clear_queues(self):
|
def clear_queues(self):
|
||||||
"""清空所有任务队列"""
|
"""clear TTS task queues (except report_queue, which is handled by close method)"""
|
||||||
if self.tts:
|
if self.tts:
|
||||||
self.logger.bind(tag=TAG).debug(
|
self.logger.bind(tag=TAG).debug(
|
||||||
f"开始清理: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
|
f"开始清理: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# 使用非阻塞方式清空队列
|
# use non-blocking way to clear TTS queues
|
||||||
for q in [
|
for q in [
|
||||||
self.tts.tts_text_queue,
|
self.tts.tts_text_queue,
|
||||||
self.tts.tts_audio_queue,
|
self.tts.tts_audio_queue,
|
||||||
self.report_queue,
|
|
||||||
]:
|
]:
|
||||||
if not q:
|
if not q:
|
||||||
continue
|
continue
|
||||||
|
|
|
||||||
|
|
@ -7,46 +7,15 @@ Report features:
|
||||||
See core/connection.py for implementation details.
|
See core/connection.py for implementation details.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import re
|
|
||||||
import time
|
import time
|
||||||
import base64
|
import base64
|
||||||
from typing import List, Dict, Any
|
from typing import List, Dict, Any
|
||||||
from config.live_agent_api_client import report_chat_message
|
from config.live_agent_api_client import report_chat_message
|
||||||
|
from core.providers.tts.dto.dto import MessageTag
|
||||||
|
from core.utils.textUtils import strip_emotion_tags
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
# Regex pattern to match emotion tags anywhere in text
|
|
||||||
# Format: (emotion) e.g., "(happy)", "(sincere)", "(curious)"
|
|
||||||
# Matches: optional whitespace + (word) + optional whitespace
|
|
||||||
EMOTION_TAG_PATTERN = re.compile(r'\s*\([a-zA-Z_]+\)\s*')
|
|
||||||
|
|
||||||
|
|
||||||
def strip_emotion_tags(text: str) -> str:
|
|
||||||
"""
|
|
||||||
Remove all emotion tags from TTS text.
|
|
||||||
|
|
||||||
Emotion tags are in format: (emotion) typically at the start of sentences.
|
|
||||||
Examples:
|
|
||||||
"(happy) Hello!" -> "Hello!"
|
|
||||||
"(sincere) That's great. (curious) What next?" -> "That's great. What next?"
|
|
||||||
"Hello (happy) world" -> "Hello world"
|
|
||||||
|
|
||||||
Args:
|
|
||||||
text: Text with potential emotion tags
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Text with all emotion tags removed
|
|
||||||
"""
|
|
||||||
if not text:
|
|
||||||
return text
|
|
||||||
|
|
||||||
# Remove all emotion tags from the text
|
|
||||||
result = EMOTION_TAG_PATTERN.sub(' ', text)
|
|
||||||
# Clean up multiple spaces and trim
|
|
||||||
result = re.sub(r'\s+', ' ', result)
|
|
||||||
return result.strip()
|
|
||||||
|
|
||||||
|
|
||||||
def report(conn, role, text: str, opus_data: List[bytes] | None = None, report_time: int = 0, attachments: List[Dict[str, Any]] | None = None):
|
def report(conn, role, text: str, opus_data: List[bytes] | None = None, report_time: int = 0, attachments: List[Dict[str, Any]] | None = None):
|
||||||
"""Execute chat message report to live-agent-api
|
"""Execute chat message report to live-agent-api
|
||||||
|
|
@ -56,7 +25,7 @@ def report(conn, role, text: str, opus_data: List[bytes] | None = None, report_t
|
||||||
role: Message role, 1=user, 2=agent
|
role: Message role, 1=user, 2=agent
|
||||||
text: Message text content
|
text: Message text content
|
||||||
opus_data: Opus audio data (list of opus packets)
|
opus_data: Opus audio data (list of opus packets)
|
||||||
report_time: Report timestamp (currently unused, kept for compatibility)
|
report_time: Unix timestamp when message actually occurred (for correct ordering)
|
||||||
attachments: Optional list of attachments (multimodal content), format:
|
attachments: Optional list of attachments (multimodal content), format:
|
||||||
[
|
[
|
||||||
{"type": "image", "url": "https://..."},
|
{"type": "image", "url": "https://..."},
|
||||||
|
|
@ -101,30 +70,40 @@ def report(conn, role, text: str, opus_data: List[bytes] | None = None, report_t
|
||||||
conn.logger.bind(tag=TAG).warning("No content to report, skipping")
|
conn.logger.bind(tag=TAG).warning("No content to report, skipping")
|
||||||
return
|
return
|
||||||
|
|
||||||
# Report to live-agent-api (client already initialized at startup)
|
# Report to live-agent-api with message_time for correct ordering
|
||||||
report_chat_message(
|
report_chat_message(
|
||||||
agent_id=conn.agent_id,
|
agent_id=conn.agent_id,
|
||||||
role=role,
|
role=role,
|
||||||
content_items=content_items
|
content_items=content_items,
|
||||||
|
message_time=report_time if report_time > 0 else None
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
conn.logger.bind(tag=TAG).error(f"Chat message report failed: {e}")
|
conn.logger.bind(tag=TAG).error(f"Chat message report failed: {e}")
|
||||||
|
|
||||||
|
|
||||||
def enqueue_tts_report(conn, text, opus_data):
|
def enqueue_tts_report(conn, text, opus_data, message_tag=MessageTag.NORMAL, report_time=None):
|
||||||
"""Enqueue TTS data for reporting (Agent message)
|
"""Enqueue TTS data for reporting (Agent message)
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
conn: Connection object
|
conn: Connection object
|
||||||
text: Synthesized text (may contain emotion tags)
|
text: Synthesized text (may contain emotion tags)
|
||||||
opus_data: Opus audio data (list of opus packets)
|
opus_data: Opus audio data (list of opus packets)
|
||||||
|
message_tag: Message tag for special messages (opening/closing)
|
||||||
|
report_time: Timestamp when message actually occurred (for correct ordering)
|
||||||
"""
|
"""
|
||||||
# Check if reporting is enabled for live-agent-api mode
|
# Check if reporting is enabled for live-agent-api mode
|
||||||
if not conn.read_config_from_live_agent_api or conn.need_bind or not conn.report_tts_enable:
|
if not conn.read_config_from_live_agent_api or conn.need_bind or not conn.report_tts_enable:
|
||||||
return
|
return
|
||||||
if conn.chat_history_conf == 0:
|
if conn.chat_history_conf == 0:
|
||||||
return
|
return
|
||||||
|
# if the message is opening and the connection is reconnected, skip the report
|
||||||
|
if message_tag == MessageTag.OPENING and conn.reconnected:
|
||||||
|
conn.logger.bind(tag=TAG).info(f"Opening message is reconnected, skipping report")
|
||||||
|
return
|
||||||
|
|
||||||
|
# Use provided report_time or current time
|
||||||
|
timestamp = report_time if report_time is not None else int(time.time())
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Remove emotion tags from text before reporting
|
# Remove emotion tags from text before reporting
|
||||||
|
|
@ -133,27 +112,29 @@ def enqueue_tts_report(conn, text, opus_data):
|
||||||
# Use connection's queue, pass text and binary data
|
# Use connection's queue, pass text and binary data
|
||||||
if conn.chat_history_conf == 2:
|
if conn.chat_history_conf == 2:
|
||||||
# Report with audio (TTS never has attachments)
|
# Report with audio (TTS never has attachments)
|
||||||
conn.report_queue.put((2, clean_text, opus_data, int(time.time()), None))
|
conn.report_queue.put((2, clean_text, opus_data, timestamp, None))
|
||||||
conn.logger.bind(tag=TAG).debug(
|
conn.logger.bind(tag=TAG).debug(
|
||||||
f"TTS data enqueued: agent_id={conn.agent_id}, audio packets: {len(opus_data)}"
|
f"TTS data enqueued: agent_id={conn.agent_id}, audio packets: {len(opus_data)}, report_time: {timestamp}"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# Report without audio (text only)
|
# Report without audio (text only)
|
||||||
conn.report_queue.put((2, clean_text, None, int(time.time()), None))
|
conn.report_queue.put((2, clean_text, None, timestamp, None))
|
||||||
conn.logger.bind(tag=TAG).debug(
|
conn.logger.bind(tag=TAG).debug(
|
||||||
f"TTS data enqueued: agent_id={conn.agent_id}, no audio"
|
f"TTS data enqueued: agent_id={conn.agent_id}, no audio, report_time: {timestamp}"
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
conn.logger.bind(tag=TAG).error(f"Failed to enqueue TTS report: {text}, {e}")
|
conn.logger.bind(tag=TAG).error(f"Failed to enqueue TTS report: {text}, {e}")
|
||||||
|
|
||||||
|
|
||||||
def enqueue_asr_report(conn, text, opus_data, attachments=None):
|
def enqueue_asr_report(conn, text, opus_data, attachments=None, report_time=None):
|
||||||
"""Enqueue ASR data for reporting (User message)
|
"""Enqueue ASR data for reporting (User message)
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
conn: Connection object
|
conn: Connection object
|
||||||
text: Recognized text
|
text: Recognized text
|
||||||
opus_data: Opus audio data (list of opus packets)
|
opus_data: Opus audio data (list of opus packets)
|
||||||
|
attachments: Optional list of attachments (images, files)
|
||||||
|
report_time: Timestamp when message actually occurred (for correct ordering)
|
||||||
"""
|
"""
|
||||||
# Check if reporting is enabled for live-agent-api mode
|
# Check if reporting is enabled for live-agent-api mode
|
||||||
if not conn.read_config_from_live_agent_api or conn.need_bind or not conn.report_asr_enable:
|
if not conn.read_config_from_live_agent_api or conn.need_bind or not conn.report_asr_enable:
|
||||||
|
|
@ -161,20 +142,23 @@ def enqueue_asr_report(conn, text, opus_data, attachments=None):
|
||||||
if conn.chat_history_conf == 0:
|
if conn.chat_history_conf == 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# Use provided report_time or current time
|
||||||
|
timestamp = report_time if report_time is not None else int(time.time())
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Use connection's queue, pass text, audio data, and attachments
|
# Use connection's queue, pass text, audio data, and attachments
|
||||||
# Queue format: (role, text, opus_data, timestamp, attachments)
|
# Queue format: (role, text, opus_data, timestamp, attachments)
|
||||||
if conn.chat_history_conf == 2:
|
if conn.chat_history_conf == 2:
|
||||||
# Report with audio
|
# Report with audio
|
||||||
conn.report_queue.put((1, text, opus_data, int(time.time()), attachments))
|
conn.report_queue.put((1, text, opus_data, timestamp, attachments))
|
||||||
conn.logger.bind(tag=TAG).debug(
|
conn.logger.bind(tag=TAG).debug(
|
||||||
f"ASR data enqueued: agent_id={conn.agent_id}, audio packets: {len(opus_data)}, attachments: {len(attachments) if attachments else 0}"
|
f"ASR data enqueued: agent_id={conn.agent_id}, audio packets: {len(opus_data)}, attachments: {len(attachments) if attachments else 0}, report_time: {timestamp}"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# Report without audio (text only, but may have attachments)
|
# Report without audio (text only, but may have attachments)
|
||||||
conn.report_queue.put((1, text, None, int(time.time()), attachments))
|
conn.report_queue.put((1, text, None, timestamp, attachments))
|
||||||
conn.logger.bind(tag=TAG).debug(
|
conn.logger.bind(tag=TAG).debug(
|
||||||
f"ASR data enqueued: agent_id={conn.agent_id}, no audio, attachments: {len(attachments) if attachments else 0}"
|
f"ASR data enqueued: agent_id={conn.agent_id}, no audio, attachments: {len(attachments) if attachments else 0}, report_time: {timestamp}"
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
conn.logger.bind(tag=TAG).debug(f"Failed to enqueue ASR report: {text}, {e}")
|
conn.logger.bind(tag=TAG).debug(f"Failed to enqueue ASR report: {text}, {e}")
|
||||||
|
|
|
||||||
|
|
@ -3,15 +3,20 @@ import time
|
||||||
import asyncio
|
import asyncio
|
||||||
from core.utils import textUtils
|
from core.utils import textUtils
|
||||||
from core.utils.util import audio_to_data
|
from core.utils.util import audio_to_data
|
||||||
from core.providers.tts.dto.dto import SentenceType
|
from core.providers.tts.dto.dto import (
|
||||||
|
SentenceType,
|
||||||
|
MessageTag,
|
||||||
|
)
|
||||||
|
from core.utils.textUtils import strip_emotion_tags
|
||||||
|
from core.utils.opus import pack_opus_with_header
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
|
|
||||||
async def sendAudioMessage(conn, sentenceType, audios, text):
|
async def sendAudioMessage(conn, sentenceType, audios, text, message_tag=MessageTag.NORMAL):
|
||||||
if conn.tts.tts_audio_first_sentence:
|
if conn.tts.tts_audio_first_sentence:
|
||||||
conn.tts.tts_audio_first_sentence = False
|
conn.tts.tts_audio_first_sentence = False
|
||||||
await send_tts_message(conn, "start", None)
|
await send_tts_message(conn, "start", None, message_tag)
|
||||||
|
|
||||||
# 记录首句 TTS 播放时间(端到端延迟的终点)
|
# 记录首句 TTS 播放时间(端到端延迟的终点)
|
||||||
first_audio_time = time.time() * 1000
|
first_audio_time = time.time() * 1000
|
||||||
|
|
@ -34,16 +39,16 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
|
||||||
)
|
)
|
||||||
|
|
||||||
if sentenceType == SentenceType.FIRST:
|
if sentenceType == SentenceType.FIRST:
|
||||||
await send_tts_message(conn, "sentence_start", text)
|
await send_tts_message(conn, "sentence_start", text, message_tag)
|
||||||
|
|
||||||
await sendAudio(conn, audios)
|
await sendAudio(conn, audios, message_tag=message_tag)
|
||||||
# 发送句子开始消息
|
# 发送句子开始消息
|
||||||
if sentenceType is not SentenceType.MIDDLE:
|
if sentenceType is not SentenceType.MIDDLE:
|
||||||
conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}")
|
conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}")
|
||||||
|
|
||||||
# 发送结束消息(如果是最后一个文本)
|
# 发送结束消息(如果是最后一个文本)
|
||||||
if conn.llm_finish_task and sentenceType == SentenceType.LAST:
|
if conn.llm_finish_task and sentenceType == SentenceType.LAST:
|
||||||
await send_tts_message(conn, "stop", None)
|
await send_tts_message(conn, "stop", None, message_tag)
|
||||||
conn.client_is_speaking = False
|
conn.client_is_speaking = False
|
||||||
if conn.close_after_chat:
|
if conn.close_after_chat:
|
||||||
await conn.close()
|
await conn.close()
|
||||||
|
|
@ -95,9 +100,15 @@ async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence):
|
||||||
complete_packet = bytes(header) + opus_packet
|
complete_packet = bytes(header) + opus_packet
|
||||||
await conn.websocket.send(complete_packet)
|
await conn.websocket.send(complete_packet)
|
||||||
|
|
||||||
|
async def _send_audio_with_header(conn, audios, message_tag=MessageTag.NORMAL):
|
||||||
|
if audios is None or len(audios) == 0:
|
||||||
|
return
|
||||||
|
complete_packet = pack_opus_with_header(audios, message_tag)
|
||||||
|
await conn.websocket.send(complete_packet)
|
||||||
|
|
||||||
|
|
||||||
# 播放音频
|
# 播放音频
|
||||||
async def sendAudio(conn, audios, frame_duration=60):
|
async def sendAudio(conn, audios, frame_duration=60, message_tag=MessageTag.NORMAL):
|
||||||
"""
|
"""
|
||||||
发送单个opus包,支持流控
|
发送单个opus包,支持流控
|
||||||
Args:
|
Args:
|
||||||
|
|
@ -157,7 +168,7 @@ async def sendAudio(conn, audios, frame_duration=60):
|
||||||
await _send_to_mqtt_gateway(conn, audios, timestamp, sequence)
|
await _send_to_mqtt_gateway(conn, audios, timestamp, sequence)
|
||||||
else:
|
else:
|
||||||
# 直接发送opus数据包,不添加头部
|
# 直接发送opus数据包,不添加头部
|
||||||
await conn.websocket.send(audios)
|
await _send_audio_with_header(conn, audios, message_tag)
|
||||||
|
|
||||||
# 更新流控状态
|
# 更新流控状态
|
||||||
flow_control["packet_count"] += 1
|
flow_control["packet_count"] += 1
|
||||||
|
|
@ -180,7 +191,7 @@ async def sendAudio(conn, audios, frame_duration=60):
|
||||||
await _send_to_mqtt_gateway(conn, audios[i], timestamp, sequence)
|
await _send_to_mqtt_gateway(conn, audios[i], timestamp, sequence)
|
||||||
else:
|
else:
|
||||||
# 直接发送预缓冲包,不添加头部
|
# 直接发送预缓冲包,不添加头部
|
||||||
await conn.websocket.send(audios[i])
|
await _send_audio_with_header(conn, audios[i], message_tag)
|
||||||
remaining_audios = audios[pre_buffer_frames:]
|
remaining_audios = audios[pre_buffer_frames:]
|
||||||
|
|
||||||
# 播放剩余音频帧
|
# 播放剩余音频帧
|
||||||
|
|
@ -212,18 +223,26 @@ async def sendAudio(conn, audios, frame_duration=60):
|
||||||
await _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence)
|
await _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence)
|
||||||
else:
|
else:
|
||||||
# 直接发送opus数据包,不添加头部
|
# 直接发送opus数据包,不添加头部
|
||||||
await conn.websocket.send(opus_packet)
|
await _send_audio_with_header(conn, opus_packet, message_tag)
|
||||||
|
|
||||||
play_position += frame_duration
|
play_position += frame_duration
|
||||||
|
|
||||||
|
|
||||||
async def send_tts_message(conn, state, text=None):
|
async def send_tts_message(conn, state, text=None, message_tag=MessageTag.NORMAL):
|
||||||
"""发送 TTS 状态消息"""
|
"""发送 TTS 状态消息"""
|
||||||
if text is None and state == "sentence_start":
|
if text is None and state == "sentence_start":
|
||||||
return
|
return
|
||||||
message = {"type": "tts", "state": state, "session_id": conn.session_id}
|
|
||||||
|
message = {
|
||||||
|
"type": "tts",
|
||||||
|
"state": state,
|
||||||
|
"session_id": conn.session_id,
|
||||||
|
"message_tag": message_tag.value,
|
||||||
|
}
|
||||||
if text is not None:
|
if text is not None:
|
||||||
message["text"] = textUtils.check_emoji(text)
|
text = textUtils.check_emoji(text)
|
||||||
|
text = strip_emotion_tags(text)
|
||||||
|
message["text"] = text
|
||||||
|
|
||||||
# TTS播放结束
|
# TTS播放结束
|
||||||
if state == "stop":
|
if state == "stop":
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry
|
from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry
|
||||||
from core.handle.textMessageProcessor import TextMessageProcessor
|
from core.handle.textMessageProcessor import TextMessageProcessor
|
||||||
|
from config.logger import setup_logging
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
logger = setup_logging()
|
||||||
|
|
||||||
# 全局处理器注册表
|
# 全局处理器注册表
|
||||||
message_registry = TextMessageHandlerRegistry()
|
message_registry = TextMessageHandlerRegistry()
|
||||||
|
|
@ -11,4 +13,5 @@ message_processor = TextMessageProcessor(message_registry)
|
||||||
|
|
||||||
async def handleTextMessage(conn, message):
|
async def handleTextMessage(conn, message):
|
||||||
"""处理文本消息"""
|
"""处理文本消息"""
|
||||||
|
logger.bind(tag=TAG).info(f"收到文本消息: {message}")
|
||||||
await message_processor.process_message(conn, message)
|
await message_processor.process_message(conn, message)
|
||||||
|
|
|
||||||
|
|
@ -101,22 +101,26 @@ class ListenTextMessageHandler(TextMessageHandler):
|
||||||
conn.client_is_speaking = False
|
conn.client_is_speaking = False
|
||||||
elif is_wakeup_words:
|
elif is_wakeup_words:
|
||||||
conn.just_woken_up = True
|
conn.just_woken_up = True
|
||||||
|
# Record timestamp for correct message ordering
|
||||||
|
report_time = int(time.time())
|
||||||
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
||||||
enqueue_asr_report(conn, "嘿,你好呀", [])
|
enqueue_asr_report(conn, "嘿,你好呀", [], report_time=report_time)
|
||||||
await startToChat(conn, "嘿,你好呀")
|
await startToChat(conn, "嘿,你好呀")
|
||||||
else:
|
else:
|
||||||
# check if there are attachments(eg. images, files) in text mode
|
# check if there are attachments(eg. images, files) in text mode
|
||||||
attachments = msg_json.get("attachments", [])
|
attachments = msg_json.get("attachments", [])
|
||||||
|
# Record timestamp for correct message ordering
|
||||||
|
report_time = int(time.time())
|
||||||
|
|
||||||
if attachments:
|
if attachments:
|
||||||
# build multimodal content
|
# build multimodal content
|
||||||
multimodal_content = build_multimodal_content(original_text, attachments)
|
multimodal_content = build_multimodal_content(original_text, attachments)
|
||||||
# report text data with attachments
|
# report text data with attachments
|
||||||
enqueue_asr_report(conn, original_text, [], attachments)
|
enqueue_asr_report(conn, original_text, [], attachments, report_time=report_time)
|
||||||
# use multimodal content to chat
|
# use multimodal content to chat
|
||||||
await startToChat(conn, original_text, multimodal_content)
|
await startToChat(conn, original_text, multimodal_content)
|
||||||
else:
|
else:
|
||||||
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
|
||||||
enqueue_asr_report(conn, original_text, [])
|
enqueue_asr_report(conn, original_text, [], report_time=report_time)
|
||||||
# 否则需要LLM对文字内容进行答复
|
# 否则需要LLM对文字内容进行答复
|
||||||
await startToChat(conn, original_text)
|
await startToChat(conn, original_text)
|
||||||
|
|
@ -178,9 +178,12 @@ class ASRProviderBase(ABC):
|
||||||
# 构建包含说话人信息的JSON字符串
|
# 构建包含说话人信息的JSON字符串
|
||||||
enhanced_text = self._build_enhanced_text(raw_text, speaker_name)
|
enhanced_text = self._build_enhanced_text(raw_text, speaker_name)
|
||||||
|
|
||||||
|
# Record the timestamp when ASR completed (for correct message ordering)
|
||||||
|
asr_report_time = int(time.time())
|
||||||
|
|
||||||
# 使用自定义模块进行上报
|
# 使用自定义模块进行上报
|
||||||
await startToChat(conn, enhanced_text)
|
await startToChat(conn, enhanced_text)
|
||||||
enqueue_asr_report(conn, enhanced_text, asr_audio_task)
|
enqueue_asr_report(conn, enhanced_text, asr_audio_task, report_time=asr_report_time)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
|
logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import queue
|
||||||
import asyncio
|
import asyncio
|
||||||
import threading
|
import threading
|
||||||
import traceback
|
import traceback
|
||||||
|
from typing import Optional
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from core.utils import p3
|
from core.utils import p3
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
@ -15,6 +16,7 @@ from abc import ABC, abstractmethod
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.utils.tts import MarkdownCleaner
|
from core.utils.tts import MarkdownCleaner
|
||||||
from core.utils.output_counter import add_device_output
|
from core.utils.output_counter import add_device_output
|
||||||
|
from core.utils.opus import pack_opus_with_header
|
||||||
from core.handle.reportHandle import enqueue_tts_report
|
from core.handle.reportHandle import enqueue_tts_report
|
||||||
from core.handle.sendAudioHandle import sendAudioMessage
|
from core.handle.sendAudioHandle import sendAudioMessage
|
||||||
from core.utils.util import audio_bytes_to_data_stream, audio_to_data_stream
|
from core.utils.util import audio_bytes_to_data_stream, audio_to_data_stream
|
||||||
|
|
@ -23,6 +25,8 @@ from core.providers.tts.dto.dto import (
|
||||||
SentenceType,
|
SentenceType,
|
||||||
ContentType,
|
ContentType,
|
||||||
InterfaceType,
|
InterfaceType,
|
||||||
|
TTSAudioDTO,
|
||||||
|
MessageTag,
|
||||||
)
|
)
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
@ -39,10 +43,12 @@ class TTSProviderBase(ABC):
|
||||||
self.delete_audio_file = delete_audio_file
|
self.delete_audio_file = delete_audio_file
|
||||||
self.audio_file_type = "wav"
|
self.audio_file_type = "wav"
|
||||||
self.output_file = config.get("output_dir", "tmp/")
|
self.output_file = config.get("output_dir", "tmp/")
|
||||||
self.tts_text_queue = queue.Queue()
|
self.tts_text_queue = queue.Queue[TTSMessageDTO]()
|
||||||
self.tts_audio_queue = queue.Queue()
|
# TODO: for long-term, we need to use TTSAudioDTO instead of tuple[SentenceType, Optional[bytes], Optional[str]]
|
||||||
|
self.tts_audio_queue = queue.Queue[TTSAudioDTO | tuple[SentenceType, Optional[bytes], Optional[str]]]()
|
||||||
self.tts_audio_first_sentence = True
|
self.tts_audio_first_sentence = True
|
||||||
self.before_stop_play_files = []
|
self.before_stop_play_files = []
|
||||||
|
self._message_tag = MessageTag.NORMAL
|
||||||
|
|
||||||
self.tts_text_buff = []
|
self.tts_text_buff = []
|
||||||
self.punctuations = (
|
self.punctuations = (
|
||||||
|
|
@ -83,7 +89,12 @@ class TTSProviderBase(ABC):
|
||||||
|
|
||||||
def handle_opus(self, opus_data: bytes):
|
def handle_opus(self, opus_data: bytes):
|
||||||
logger.bind(tag=TAG).debug(f"推送数据到队列里面帧数~~ {len(opus_data)}")
|
logger.bind(tag=TAG).debug(f"推送数据到队列里面帧数~~ {len(opus_data)}")
|
||||||
self.tts_audio_queue.put((SentenceType.MIDDLE, opus_data, None))
|
self.tts_audio_queue.put(TTSAudioDTO(
|
||||||
|
sentence_type=SentenceType.MIDDLE,
|
||||||
|
audio_data=opus_data,
|
||||||
|
text=None,
|
||||||
|
message_tag=self._message_tag,
|
||||||
|
))
|
||||||
|
|
||||||
def handle_audio_file(self, file_audio: bytes, text):
|
def handle_audio_file(self, file_audio: bytes, text):
|
||||||
self.before_stop_play_files.append((file_audio, text))
|
self.before_stop_play_files.append((file_audio, text))
|
||||||
|
|
@ -331,9 +342,22 @@ class TTSProviderBase(ABC):
|
||||||
text = None
|
text = None
|
||||||
try:
|
try:
|
||||||
try:
|
try:
|
||||||
sentence_type, audio_datas, text = self.tts_audio_queue.get(
|
tts_audio_message = self.tts_audio_queue.get(
|
||||||
timeout=0.1
|
timeout=0.1
|
||||||
)
|
)
|
||||||
|
if isinstance(tts_audio_message, TTSAudioDTO):
|
||||||
|
sentence_type = tts_audio_message.sentence_type
|
||||||
|
audio_datas = tts_audio_message.audio_data
|
||||||
|
text = tts_audio_message.text
|
||||||
|
message_tag = tts_audio_message.message_tag
|
||||||
|
elif isinstance(tts_audio_message, tuple):
|
||||||
|
sentence_type = tts_audio_message[0]
|
||||||
|
audio_datas = tts_audio_message[1]
|
||||||
|
text = tts_audio_message[2]
|
||||||
|
message_tag = MessageTag.NORMAL # tuple format doesn't have message_tag
|
||||||
|
else:
|
||||||
|
logger.bind(tag=TAG).warning(f"Unknown tts_audio_message type: {type(tts_audio_message)}")
|
||||||
|
continue
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
if self.conn.stop_event.is_set():
|
if self.conn.stop_event.is_set():
|
||||||
break
|
break
|
||||||
|
|
@ -349,12 +373,13 @@ class TTSProviderBase(ABC):
|
||||||
if sentence_type is not SentenceType.MIDDLE:
|
if sentence_type is not SentenceType.MIDDLE:
|
||||||
# 上报TTS数据
|
# 上报TTS数据
|
||||||
if enqueue_text is not None and enqueue_audio is not None:
|
if enqueue_text is not None and enqueue_audio is not None:
|
||||||
enqueue_tts_report(self.conn, enqueue_text, enqueue_audio)
|
enqueue_tts_report(self.conn, enqueue_text, enqueue_audio, message_tag)
|
||||||
enqueue_audio = []
|
enqueue_audio = []
|
||||||
enqueue_text = text
|
enqueue_text = text
|
||||||
|
|
||||||
# 收集上报音频数据
|
# 收集上报音频数据
|
||||||
if isinstance(audio_datas, bytes) and enqueue_audio is not None:
|
if isinstance(audio_datas, bytes) and enqueue_audio is not None:
|
||||||
|
audio_datas = pack_opus_with_header(audio_datas, message_tag)
|
||||||
enqueue_audio.append(audio_datas)
|
enqueue_audio.append(audio_datas)
|
||||||
|
|
||||||
# 等待上一个发送完成(保持顺序),但使用短超时避免长时间阻塞
|
# 等待上一个发送完成(保持顺序),但使用短超时避免长时间阻塞
|
||||||
|
|
@ -366,7 +391,7 @@ class TTSProviderBase(ABC):
|
||||||
|
|
||||||
# 异步发送音频(不阻塞等待)
|
# 异步发送音频(不阻塞等待)
|
||||||
last_send_future = asyncio.run_coroutine_threadsafe(
|
last_send_future = asyncio.run_coroutine_threadsafe(
|
||||||
sendAudioMessage(self.conn, sentence_type, audio_datas, text),
|
sendAudioMessage(self.conn, sentence_type, audio_datas, text, message_tag),
|
||||||
self.conn.loop,
|
self.conn.loop,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -377,6 +402,14 @@ class TTSProviderBase(ABC):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"audio_play_priority_thread: {text} {e}")
|
logger.bind(tag=TAG).error(f"audio_play_priority_thread: {text} {e}")
|
||||||
|
|
||||||
|
# when connection session is closing, report the remaining TTS data(latest message)
|
||||||
|
if enqueue_text is not None and enqueue_audio is not None and len(enqueue_audio) > 0:
|
||||||
|
try:
|
||||||
|
enqueue_tts_report(self.conn, enqueue_text, enqueue_audio, message_tag)
|
||||||
|
logger.bind(tag=TAG).info(f"connection closing, report the remaining TTS data: {enqueue_text}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).warning(f"connection closing, report the remaining TTS data failed: {e}")
|
||||||
|
|
||||||
async def start_session(self, session_id):
|
async def start_session(self, session_id):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
@ -461,9 +494,19 @@ class TTSProviderBase(ABC):
|
||||||
|
|
||||||
def _process_before_stop_play_files(self):
|
def _process_before_stop_play_files(self):
|
||||||
for audio_datas, text in self.before_stop_play_files:
|
for audio_datas, text in self.before_stop_play_files:
|
||||||
self.tts_audio_queue.put((SentenceType.MIDDLE, audio_datas, text))
|
self.tts_audio_queue.put(TTSAudioDTO(
|
||||||
|
sentence_type=SentenceType.MIDDLE,
|
||||||
|
audio_data=audio_datas,
|
||||||
|
text=text,
|
||||||
|
message_tag=self._message_tag,
|
||||||
|
))
|
||||||
self.before_stop_play_files.clear()
|
self.before_stop_play_files.clear()
|
||||||
self.tts_audio_queue.put((SentenceType.LAST, [], None))
|
self.tts_audio_queue.put(TTSAudioDTO(
|
||||||
|
sentence_type=SentenceType.LAST,
|
||||||
|
audio_data=[],
|
||||||
|
text=None,
|
||||||
|
message_tag=self._message_tag,
|
||||||
|
))
|
||||||
|
|
||||||
def _process_remaining_text_stream(
|
def _process_remaining_text_stream(
|
||||||
self, opus_handler: Callable[[bytes], None] = None
|
self, opus_handler: Callable[[bytes], None] = None
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from typing import Union, Optional
|
from typing import Union, Optional
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
|
||||||
class SentenceType(Enum):
|
class SentenceType(Enum):
|
||||||
|
|
@ -22,6 +23,11 @@ class InterfaceType(Enum):
|
||||||
SINGLE_STREAM = "SINGLE_STREAM" # 单流式
|
SINGLE_STREAM = "SINGLE_STREAM" # 单流式
|
||||||
NON_STREAM = "NON_STREAM" # 非流式
|
NON_STREAM = "NON_STREAM" # 非流式
|
||||||
|
|
||||||
|
class MessageTag(Enum):
|
||||||
|
NORMAL = 0
|
||||||
|
OPENING = 1
|
||||||
|
CLOSING = 2
|
||||||
|
|
||||||
|
|
||||||
class TTSMessageDTO:
|
class TTSMessageDTO:
|
||||||
def __init__(
|
def __init__(
|
||||||
|
|
@ -35,9 +41,27 @@ class TTSMessageDTO:
|
||||||
content_detail: Optional[str] = None,
|
content_detail: Optional[str] = None,
|
||||||
# 如果内容类型为文件,则需要传入文件路径
|
# 如果内容类型为文件,则需要传入文件路径
|
||||||
content_file: Optional[str] = None,
|
content_file: Optional[str] = None,
|
||||||
|
# message tag: identify the tag of the message
|
||||||
|
message_tag: MessageTag = MessageTag.NORMAL,
|
||||||
):
|
):
|
||||||
self.sentence_id = sentence_id
|
self.sentence_id = sentence_id
|
||||||
self.sentence_type = sentence_type
|
self.sentence_type = sentence_type
|
||||||
self.content_type = content_type
|
self.content_type = content_type
|
||||||
self.content_detail = content_detail
|
self.content_detail = content_detail
|
||||||
self.content_file = content_file
|
self.content_file = content_file
|
||||||
|
self.message_tag = message_tag
|
||||||
|
|
||||||
|
class TTSAudioDTO:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
sentence_type: SentenceType,
|
||||||
|
audio_data: Optional[bytes] = None,
|
||||||
|
text: Optional[str] = None,
|
||||||
|
message_tag: MessageTag = MessageTag.NORMAL,
|
||||||
|
report_time: Optional[int] = None,
|
||||||
|
):
|
||||||
|
self.sentence_type = sentence_type
|
||||||
|
self.audio_data = audio_data
|
||||||
|
self.text = text
|
||||||
|
self.message_tag = message_tag
|
||||||
|
self.report_time = report_time
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ Reference: https://docs.fish.audio/api-reference/endpoint/websocket/tts-live
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
import queue
|
import queue
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
@ -22,8 +23,18 @@ from core.utils.tts import MarkdownCleaner
|
||||||
from core.utils import opus_encoder_utils
|
from core.utils import opus_encoder_utils
|
||||||
from core.utils.util import check_model_key
|
from core.utils.util import check_model_key
|
||||||
from core.providers.tts.base import TTSProviderBase
|
from core.providers.tts.base import TTSProviderBase
|
||||||
from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
|
from core.providers.tts.dto.dto import (
|
||||||
|
SentenceType,
|
||||||
|
ContentType,
|
||||||
|
InterfaceType,
|
||||||
|
TTSAudioDTO,
|
||||||
|
MessageTag,
|
||||||
|
)
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
from core.utils.opus import pack_opus_with_header
|
||||||
|
from core.handle.reportHandle import enqueue_tts_report
|
||||||
|
from core.handle.sendAudioHandle import sendAudioMessage
|
||||||
|
from core.utils.output_counter import add_device_output
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
@ -162,6 +173,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
self._first_sent = False
|
self._first_sent = False
|
||||||
self._session_text_buffer = []
|
self._session_text_buffer = []
|
||||||
self.conn._latency_tts_first_text_time = None # Reset TTS input time
|
self.conn._latency_tts_first_text_time = None # Reset TTS input time
|
||||||
|
self._message_tag = message.message_tag
|
||||||
|
|
||||||
elif self.conn.client_abort:
|
elif self.conn.client_abort:
|
||||||
# ========== Interruption ==========
|
# ========== Interruption ==========
|
||||||
|
|
@ -247,6 +259,89 @@ class TTSProvider(TTSProviderBase):
|
||||||
f"stack: {traceback.format_exc()}"
|
f"stack: {traceback.format_exc()}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _audio_play_priority_thread(self):
|
||||||
|
# the buffer of text and audio that needs to be reported
|
||||||
|
enqueue_text = None
|
||||||
|
enqueue_audio = None
|
||||||
|
enqueue_report_time = None # timestamp when TTS session started (for correct ordering)
|
||||||
|
# 用于跟踪上一个发送任务,确保顺序但不阻塞
|
||||||
|
last_send_future = None
|
||||||
|
|
||||||
|
while not self.conn.stop_event.is_set():
|
||||||
|
text = None
|
||||||
|
report_time = None
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
tts_audio_message = self.tts_audio_queue.get_nowait()
|
||||||
|
|
||||||
|
if isinstance(tts_audio_message, TTSAudioDTO):
|
||||||
|
sentence_type = tts_audio_message.sentence_type
|
||||||
|
audio_datas = tts_audio_message.audio_data
|
||||||
|
text = tts_audio_message.text
|
||||||
|
message_tag = tts_audio_message.message_tag
|
||||||
|
report_time = tts_audio_message.report_time
|
||||||
|
elif isinstance(tts_audio_message, tuple):
|
||||||
|
sentence_type = tts_audio_message[0]
|
||||||
|
audio_datas = tts_audio_message[1]
|
||||||
|
text = tts_audio_message[2]
|
||||||
|
message_tag = MessageTag.NORMAL # tuple format doesn't have message_tag
|
||||||
|
report_time = None
|
||||||
|
else:
|
||||||
|
logger.bind(tag=TAG).warning(f"Unknown tts_audio_message type: {type(tts_audio_message)}")
|
||||||
|
continue
|
||||||
|
except queue.Empty:
|
||||||
|
if self.conn.stop_event.is_set():
|
||||||
|
break
|
||||||
|
continue
|
||||||
|
|
||||||
|
if self.conn.client_abort:
|
||||||
|
logger.bind(tag=TAG).debug("received interruption, skip current audio data")
|
||||||
|
enqueue_text, enqueue_audio, enqueue_report_time = None, [], None
|
||||||
|
last_send_future = None
|
||||||
|
continue
|
||||||
|
|
||||||
|
# report TTS data when next text starts or session ends
|
||||||
|
if sentence_type is not SentenceType.MIDDLE:
|
||||||
|
# report TTS data with the recorded timestamp
|
||||||
|
if enqueue_text is not None and enqueue_audio is not None:
|
||||||
|
enqueue_tts_report(self.conn, enqueue_text, enqueue_audio, message_tag, enqueue_report_time)
|
||||||
|
enqueue_audio = []
|
||||||
|
enqueue_text = text
|
||||||
|
enqueue_report_time = report_time # save timestamp from FIRST for later reporting
|
||||||
|
|
||||||
|
# collect TTS audio data for reporting
|
||||||
|
if isinstance(audio_datas, bytes) and enqueue_audio is not None:
|
||||||
|
audio_datas = pack_opus_with_header(audio_datas, message_tag)
|
||||||
|
enqueue_audio.append(audio_datas)
|
||||||
|
|
||||||
|
# wait for the previous send to complete (maintain order) but use short timeout to avoid long blocking
|
||||||
|
if last_send_future is not None:
|
||||||
|
try:
|
||||||
|
last_send_future.result(timeout=5.0)
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).warning(f"previous audio send timeout or failed: {e}")
|
||||||
|
|
||||||
|
# async send audio (without blocking wait)
|
||||||
|
last_send_future = asyncio.run_coroutine_threadsafe(
|
||||||
|
sendAudioMessage(self.conn, sentence_type, audio_datas, text, message_tag),
|
||||||
|
self.conn.loop,
|
||||||
|
)
|
||||||
|
|
||||||
|
# record output and report
|
||||||
|
if self.conn.max_output_size > 0 and text:
|
||||||
|
add_device_output(self.conn.headers.get("device-id"), len(text))
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"audio_play_priority_thread: {text} {e}")
|
||||||
|
|
||||||
|
# when connection session is closing, report the remaining TTS data(latest message)
|
||||||
|
if enqueue_text is not None and enqueue_audio is not None and len(enqueue_audio) > 0:
|
||||||
|
try:
|
||||||
|
enqueue_tts_report(self.conn, enqueue_text, enqueue_audio, message_tag, enqueue_report_time)
|
||||||
|
logger.bind(tag=TAG).info(f"connection closing, report the remaining TTS data: {enqueue_text}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).warning(f"connection closing, report the remaining TTS data failed: {e}")
|
||||||
|
|
||||||
async def close(self):
|
async def close(self):
|
||||||
"""Clean up WebSocket resources"""
|
"""Clean up WebSocket resources"""
|
||||||
self._session_active = False
|
self._session_active = False
|
||||||
|
|
@ -294,8 +389,17 @@ class TTSProvider(TTSProviderBase):
|
||||||
# 这样后续音频通过 MIDDLE 累积时,enqueue_audio 不会被清空
|
# 这样后续音频通过 MIDDLE 累积时,enqueue_audio 不会被清空
|
||||||
if not self._first_sent:
|
if not self._first_sent:
|
||||||
self._first_sent = True
|
self._first_sent = True
|
||||||
|
# Record the timestamp when TTS starts (for correct message ordering)
|
||||||
|
self._message_report_time = int(time.time())
|
||||||
report_text = ''.join(self._session_text_buffer) if self._session_text_buffer else None
|
report_text = ''.join(self._session_text_buffer) if self._session_text_buffer else None
|
||||||
self.tts_audio_queue.put((SentenceType.FIRST, None, report_text))
|
|
||||||
|
self.tts_audio_queue.put(TTSAudioDTO(
|
||||||
|
sentence_type=SentenceType.FIRST,
|
||||||
|
audio_data=None,
|
||||||
|
text=report_text,
|
||||||
|
message_tag=self._message_tag,
|
||||||
|
report_time=self._message_report_time,
|
||||||
|
))
|
||||||
|
|
||||||
# PCM -> Opus conversion
|
# PCM -> Opus conversion
|
||||||
self.opus_encoder.encode_pcm_to_opus_stream(
|
self.opus_encoder.encode_pcm_to_opus_stream(
|
||||||
|
|
@ -318,8 +422,12 @@ class TTSProvider(TTSProviderBase):
|
||||||
|
|
||||||
# 发送 LAST 触发客户端 stop 和最终上报
|
# 发送 LAST 触发客户端 stop 和最终上报
|
||||||
# 不再发送 FIRST,避免清空之前累积的音频
|
# 不再发送 FIRST,避免清空之前累积的音频
|
||||||
self.tts_audio_queue.put((SentenceType.LAST, None, None))
|
self.tts_audio_queue.put(TTSAudioDTO(
|
||||||
|
sentence_type=SentenceType.LAST,
|
||||||
|
audio_data=None,
|
||||||
|
text=None,
|
||||||
|
message_tag=self._message_tag,
|
||||||
|
))
|
||||||
# 清理状态
|
# 清理状态
|
||||||
self._session_text_buffer = []
|
self._session_text_buffer = []
|
||||||
self.conn.tts_MessageText = None
|
self.conn.tts_MessageText = None
|
||||||
|
|
|
||||||
10
main/xiaozhi-server/core/utils/opus.py
Normal file
10
main/xiaozhi-server/core/utils/opus.py
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
from core.providers.tts.dto.dto import MessageTag
|
||||||
|
|
||||||
|
def pack_opus_with_header(opus_data: bytes, message_tag: MessageTag = MessageTag.NORMAL) -> bytes:
|
||||||
|
header = bytearray(16)
|
||||||
|
header[0] = 1 # default value is 1 for audio message
|
||||||
|
header[1] = message_tag.value
|
||||||
|
header[2:6] = len(opus_data).to_bytes(4, "big")
|
||||||
|
# 3-15 bytes is reserved for future use, currently not used
|
||||||
|
complete_packet = bytes(header) + opus_data
|
||||||
|
return complete_packet
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
from urllib3 import Retry
|
from urllib3 import Retry
|
||||||
|
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
EMOJI_MAP = {
|
EMOJI_MAP = {
|
||||||
"😂": "laughing",
|
"😂": "laughing",
|
||||||
|
|
@ -115,3 +116,34 @@ def is_emoji(char):
|
||||||
def check_emoji(text):
|
def check_emoji(text):
|
||||||
"""去除文本中的所有emoji表情"""
|
"""去除文本中的所有emoji表情"""
|
||||||
return ''.join(char for char in text if not is_emoji(char) and char != "\n")
|
return ''.join(char for char in text if not is_emoji(char) and char != "\n")
|
||||||
|
|
||||||
|
# Regex pattern to match emotion tags anywhere in text
|
||||||
|
# Format: (emotion) e.g., "(happy)", "(sincere)", "(curious)"
|
||||||
|
# Matches: optional whitespace + (word) + optional whitespace
|
||||||
|
EMOTION_TAG_PATTERN = re.compile(r'\s*\([a-zA-Z_]+\)\s*')
|
||||||
|
|
||||||
|
|
||||||
|
def strip_emotion_tags(text: str) -> str:
|
||||||
|
"""
|
||||||
|
Remove all emotion tags from TTS text.
|
||||||
|
|
||||||
|
Emotion tags are in format: (emotion) typically at the start of sentences.
|
||||||
|
Examples:
|
||||||
|
"(happy) Hello!" -> "Hello!"
|
||||||
|
"(sincere) That's great. (curious) What next?" -> "That's great. What next?"
|
||||||
|
"Hello (happy) world" -> "Hello world"
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Text with potential emotion tags
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Text with all emotion tags removed
|
||||||
|
"""
|
||||||
|
if not text:
|
||||||
|
return text
|
||||||
|
|
||||||
|
# Remove all emotion tags from the text
|
||||||
|
result = EMOTION_TAG_PATTERN.sub(' ', text)
|
||||||
|
# Clean up multiple spaces and trim
|
||||||
|
result = re.sub(r'\s+', ' ', result)
|
||||||
|
return result.strip()
|
||||||
|
|
@ -49,7 +49,10 @@ class WebSocketServer:
|
||||||
port = int(server_config.get("port", 8000))
|
port = int(server_config.get("port", 8000))
|
||||||
|
|
||||||
async with websockets.serve(
|
async with websockets.serve(
|
||||||
self._handle_connection, host, port, process_request=self._http_response
|
self._handle_connection, host, port, process_request=self._http_response,
|
||||||
|
ping_interval=30, # Interval between keepalive pings in seconds
|
||||||
|
ping_timeout=20, # Timeout for keepalive pings in seconds
|
||||||
|
close_timeout=10, # Timeout for closing the connection in seconds
|
||||||
):
|
):
|
||||||
await asyncio.Future()
|
await asyncio.Future()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -207,7 +207,7 @@ language: zh
|
||||||
|
|
||||||
# 结束语prompt
|
# 结束语prompt
|
||||||
end_prompt:
|
end_prompt:
|
||||||
enable: true # 是否开启结束语
|
enable: false # 是否开启结束语
|
||||||
# 结束语
|
# 结束语
|
||||||
prompt: |
|
prompt: |
|
||||||
请你以"时间过得真快"未来头,用富有感情、依依不舍的话来结束这场对话吧!
|
请你以"时间过得真快"未来头,用富有感情、依依不舍的话来结束这场对话吧!
|
||||||
|
|
|
||||||
|
|
@ -1009,20 +1009,40 @@
|
||||||
|
|
||||||
if (message.type === 'hello') {
|
if (message.type === 'hello') {
|
||||||
log(`服务器回应:${JSON.stringify(message, null, 2)}`, 'success');
|
log(`服务器回应:${JSON.stringify(message, null, 2)}`, 'success');
|
||||||
|
// Check if this is a reconnect - if opening was played before, skip it
|
||||||
|
if (openingPlayedInSession) {
|
||||||
|
skipCurrentOpening = true;
|
||||||
|
log('检测到重连,将跳过开场白', 'info');
|
||||||
|
}
|
||||||
} else if (message.type === 'tts') {
|
} else if (message.type === 'tts') {
|
||||||
// TTS状态消息
|
// TTS状态消息
|
||||||
|
const msgTag = message.message_tag !== undefined ? message.message_tag : MESSAGE_TAG.NORMAL;
|
||||||
|
const tagName = msgTag === MESSAGE_TAG.OPENING ? '[开场白]' :
|
||||||
|
msgTag === MESSAGE_TAG.CLOSING ? '[结束语]' : '';
|
||||||
|
|
||||||
if (message.state === 'start') {
|
if (message.state === 'start') {
|
||||||
log('服务器开始发送语音', 'info');
|
log(`服务器开始发送语音 ${tagName}`, 'info');
|
||||||
} else if (message.state === 'sentence_start') {
|
} else if (message.state === 'sentence_start') {
|
||||||
log(`服务器发送语音段: ${message.text}`, 'info');
|
log(`服务器发送语音段${tagName}: ${message.text}`, 'info');
|
||||||
// 添加文本到会话记录
|
// Handle opening text - skip if this is a reconnect
|
||||||
|
if (msgTag === MESSAGE_TAG.OPENING && skipCurrentOpening) {
|
||||||
|
log('跳过重复的开场白文本显示', 'debug');
|
||||||
|
} else {
|
||||||
if (message.text) {
|
if (message.text) {
|
||||||
addMessage(message.text);
|
addMessage(message.text);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
} else if (message.state === 'sentence_end') {
|
} else if (message.state === 'sentence_end') {
|
||||||
log(`语音段结束: ${message.text}`, 'info');
|
log(`语音段结束${tagName}: ${message.text}`, 'info');
|
||||||
} else if (message.state === 'stop') {
|
} else if (message.state === 'stop') {
|
||||||
log('服务器语音传输结束', 'info');
|
log('服务器语音传输结束', 'info');
|
||||||
|
// Mark opening as played after TTS completes
|
||||||
|
if (!openingPlayedInSession) {
|
||||||
|
openingPlayedInSession = true;
|
||||||
|
log('开场白播放完成,后续重连将跳过', 'debug');
|
||||||
|
}
|
||||||
|
// Reset skip flag for next session
|
||||||
|
skipCurrentOpening = false;
|
||||||
// 结束后更新UI状态
|
// 结束后更新UI状态
|
||||||
if (recordButton.disabled) {
|
if (recordButton.disabled) {
|
||||||
recordButton.disabled = false;
|
recordButton.disabled = false;
|
||||||
|
|
@ -1760,32 +1780,62 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Message tag constants (sync with server MessageTag enum)
|
||||||
|
const MESSAGE_TAG = {
|
||||||
|
NORMAL: 0,
|
||||||
|
OPENING: 1,
|
||||||
|
CLOSING: 2
|
||||||
|
};
|
||||||
|
|
||||||
|
// Track opening state across reconnections
|
||||||
|
let openingPlayedInSession = false; // Has opening been played in this page session?
|
||||||
|
let skipCurrentOpening = false; // Should we skip the current opening (on reconnect)?
|
||||||
|
|
||||||
async function handleBinaryMessage(data) {
|
async function handleBinaryMessage(data) {
|
||||||
try {
|
try {
|
||||||
let arrayBuffer;
|
let arrayBuffer;
|
||||||
// 根据数据类型进行处理
|
// Convert to ArrayBuffer based on data type
|
||||||
if (data instanceof ArrayBuffer) {
|
if (data instanceof ArrayBuffer) {
|
||||||
arrayBuffer = data;
|
arrayBuffer = data;
|
||||||
log(`收到ArrayBuffer音频数据,大小: ${data.byteLength}字节`, 'debug');
|
|
||||||
} else if (data instanceof Blob) {
|
} else if (data instanceof Blob) {
|
||||||
// 如果是Blob类型,转换为ArrayBuffer
|
|
||||||
arrayBuffer = await data.arrayBuffer();
|
arrayBuffer = await data.arrayBuffer();
|
||||||
log(`收到Blob音频数据,大小: ${arrayBuffer.byteLength}字节`, 'debug');
|
|
||||||
} else {
|
} else {
|
||||||
log(`收到未知类型的二进制数据: ${typeof data}`, 'warning');
|
log(`收到未知类型的二进制数据: ${typeof data}`, 'warning');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// 创建Uint8Array用于处理
|
|
||||||
const opusData = new Uint8Array(arrayBuffer);
|
// Parse 16-byte header + opus payload
|
||||||
if (opusData.length > 0) {
|
// Header structure:
|
||||||
// 将数据添加到缓冲队列
|
// byte 0: type (1 = audio)
|
||||||
queue.enqueue(opusData);
|
// byte 1: message_tag (0=normal, 1=opening, 2=notification)
|
||||||
} else {
|
// bytes 2-15: reserved
|
||||||
|
const HEADER_SIZE = 16;
|
||||||
|
|
||||||
|
if (arrayBuffer.byteLength <= HEADER_SIZE) {
|
||||||
log('收到空音频数据帧,可能是结束标志', 'warning');
|
log('收到空音频数据帧,可能是结束标志', 'warning');
|
||||||
// 如果正在播放,发送结束信号
|
|
||||||
if (isAudioPlaying && streamingContext) {
|
if (isAudioPlaying && streamingContext) {
|
||||||
streamingContext.endOfStream = true;
|
streamingContext.endOfStream = true;
|
||||||
}
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const headerView = new DataView(arrayBuffer);
|
||||||
|
const type = headerView.getUint8(0);
|
||||||
|
const messageTag = headerView.getUint8(1);
|
||||||
|
|
||||||
|
// Extract opus data (skip 16-byte header)
|
||||||
|
const opusData = new Uint8Array(arrayBuffer, HEADER_SIZE);
|
||||||
|
|
||||||
|
log(`收到音频数据: type=${type}, tag=${messageTag}, payload=${opusData.length}字节`, 'debug');
|
||||||
|
|
||||||
|
// Handle opening message - skip if this is a reconnect
|
||||||
|
if (messageTag === MESSAGE_TAG.OPENING && skipCurrentOpening) {
|
||||||
|
log('跳过重复的开场白音频', 'debug');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (opusData.length > 0) {
|
||||||
|
queue.enqueue(opusData);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(`处理二进制消息出错: ${error.message}`, 'error');
|
log(`处理二进制消息出错: ${error.message}`, 'error');
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue