diff --git a/main/.env.example b/main/.env.example index 783b93cc0..a6e4a2018 100644 --- a/main/.env.example +++ b/main/.env.example @@ -28,4 +28,19 @@ DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/live_agent FISH_API_KEY=your-fish-api-key OPENAI_API_KEY=your-openai-key GROQ_API_KEY=your-groq-api-key -OPENAI_MODEL= \ No newline at end of file +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 \ No newline at end of file diff --git a/main/live-agent-api/api/v1/__init__.py b/main/live-agent-api/api/v1/__init__.py index 7a470f9e7..99a3ff769 100644 --- a/main/live-agent-api/api/v1/__init__.py +++ b/main/live-agent-api/api/v1/__init__.py @@ -1,5 +1,5 @@ from fastapi import APIRouter -from api.v1 import user, templates, agents, voices, internal, files, chat, memories, devices +from api.v1 import user, templates, agents, voices, internal, files, chat, memories, devices, stt api_router = APIRouter() @@ -65,3 +65,10 @@ api_router.include_router( prefix="/devices", tags=["Devices"] ) + +# STT routes +api_router.include_router( + stt.router, + prefix="/stt", + tags=["STT"] +) diff --git a/main/live-agent-api/api/v1/agents.py b/main/live-agent-api/api/v1/agents.py index 1dc814de9..013ad4084 100644 --- a/main/live-agent-api/api/v1/agents.py +++ b/main/live-agent-api/api/v1/agents.py @@ -10,10 +10,12 @@ from services.llm_service import llm_service from utils.response import success_response from api.auth import get_current_user_id from schemas.agent import AgentResponse, BindableAgentResponse, BindableAgentListResponse +from config import get_logger import base64 -import logging from fastapi import HTTPException +import asyncio +logger = get_logger(__name__) router = APIRouter() @@ -201,7 +203,7 @@ async def generate_persona( avatar_base64 = base64.b64encode(content).decode("utf-8") avatar_media_type = avatar.content_type or "image/jpeg" except Exception as e: - logging.warning(f"Failed to process avatar: {e}") + logger.warning(f"Failed to process avatar: {e}") if mode == "optimize": # Optimize mode: streaming with SSE format, requires existing instruction @@ -220,7 +222,7 @@ async def generate_persona( # SSE format: data: \n\n yield f"data: {chunk}\n\n" 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" return StreamingResponse( @@ -238,6 +240,6 @@ async def generate_persona( ) return success_response(data=result) 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)}") diff --git a/main/live-agent-api/api/v1/chat.py b/main/live-agent-api/api/v1/chat.py index dac2e2603..93e30d14e 100644 --- a/main/live-agent-api/api/v1/chat.py +++ b/main/live-agent-api/api/v1/chat.py @@ -9,7 +9,6 @@ from infra import get_db, get_s3 from services.chat_service import chat_service from schemas.chat import ( ReportChatMessageRequest, - ChatMessage, ChatMessagesListResponse ) 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") async def get_agent_messages( 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"), include_audio: bool = Query(False, description="Load audio base64 from S3"), 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) 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) - - 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) 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) - include_audio: If True, downloads opus from S3 and returns as base64 Returns: - - messages: List of chat messages (newest first in each batch) - - next_cursor: Message ID for loading older messages (None if no more history) + - messages: List of chat messages (newest first in each batch, ordered by message_time) + - next_cursor: ISO timestamp for loading older messages (None if no more history) - has_more: Whether there are more older messages Example: @@ -76,15 +75,15 @@ async def get_agent_messages( GET /chat/agent_123/messages?limit=50 Response: { messages: [newest_msg, ..., oldest_msg_in_batch], - next_cursor: "01JD8X0000ABC", # ID of oldest message in this batch + next_cursor: "2024-01-15T10:30:00+00:00", has_more: true } # 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: { messages: [newer_old_msg, ..., older_msg], - next_cursor: "01JD8W0000XYZ", + next_cursor: "2024-01-15T09:15:00+00:00", has_more: true } diff --git a/main/live-agent-api/api/v1/stt.py b/main/live-agent-api/api/v1/stt.py new file mode 100644 index 000000000..34ad1908a --- /dev/null +++ b/main/live-agent-api/api/v1/stt.py @@ -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)) + diff --git a/main/live-agent-api/api/v1/voices.py b/main/live-agent-api/api/v1/voices.py index 1c7904018..4fdcd9076 100644 --- a/main/live-agent-api/api/v1/voices.py +++ b/main/live-agent-api/api/v1/voices.py @@ -1,5 +1,4 @@ from typing import Optional, List -from botocore.args import logger from fastapi import APIRouter, Depends, Query, Form, File, UploadFile from fastapi.responses import StreamingResponse from sqlalchemy.ext.asyncio import AsyncSession @@ -19,13 +18,11 @@ from schemas.voice import ( ) from utils.response import success_response from api.auth import get_current_user_id +from config import get_logger -import logging - +logger = get_logger(__name__) router = APIRouter() -logging.getLogger(__name__) - @router.get("/discover", summary="Get Discover Voices") async def get_discover_voices( title: Optional[str] = Query(None, description="Filter by voice title/name"), @@ -304,8 +301,7 @@ async def generate_voice_sample_text( yield chunk except Exception as e: # Error already yielded in service, just log - import logging - logging.error(f"Voice sample text generation failed: {e}") + logger.error(f"Voice sample text generation failed: {e}") return StreamingResponse( text_generator(), diff --git a/main/live-agent-api/config/__init__.py b/main/live-agent-api/config/__init__.py index f944ab23a..f08d6ec94 100644 --- a/main/live-agent-api/config/__init__.py +++ b/main/live-agent-api/config/__init__.py @@ -1,4 +1,5 @@ from .settings import Settings, settings +from .logger import setup_logging, get_logger -__all__ = ["Settings", "settings"] +__all__ = ["Settings", "settings", "setup_logging", "get_logger"] diff --git a/main/live-agent-api/config/logger.py b/main/live-agent-api/config/logger.py new file mode 100644 index 000000000..dd1b07bc8 --- /dev/null +++ b/main/live-agent-api/config/logger.py @@ -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 = ( + "{time:YYYY-MM-DD HH:mm:ss.SSS} | " + "{level: <8} | " + "{name}:{function}:{line} | " + "{message}" + ) + + # 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 + diff --git a/main/live-agent-api/config/settings.py b/main/live-agent-api/config/settings.py index 1bf15f180..db858e860 100644 --- a/main/live-agent-api/config/settings.py +++ b/main/live-agent-api/config/settings.py @@ -44,6 +44,11 @@ class Settings(BaseSettings): QUICK_PERSONA_MODEL: str = "google/gemini-2.5-flash" 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( env_file=".env", env_file_encoding="utf-8", diff --git a/main/live-agent-api/infra/__init__.py b/main/live-agent-api/infra/__init__.py index f53c69a20..1ad897ec0 100644 --- a/main/live-agent-api/infra/__init__.py +++ b/main/live-agent-api/infra/__init__.py @@ -26,6 +26,11 @@ from .openai import ( init_openai, close_openai, ) +from .groq import ( + get_groq, + init_groq, + close_groq, +) __all__ = [ # Database @@ -48,5 +53,9 @@ __all__ = [ "get_openai", "init_openai", "close_openai", + # Groq + "get_groq", + "init_groq", + "close_groq", ] diff --git a/main/live-agent-api/infra/groq.py b/main/live-agent-api/infra/groq.py new file mode 100644 index 000000000..91a1fda97 --- /dev/null +++ b/main/live-agent-api/infra/groq.py @@ -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 + diff --git a/main/live-agent-api/init_db.sql b/main/live-agent-api/init_db.sql index 627224fd6..eff283b5b 100644 --- a/main/live-agent-api/init_db.sql +++ b/main/live-agent-api/init_db.sql @@ -123,6 +123,7 @@ CREATE TABLE IF NOT EXISTS chat_messages ( agent_id VARCHAR(50) NOT NULL, role SMALLINT NOT NULL CHECK (role IN (1, 2)), 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'), CONSTRAINT fk_chat_messages_agent FOREIGN KEY (agent_id) 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); -- 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); +-- 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.) 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.role IS 'Message role: 1=user, 2=agent'; COMMENT ON COLUMN chat_messages.content IS 'JSONB array: [{"message_type": "text|audio|image|file", "message_content": "text or S3 URL"}]'; -COMMENT ON COLUMN chat_messages.created_at IS 'Message creation timestamp (UTC)'; +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 ==================== -- Device registry table diff --git a/main/live-agent-api/main.py b/main/live-agent-api/main.py index 87c682d66..b30b2f09c 100644 --- a/main/live-agent-api/main.py +++ b/main/live-agent-api/main.py @@ -3,38 +3,64 @@ from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse -from config import settings -from infra import init_db, close_db, init_s3, close_s3, init_fish_audio, close_fish_audio, init_openai, close_openai +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, init_groq, close_groq from api.v1 import api_router 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 async def lifespan(app: FastAPI): """Application lifespan events""" # Startup - print("Starting up Live Agent API...") + logger.info("Starting up Live Agent API...") await init_db() - print("Database initialized") + logger.info("Database initialized") await init_s3() - print("S3 connection initialized") + logger.info("S3 connection initialized") await init_fish_audio() - print("Fish Audio client initialized") + logger.info("Fish Audio client initialized") await init_openai() - print("OpenAI client initialized") + logger.info("OpenAI client initialized") + await init_groq() + logger.info("Groq client initialized") yield # Shutdown - print("Shutting down Live Agent API...") + logger.info("Shutting down Live Agent API...") await close_db() - print("Database connections closed") + logger.info("Database connections closed") await close_s3() - print("S3 connections closed") + logger.info("S3 connections closed") await close_fish_audio() - print("Fish Audio client closed") + logger.info("Fish Audio client closed") await close_openai() - print("OpenAI client closed") + logger.info("OpenAI client closed") + await close_groq() + logger.info("Groq client closed") # Create FastAPI application diff --git a/main/live-agent-api/migrations/add_message_time.sql b/main/live-agent-api/migrations/add_message_time.sql new file mode 100644 index 000000000..46d834830 --- /dev/null +++ b/main/live-agent-api/migrations/add_message_time.sql @@ -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 + diff --git a/main/live-agent-api/pyproject.toml b/main/live-agent-api/pyproject.toml index d5818b779..b949f265f 100644 --- a/main/live-agent-api/pyproject.toml +++ b/main/live-agent-api/pyproject.toml @@ -20,6 +20,7 @@ dependencies = [ "pyjwt>=2.9.0", "fish-audio-sdk>=1.1.0", "openai>=1.54.0", + "loguru>=0.7.0", ] [project.optional-dependencies] diff --git a/main/live-agent-api/repositories/agent.py b/main/live-agent-api/repositories/agent.py index fb1b70b66..c4a4d5a91 100644 --- a/main/live-agent-api/repositories/agent.py +++ b/main/live-agent-api/repositories/agent.py @@ -234,16 +234,17 @@ class Agent: latest_message_content, latest_message_time, sort_time) """ # Subquery: get latest message per agent using DISTINCT ON + # Use message_time for ordering (when message actually occurred) latest_msg_subq = ( select( ChatMessageModel.agent_id, ChatMessageModel.message_id, ChatMessageModel.role, ChatMessageModel.content, - ChatMessageModel.created_at.label('message_time') + ChatMessageModel.message_time.label('message_time') ) .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') ) @@ -272,7 +273,12 @@ class Agent: # Apply cursor filter if cursor: 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) except (ValueError, TypeError): pass @@ -288,12 +294,12 @@ class Agent: if has_more: 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 if has_more and rows: last_sort_time = rows[-1].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 diff --git a/main/live-agent-api/repositories/chat.py b/main/live-agent-api/repositories/chat.py index ddb8e2cfb..d4714a6a6 100644 --- a/main/live-agent-api/repositories/chat.py +++ b/main/live-agent-api/repositories/chat.py @@ -1,7 +1,7 @@ """ Chat messages repository - Database operations for chat messages """ -from datetime import datetime +from datetime import datetime, timezone from typing import List, Optional, Tuple from sqlalchemy import String, SmallInteger, TIMESTAMP, ForeignKey, Index, select, insert from sqlalchemy.orm import Mapped, mapped_column @@ -35,7 +35,14 @@ class ChatMessageModel(Base): # JSONB content: [{"message_type": "text|audio|image|file", "message_content": "..."}] 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( TIMESTAMP(timezone=True), default=utc_now, @@ -47,6 +54,7 @@ class ChatMessageModel(Base): Index('idx_chat_messages_agent_id', 'agent_id'), Index('idx_chat_messages_agent_message_composite', 'agent_id', 'message_id'), Index('idx_chat_messages_content_gin', 'content', postgresql_using='gin'), + Index('idx_chat_messages_agent_message_time', 'agent_id', 'message_time'), ) def __repr__(self): @@ -66,7 +74,8 @@ class ChatMessage: message_id: str, agent_id: str, 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: """ Create new chat message @@ -77,6 +86,7 @@ class ChatMessage: agent_id: Agent ID role: 1=user, 2=agent content: List of message parts with S3 URLs + message_time: When message actually occurred (for ordering) Returns: Created message model @@ -85,7 +95,8 @@ class ChatMessage: message_id=message_id, agent_id=agent_id, role=role, - content=content + content=content, + message_time=message_time or utc_now() ) db.add(message) await db.commit() @@ -103,13 +114,13 @@ class ChatMessage: Get messages by agent_id using cursor-based pagination (chat style) Behavior: - - First load (no cursor): Returns the latest messages (DESC order) - - Scroll up (with cursor): Returns older messages before the cursor + - First load (no cursor): Returns the latest messages (DESC order by message_time) + - Scroll up (with cursor): Returns older messages before the cursor timestamp Args: db: Database session 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 Returns: @@ -118,13 +129,24 @@ class ChatMessage: # Build query with cursor 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: - 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 - 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) messages: List[ChatMessageModel] = result.scalars().all() @@ -134,10 +156,10 @@ class ChatMessage: if has_more: 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 if has_more and messages: - next_cursor = messages[-1].message_id + next_cursor = messages[-1].message_time.isoformat() return messages, next_cursor, has_more diff --git a/main/live-agent-api/schemas/chat.py b/main/live-agent-api/schemas/chat.py index 7c3b37479..8d64702f2 100644 --- a/main/live-agent-api/schemas/chat.py +++ b/main/live-agent-api/schemas/chat.py @@ -1,7 +1,7 @@ """ 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 datetime import datetime import enum @@ -21,6 +21,7 @@ class ReportChatMessageRequest(BaseModel): agent_id: str = Field(..., max_length=50, description="Agent ID") role: int = Field(..., ge=1, le=2, description="1: user, 2: agent") 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): @@ -29,12 +30,17 @@ class ChatMessage(BaseModel): agent_id: str role: int # 1: user, 2: agent 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): """Response schema for paginated chat messages (cursor-based, chat style)""" messages: List[ChatMessage] - next_cursor: Optional[str] = Field(None, description="Message ID to load older messages (pass as cursor for next request)") + 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") diff --git a/main/live-agent-api/services/chat_service.py b/main/live-agent-api/services/chat_service.py index 7ab8531b2..4af474135 100644 --- a/main/live-agent-api/services/chat_service.py +++ b/main/live-agent-api/services/chat_service.py @@ -2,6 +2,7 @@ Chat service - Business logic for chat messages """ import base64 +from datetime import datetime, timezone from typing import List, Optional, Tuple from sqlalchemy.ext.asyncio import AsyncSession from copy import deepcopy @@ -68,13 +69,19 @@ class ChatService: # Convert Pydantic models to dict for JSONB storage 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 chat_message = await ChatMessageRepo.create( db=db, message_id=message_id, agent_id=request.agent_id, role=request.role, - content=content_dicts + content=content_dicts, + message_time=message_time ) return ChatMessageSchema( @@ -82,7 +89,7 @@ class ChatService: agent_id=chat_message.agent_id, role=chat_message.role, content=chat_message.content, - created_at=chat_message.created_at + message_time=chat_message.message_time, ) async def get_agent_messages( @@ -125,7 +132,7 @@ class ChatService: agent_id=message.agent_id, role=message.role, content=message.content, - created_at=message.created_at + message_time=message.message_time, )) return response_messages, next_cursor, has_more diff --git a/main/live-agent-api/services/llm_service.py b/main/live-agent-api/services/llm_service.py index a7d55dc9a..45afd0bb7 100644 --- a/main/live-agent-api/services/llm_service.py +++ b/main/live-agent-api/services/llm_service.py @@ -2,9 +2,10 @@ import json from typing import AsyncGenerator, Optional from openai import AsyncOpenAI -from config import settings - +from config import settings, get_logger +import time +logger = get_logger(__name__) class LLMService: """Service for LLM-based text generation""" @@ -232,6 +233,7 @@ Create a richer, more detailed persona.""" async for chunk in stream: if chunk.choices and chunk.choices[0].delta.content: + logger.info(f"Optimize persona chunk time: {time.time()}") yield chunk.choices[0].delta.content except Exception as e: diff --git a/main/live-agent-api/services/stt_service.py b/main/live-agent-api/services/stt_service.py new file mode 100644 index 000000000..eb7694dc0 --- /dev/null +++ b/main/live-agent-api/services/stt_service.py @@ -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() + diff --git a/main/live-agent-api/uv.lock b/main/live-agent-api/uv.lock index d21d95caf..d100830c9 100644 --- a/main/live-agent-api/uv.lock +++ b/main/live-agent-api/uv.lock @@ -810,6 +810,7 @@ dependencies = [ { name = "fastapi" }, { name = "fish-audio-sdk" }, { name = "httpx" }, + { name = "loguru" }, { name = "openai" }, { name = "pydantic" }, { name = "pydantic-settings" }, @@ -840,6 +841,7 @@ requires-dist = [ { name = "fastapi", specifier = ">=0.115.0" }, { name = "fish-audio-sdk", specifier = ">=1.1.0" }, { name = "httpx", specifier = ">=0.27.0" }, + { name = "loguru", specifier = ">=0.7.0" }, { name = "openai", specifier = ">=1.54.0" }, { name = "pydantic", specifier = ">=2.9.0" }, { name = "pydantic-settings", specifier = ">=2.6.0" }, @@ -856,6 +858,19 @@ requires-dist = [ ] 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]] name = "multidict" 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" }, ] +[[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]] name = "wrapt" version = "1.17.3" diff --git a/main/xiaozhi-server/config/live_agent_api_client.py b/main/xiaozhi-server/config/live_agent_api_client.py index dcd326c6f..86df42255 100644 --- a/main/xiaozhi-server/config/live_agent_api_client.py +++ b/main/xiaozhi-server/config/live_agent_api_client.py @@ -114,6 +114,7 @@ def report_chat_message( agent_id: str, role: int, content_items: List[Dict[str, str]], + message_time: int = None, config: dict = None ) -> Optional[dict]: """ @@ -129,6 +130,7 @@ def report_chat_message( {"message_type": "image", "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) Returns: @@ -148,6 +150,10 @@ def report_chat_message( "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) if result.get("code") == 200: diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index dceecdb1e..828622cce 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -29,6 +29,7 @@ from core.providers.tts.default import DefaultTTS from concurrent.futures import ThreadPoolExecutor from core.utils.dialogue import Message, Dialogue from core.providers.asr.dto.dto import InterfaceType +from core.providers.tts.dto.dto import MessageTag from core.handle.textHandle import handleTextMessage from core.providers.tools.unified_tool_handler import UnifiedToolHandler from plugins_func.loadplugins import auto_import_modules @@ -168,6 +169,9 @@ class ConnectionHandler: self._voice_closing = None self._language = None + # reconnected flag + self.reconnected: bool = False + async def handle_connection(self, ws): try: # 获取并验证headers @@ -189,6 +193,9 @@ class ConnectionHandler: # 认证通过,继续处理 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连接 request_path = ws.request.path 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}") opening_sentence_id = str(uuid.uuid4().hex) - + message_tag = MessageTag.OPENING # FIRST: Start session self.tts.tts_text_queue.put(TTSMessageDTO( sentence_id=opening_sentence_id, sentence_type=SentenceType.FIRST, content_type=ContentType.ACTION, + message_tag=message_tag, )) self.tts.tts_text_queue.put(TTSMessageDTO( @@ -463,6 +471,7 @@ class ConnectionHandler: sentence_type=SentenceType.MIDDLE, content_type=ContentType.TEXT, content_detail=self._voice_opening, + message_tag=message_tag, ) ) @@ -470,6 +479,7 @@ class ConnectionHandler: sentence_id=opening_sentence_id, sentence_type=SentenceType.LAST, content_type=ContentType.ACTION, + message_tag=message_tag, )) except Exception as e: @@ -1194,14 +1204,10 @@ class ConnectionHandler: try: # 从队列获取数据,设置超时以便定期检查停止事件 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 try: - # 检查线程池状态 - if self.executor is None: - continue - # 提交任务到线程池 - # self.executor.submit(self._process_report, *item) self._process_report(*item) except Exception as e: self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}") @@ -1210,6 +1216,21 @@ class ConnectionHandler: except Exception as 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("聊天记录上报线程已退出") def _process_report(self, role, text, audio_data, report_time, attachments=None): @@ -1256,9 +1277,21 @@ class ConnectionHandler: if self.stop_event: self.stop_event.set() - # 清空任务队列 + # clear TTS text queue and audio queue, except report_queue 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连接 try: if ws: @@ -1317,17 +1350,16 @@ class ConnectionHandler: self.stop_event.set() def clear_queues(self): - """清空所有任务队列""" + """clear TTS task queues (except report_queue, which is handled by close method)""" if self.tts: self.logger.bind(tag=TAG).debug( 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 [ self.tts.tts_text_queue, self.tts.tts_audio_queue, - self.report_queue, ]: if not q: continue diff --git a/main/xiaozhi-server/core/handle/reportHandle.py b/main/xiaozhi-server/core/handle/reportHandle.py index 7c37ff4fd..d0309134c 100644 --- a/main/xiaozhi-server/core/handle/reportHandle.py +++ b/main/xiaozhi-server/core/handle/reportHandle.py @@ -7,46 +7,15 @@ Report features: See core/connection.py for implementation details. """ -import re import time import base64 from typing import List, Dict, Any 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__ -# 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): """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 text: Message text content 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: [ {"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") 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( agent_id=conn.agent_id, role=role, - content_items=content_items + content_items=content_items, + message_time=report_time if report_time > 0 else None ) except Exception as 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) Args: conn: Connection object text: Synthesized text (may contain emotion tags) 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 if not conn.read_config_from_live_agent_api or conn.need_bind or not conn.report_tts_enable: return if conn.chat_history_conf == 0: 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: # 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 if conn.chat_history_conf == 2: # 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( - 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: # 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( - 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: 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) Args: conn: Connection object text: Recognized text 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 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: return + # Use provided report_time or current time + timestamp = report_time if report_time is not None else int(time.time()) + try: # Use connection's queue, pass text, audio data, and attachments # Queue format: (role, text, opus_data, timestamp, attachments) if conn.chat_history_conf == 2: # 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( - 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: # 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( - 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: conn.logger.bind(tag=TAG).debug(f"Failed to enqueue ASR report: {text}, {e}") diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py index b8c9814d8..f46fdc294 100644 --- a/main/xiaozhi-server/core/handle/sendAudioHandle.py +++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py @@ -3,15 +3,20 @@ import time import asyncio from core.utils import textUtils 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__ -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: conn.tts.tts_audio_first_sentence = False - await send_tts_message(conn, "start", None) + await send_tts_message(conn, "start", None, message_tag) # 记录首句 TTS 播放时间(端到端延迟的终点) first_audio_time = time.time() * 1000 @@ -34,16 +39,16 @@ async def sendAudioMessage(conn, sentenceType, audios, text): ) 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: conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}") # 发送结束消息(如果是最后一个文本) 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 if conn.close_after_chat: await conn.close() @@ -95,9 +100,15 @@ async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence): complete_packet = bytes(header) + opus_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包,支持流控 Args: @@ -157,7 +168,7 @@ async def sendAudio(conn, audios, frame_duration=60): await _send_to_mqtt_gateway(conn, audios, timestamp, sequence) else: # 直接发送opus数据包,不添加头部 - await conn.websocket.send(audios) + await _send_audio_with_header(conn, audios, message_tag) # 更新流控状态 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) else: # 直接发送预缓冲包,不添加头部 - await conn.websocket.send(audios[i]) + await _send_audio_with_header(conn, audios[i], message_tag) 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) else: # 直接发送opus数据包,不添加头部 - await conn.websocket.send(opus_packet) + await _send_audio_with_header(conn, opus_packet, message_tag) 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 状态消息""" if text is None and state == "sentence_start": 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: - message["text"] = textUtils.check_emoji(text) + text = textUtils.check_emoji(text) + text = strip_emotion_tags(text) + message["text"] = text # TTS播放结束 if state == "stop": diff --git a/main/xiaozhi-server/core/handle/textHandle.py b/main/xiaozhi-server/core/handle/textHandle.py index b5e877834..53f1ad6fc 100644 --- a/main/xiaozhi-server/core/handle/textHandle.py +++ b/main/xiaozhi-server/core/handle/textHandle.py @@ -1,7 +1,9 @@ from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry from core.handle.textMessageProcessor import TextMessageProcessor +from config.logger import setup_logging TAG = __name__ +logger = setup_logging() # 全局处理器注册表 message_registry = TextMessageHandlerRegistry() @@ -11,4 +13,5 @@ message_processor = TextMessageProcessor(message_registry) async def handleTextMessage(conn, message): """处理文本消息""" + logger.bind(tag=TAG).info(f"收到文本消息: {message}") await message_processor.process_message(conn, message) diff --git a/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py index 2393cf03b..07b72c038 100644 --- a/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py +++ b/main/xiaozhi-server/core/handle/textHandler/listenMessageHandler.py @@ -101,22 +101,26 @@ class ListenTextMessageHandler(TextMessageHandler): conn.client_is_speaking = False elif is_wakeup_words: conn.just_woken_up = True + # Record timestamp for correct message ordering + report_time = int(time.time()) # 上报纯文字数据(复用ASR上报功能,但不提供音频数据) - enqueue_asr_report(conn, "嘿,你好呀", []) + enqueue_asr_report(conn, "嘿,你好呀", [], report_time=report_time) await startToChat(conn, "嘿,你好呀") else: # check if there are attachments(eg. images, files) in text mode attachments = msg_json.get("attachments", []) + # Record timestamp for correct message ordering + report_time = int(time.time()) if attachments: # build multimodal content multimodal_content = build_multimodal_content(original_text, 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 await startToChat(conn, original_text, multimodal_content) else: # 上报纯文字数据(复用ASR上报功能,但不提供音频数据) - enqueue_asr_report(conn, original_text, []) + enqueue_asr_report(conn, original_text, [], report_time=report_time) # 否则需要LLM对文字内容进行答复 await startToChat(conn, original_text) \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py index f4d731588..9055484e7 100644 --- a/main/xiaozhi-server/core/providers/asr/base.py +++ b/main/xiaozhi-server/core/providers/asr/base.py @@ -178,9 +178,12 @@ class ASRProviderBase(ABC): # 构建包含说话人信息的JSON字符串 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) - 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: logger.bind(tag=TAG).error(f"处理语音停止失败: {e}") diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index c4f2b3e2f..443c861e9 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -6,6 +6,7 @@ import queue import asyncio import threading import traceback +from typing import Optional from concurrent.futures import ThreadPoolExecutor from core.utils import p3 from datetime import datetime @@ -15,6 +16,7 @@ from abc import ABC, abstractmethod from config.logger import setup_logging from core.utils.tts import MarkdownCleaner 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.sendAudioHandle import sendAudioMessage 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, ContentType, InterfaceType, + TTSAudioDTO, + MessageTag, ) TAG = __name__ @@ -39,10 +43,12 @@ class TTSProviderBase(ABC): self.delete_audio_file = delete_audio_file self.audio_file_type = "wav" self.output_file = config.get("output_dir", "tmp/") - self.tts_text_queue = queue.Queue() - self.tts_audio_queue = queue.Queue() + self.tts_text_queue = queue.Queue[TTSMessageDTO]() + # 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.before_stop_play_files = [] + self._message_tag = MessageTag.NORMAL self.tts_text_buff = [] self.punctuations = ( @@ -83,7 +89,12 @@ class TTSProviderBase(ABC): def handle_opus(self, opus_data: bytes): 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): self.before_stop_play_files.append((file_audio, text)) @@ -331,9 +342,22 @@ class TTSProviderBase(ABC): text = None try: try: - sentence_type, audio_datas, text = self.tts_audio_queue.get( + tts_audio_message = self.tts_audio_queue.get( 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: if self.conn.stop_event.is_set(): break @@ -349,12 +373,13 @@ class TTSProviderBase(ABC): if sentence_type is not SentenceType.MIDDLE: # 上报TTS数据 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_text = text # 收集上报音频数据 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) # 等待上一个发送完成(保持顺序),但使用短超时避免长时间阻塞 @@ -366,7 +391,7 @@ class TTSProviderBase(ABC): # 异步发送音频(不阻塞等待) 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, ) @@ -377,6 +402,14 @@ class TTSProviderBase(ABC): 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) + 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): pass @@ -461,9 +494,19 @@ class TTSProviderBase(ABC): def _process_before_stop_play_files(self): 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.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( self, opus_handler: Callable[[bytes], None] = None diff --git a/main/xiaozhi-server/core/providers/tts/dto/dto.py b/main/xiaozhi-server/core/providers/tts/dto/dto.py index b23173409..4d8bc54b2 100644 --- a/main/xiaozhi-server/core/providers/tts/dto/dto.py +++ b/main/xiaozhi-server/core/providers/tts/dto/dto.py @@ -1,5 +1,6 @@ from enum import Enum from typing import Union, Optional +from typing import Literal class SentenceType(Enum): @@ -22,6 +23,11 @@ class InterfaceType(Enum): SINGLE_STREAM = "SINGLE_STREAM" # 单流式 NON_STREAM = "NON_STREAM" # 非流式 +class MessageTag(Enum): + NORMAL = 0 + OPENING = 1 + CLOSING = 2 + class TTSMessageDTO: def __init__( @@ -35,9 +41,27 @@ class TTSMessageDTO: content_detail: 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_type = sentence_type self.content_type = content_type self.content_detail = content_detail 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 diff --git a/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py b/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py index 7d24e0ab4..aae190155 100644 --- a/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py +++ b/main/xiaozhi-server/core/providers/tts/fish_dual_stream.py @@ -11,6 +11,7 @@ Reference: https://docs.fish.audio/api-reference/endpoint/websocket/tts-live """ import os +import time import uuid import queue import asyncio @@ -22,8 +23,18 @@ from core.utils.tts import MarkdownCleaner from core.utils import opus_encoder_utils from core.utils.util import check_model_key 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 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__ logger = setup_logging() @@ -162,6 +173,7 @@ class TTSProvider(TTSProviderBase): self._first_sent = False self._session_text_buffer = [] self.conn._latency_tts_first_text_time = None # Reset TTS input time + self._message_tag = message.message_tag elif self.conn.client_abort: # ========== Interruption ========== @@ -246,7 +258,90 @@ class TTSProvider(TTSProviderBase): f"TTS text processing failed: {str(e)}, type: {type(e).__name__}, " 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): """Clean up WebSocket resources""" self._session_active = False @@ -294,8 +389,17 @@ class TTSProvider(TTSProviderBase): # 这样后续音频通过 MIDDLE 累积时,enqueue_audio 不会被清空 if not self._first_sent: 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 - 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 self.opus_encoder.encode_pcm_to_opus_stream( @@ -318,8 +422,12 @@ class TTSProvider(TTSProviderBase): # 发送 LAST 触发客户端 stop 和最终上报 # 不再发送 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.conn.tts_MessageText = None diff --git a/main/xiaozhi-server/core/utils/opus.py b/main/xiaozhi-server/core/utils/opus.py new file mode 100644 index 000000000..090f3e4dd --- /dev/null +++ b/main/xiaozhi-server/core/utils/opus.py @@ -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 \ No newline at end of file diff --git a/main/xiaozhi-server/core/utils/textUtils.py b/main/xiaozhi-server/core/utils/textUtils.py index d3689d346..812ef6bf3 100644 --- a/main/xiaozhi-server/core/utils/textUtils.py +++ b/main/xiaozhi-server/core/utils/textUtils.py @@ -1,7 +1,8 @@ import json - +import re from urllib3 import Retry + TAG = __name__ EMOJI_MAP = { "😂": "laughing", @@ -115,3 +116,34 @@ def is_emoji(char): def check_emoji(text): """去除文本中的所有emoji表情""" 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() \ No newline at end of file diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index d999b9c1e..a71e56bb8 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -49,7 +49,10 @@ class WebSocketServer: port = int(server_config.get("port", 8000)) 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() diff --git a/main/xiaozhi-server/custom_config.yaml b/main/xiaozhi-server/custom_config.yaml index 94053b62b..8218eb812 100644 --- a/main/xiaozhi-server/custom_config.yaml +++ b/main/xiaozhi-server/custom_config.yaml @@ -207,7 +207,7 @@ language: zh # 结束语prompt end_prompt: - enable: true # 是否开启结束语 + enable: false # 是否开启结束语 # 结束语 prompt: | 请你以"时间过得真快"未来头,用富有感情、依依不舍的话来结束这场对话吧! diff --git a/main/xiaozhi-server/test/test_page.html b/main/xiaozhi-server/test/test_page.html index a19a0d9d7..7543dcc4f 100644 --- a/main/xiaozhi-server/test/test_page.html +++ b/main/xiaozhi-server/test/test_page.html @@ -1009,20 +1009,40 @@ if (message.type === 'hello') { 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') { // 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') { - log('服务器开始发送语音', 'info'); + log(`服务器开始发送语音 ${tagName}`, 'info'); } else if (message.state === 'sentence_start') { - log(`服务器发送语音段: ${message.text}`, 'info'); - // 添加文本到会话记录 - if (message.text) { - addMessage(message.text); + 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) { + addMessage(message.text); + } } } else if (message.state === 'sentence_end') { - log(`语音段结束: ${message.text}`, 'info'); + log(`语音段结束${tagName}: ${message.text}`, 'info'); } else if (message.state === 'stop') { log('服务器语音传输结束', 'info'); + // Mark opening as played after TTS completes + if (!openingPlayedInSession) { + openingPlayedInSession = true; + log('开场白播放完成,后续重连将跳过', 'debug'); + } + // Reset skip flag for next session + skipCurrentOpening = false; // 结束后更新UI状态 if (recordButton.disabled) { 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) { try { let arrayBuffer; - // 根据数据类型进行处理 + // Convert to ArrayBuffer based on data type if (data instanceof ArrayBuffer) { arrayBuffer = data; - log(`收到ArrayBuffer音频数据,大小: ${data.byteLength}字节`, 'debug'); } else if (data instanceof Blob) { - // 如果是Blob类型,转换为ArrayBuffer arrayBuffer = await data.arrayBuffer(); - log(`收到Blob音频数据,大小: ${arrayBuffer.byteLength}字节`, 'debug'); } else { log(`收到未知类型的二进制数据: ${typeof data}`, 'warning'); return; } - // 创建Uint8Array用于处理 - const opusData = new Uint8Array(arrayBuffer); - if (opusData.length > 0) { - // 将数据添加到缓冲队列 - queue.enqueue(opusData); - } else { + + // Parse 16-byte header + opus payload + // Header structure: + // byte 0: type (1 = audio) + // byte 1: message_tag (0=normal, 1=opening, 2=notification) + // bytes 2-15: reserved + const HEADER_SIZE = 16; + + if (arrayBuffer.byteLength <= HEADER_SIZE) { log('收到空音频数据帧,可能是结束标志', 'warning'); - // 如果正在播放,发送结束信号 if (isAudioPlaying && streamingContext) { 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) { log(`处理二进制消息出错: ${error.message}`, 'error');