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 603481070..341b07a74 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 +from config import get_logger import base64 -import logging from fastapi import HTTPException +import asyncio +logger = get_logger(__name__) router = APIRouter() @@ -180,7 +182,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 @@ -199,7 +201,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( @@ -217,6 +219,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/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/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/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/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"