mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge pull request #17 from Plaud-AI/feat/demo
feat: Enhance Agent list API with activity-based sorting and add template creation endpoint
This commit is contained in:
commit
58ae4c20e0
11 changed files with 323 additions and 80 deletions
31
main/.env.example
Normal file
31
main/.env.example
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
# Live Agent Environment Configuration
|
||||
# Copy this file to .env and update the values
|
||||
|
||||
# ==================== S3/MinIO Configuration ====================
|
||||
# For local development with MinIO(compatible with S3)
|
||||
AWS_ACCESS_KEY_ID=minioadmin
|
||||
AWS_SECRET_ACCESS_KEY=minioadmin
|
||||
AWS_REGION=us-east-1
|
||||
S3_BUCKET_NAME=live-agent-files
|
||||
S3_ENDPOINT_URL=
|
||||
S3_PUBLIC_BASE_URL=
|
||||
|
||||
# ==================== Security ====================
|
||||
SECRET_KEY=dev-secret-key-change-in-production
|
||||
|
||||
# ==================== Token Configuration ====================
|
||||
TOKEN_EXPIRE_DAYS=7
|
||||
|
||||
# ==================== Live Agent API Server Configuration ====================
|
||||
# These are optional, defaults are set in settings.py
|
||||
# LIVE_AGENT_API_HOST=0.0.0.0
|
||||
# LIVE_AGENT_API_PORT=8080
|
||||
# LIVE_AGENT_API_DEBUG=False
|
||||
|
||||
# ==================== Database Configuration ====================
|
||||
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=
|
||||
|
|
@ -8,6 +8,8 @@ services:
|
|||
dockerfile: Dockerfile
|
||||
image: xiaozhi-esp32-server:local
|
||||
container_name: xiaozhi-esp32-server
|
||||
env_file:
|
||||
- .env
|
||||
depends_on:
|
||||
xiaozhi-esp32-server-db:
|
||||
condition: service_healthy
|
||||
|
|
@ -211,7 +213,7 @@ services:
|
|||
dockerfile: Dockerfile
|
||||
container_name: live-agent-api
|
||||
env_file:
|
||||
- ./live-agent-api/.env
|
||||
- .env
|
||||
environment:
|
||||
DATABASE_URL: postgresql+asyncpg://postgres:postgres@live-agent-postgres:5432/live_agent
|
||||
S3_ENDPOINT_URL: http://live-agent-minio:9000
|
||||
|
|
|
|||
6
main/live-agent-api/.dockerignore
Normal file
6
main/live-agent-api/.dockerignore
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
.git
|
||||
__pycache__
|
||||
*.pyc
|
||||
Dockerfile
|
||||
tmp/
|
||||
data/
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
# Live Agent API Environment Configuration
|
||||
# Copy this file to .env and update the values
|
||||
|
||||
# ==================== S3/MinIO Configuration ====================
|
||||
# For local development with MinIO
|
||||
AWS_ACCESS_KEY_ID=minioadmin
|
||||
AWS_SECRET_ACCESS_KEY=minioadmin
|
||||
AWS_REGION=us-east-1
|
||||
S3_BUCKET_NAME=live-agent-files
|
||||
|
||||
# For production with AWS S3, use your actual credentials:
|
||||
# AWS_ACCESS_KEY_ID=your-aws-access-key
|
||||
# AWS_SECRET_ACCESS_KEY=your-aws-secret-key
|
||||
# AWS_REGION=ap-northeast-1
|
||||
# S3_BUCKET_NAME=your-production-bucket
|
||||
|
||||
# ==================== Security ====================
|
||||
SECRET_KEY=dev-secret-key-change-in-production
|
||||
|
||||
# ==================== Token Configuration ====================
|
||||
TOKEN_EXPIRE_DAYS=7
|
||||
|
||||
# ==================== Server Configuration ====================
|
||||
# These are optional, defaults are set in settings.py
|
||||
# HOST=0.0.0.0
|
||||
# PORT=8080
|
||||
# DEBUG=False
|
||||
|
||||
# ==================== Database Configuration ====================
|
||||
# This is overridden in docker-compose.yml for container environment
|
||||
# For local development without Docker, use:
|
||||
# DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/live_agent
|
||||
|
||||
FISH_API_KEY=your-fish-api-key
|
||||
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
from fastapi import APIRouter, Depends
|
||||
from fastapi import APIRouter, Depends, Form, File, UploadFile
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from infra import get_db
|
||||
from infra import get_db, get_s3
|
||||
from services.agent_service import agent_service
|
||||
from utils.response import success_response
|
||||
|
||||
|
|
@ -16,3 +16,40 @@ async def get_templates(
|
|||
templates = await agent_service.get_templates(db)
|
||||
return success_response(data={"templates": [t.model_dump() for t in templates]})
|
||||
|
||||
|
||||
@router.post("", summary="Create Agent Template")
|
||||
async def create_template(
|
||||
name: str = Form(...),
|
||||
description: str = Form(...),
|
||||
voice_id: str = Form(...),
|
||||
instruction: str = Form(...),
|
||||
voice_opening: str = Form(...),
|
||||
voice_closing: str = Form(...),
|
||||
avatar: UploadFile = File(...),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
s3 = Depends(get_s3)
|
||||
):
|
||||
"""
|
||||
Create a new agent template (all fields required)
|
||||
|
||||
- **name**: Template name
|
||||
- **description**: Template description
|
||||
- **voice_id**: Fish Audio voice ID
|
||||
- **instruction**: System prompt for the agent
|
||||
- **voice_opening**: Opening message
|
||||
- **voice_closing**: Closing message
|
||||
- **avatar**: Avatar image file
|
||||
"""
|
||||
template = await agent_service.create_template(
|
||||
db=db,
|
||||
s3=s3,
|
||||
name=name,
|
||||
description=description,
|
||||
voice_id=voice_id,
|
||||
instruction=instruction,
|
||||
voice_opening=voice_opening,
|
||||
voice_closing=voice_closing,
|
||||
avatar=avatar
|
||||
)
|
||||
return success_response(data=template.model_dump())
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
from datetime import datetime
|
||||
from typing import Optional, List, Tuple
|
||||
from sqlalchemy import String, Text, TIMESTAMP, ForeignKey, Index, select, delete
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, List, Tuple, Any
|
||||
from sqlalchemy import String, Text, TIMESTAMP, ForeignKey, Index, select, delete, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from infra.database import Base, utc_now
|
||||
from repositories.chat import ChatMessageModel
|
||||
|
||||
|
||||
# ==================== ORM Model ====================
|
||||
|
|
@ -182,3 +183,88 @@ class Agent:
|
|||
await db.commit()
|
||||
return result.rowcount > 0
|
||||
|
||||
@staticmethod
|
||||
async def get_agents_with_latest_message(
|
||||
db: AsyncSession,
|
||||
owner_id: str,
|
||||
cursor: Optional[str] = None,
|
||||
limit: int = 20
|
||||
) -> Tuple[List[Tuple[Any, ...]], Optional[str], bool]:
|
||||
"""
|
||||
Get agents with their latest message, ordered by latest activity time
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
owner_id: User ID
|
||||
cursor: ISO datetime string of last item's sort_time
|
||||
limit: Number of items to return
|
||||
|
||||
Returns:
|
||||
Tuple of (rows, next_cursor, has_more)
|
||||
Each row contains: (AgentModel, latest_message_id, latest_message_role,
|
||||
latest_message_content, latest_message_time, sort_time)
|
||||
"""
|
||||
# Subquery: get latest message per agent using DISTINCT ON
|
||||
latest_msg_subq = (
|
||||
select(
|
||||
ChatMessageModel.agent_id,
|
||||
ChatMessageModel.message_id,
|
||||
ChatMessageModel.role,
|
||||
ChatMessageModel.content,
|
||||
ChatMessageModel.created_at.label('message_time')
|
||||
)
|
||||
.distinct(ChatMessageModel.agent_id)
|
||||
.order_by(ChatMessageModel.agent_id, ChatMessageModel.message_id.desc())
|
||||
.subquery('latest_messages')
|
||||
)
|
||||
|
||||
# Sort time: use message time if available, otherwise agent created_at
|
||||
sort_time_expr = func.coalesce(
|
||||
latest_msg_subq.c.message_time,
|
||||
AgentModel.created_at
|
||||
)
|
||||
|
||||
sort_time = sort_time_expr.label('sort_time')
|
||||
|
||||
# Main query: join agents with latest messages
|
||||
query = (
|
||||
select(
|
||||
AgentModel,
|
||||
latest_msg_subq.c.message_id.label('latest_message_id'),
|
||||
latest_msg_subq.c.role.label('latest_message_role'),
|
||||
latest_msg_subq.c.content.label('latest_message_content'),
|
||||
latest_msg_subq.c.message_time.label('latest_message_time'),
|
||||
sort_time
|
||||
)
|
||||
.outerjoin(latest_msg_subq, AgentModel.agent_id == latest_msg_subq.c.agent_id)
|
||||
.where(AgentModel.owner_id == owner_id)
|
||||
)
|
||||
|
||||
# Apply cursor filter
|
||||
if cursor:
|
||||
try:
|
||||
cursor_time = datetime.fromisoformat(cursor)
|
||||
query = query.where(sort_time_expr < cursor_time)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# Order by sort_time DESC, agent_id DESC for stable sorting
|
||||
query = query.order_by(sort_time.desc(), AgentModel.agent_id.desc()).limit(limit + 1)
|
||||
|
||||
result = await db.execute(query)
|
||||
rows = result.all()
|
||||
|
||||
# Check if there are more records
|
||||
has_more = len(rows) > limit
|
||||
if has_more:
|
||||
rows = rows[:limit]
|
||||
|
||||
# Generate next cursor from last item's sort_time
|
||||
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()
|
||||
|
||||
return rows, next_cursor, has_more
|
||||
|
||||
|
|
|
|||
|
|
@ -71,3 +71,31 @@ class AgentTemplate:
|
|||
result = await db.execute(stmt)
|
||||
return result.scalars().all()
|
||||
|
||||
@staticmethod
|
||||
async def create(
|
||||
db: AsyncSession,
|
||||
template_id: str,
|
||||
name: str,
|
||||
avatar_url: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
voice_id: Optional[str] = None,
|
||||
instruction: Optional[str] = None,
|
||||
voice_opening: Optional[str] = None,
|
||||
voice_closing: Optional[str] = None
|
||||
) -> AgentTemplateModel:
|
||||
"""Create a new agent template"""
|
||||
template = AgentTemplateModel(
|
||||
template_id=template_id,
|
||||
name=name,
|
||||
avatar_url=avatar_url,
|
||||
description=description,
|
||||
voice_id=voice_id,
|
||||
instruction=instruction,
|
||||
voice_opening=voice_opening,
|
||||
voice_closing=voice_closing
|
||||
)
|
||||
db.add(template)
|
||||
await db.commit()
|
||||
await db.refresh(template)
|
||||
return template
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, Field
|
||||
from fastapi import UploadFile
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
# ==================== Template Schemas ====================
|
||||
|
|
@ -17,7 +16,6 @@ class AgentTemplateResponse(BaseModel):
|
|||
voice_opening: Optional[str] = None
|
||||
voice_closing: Optional[str] = None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
|
@ -40,9 +38,18 @@ class AgentResponse(BaseModel):
|
|||
from_attributes = True
|
||||
|
||||
|
||||
class AgentWithLatestMessage(BaseModel):
|
||||
"""Agent with latest message for list view"""
|
||||
agent_id: str
|
||||
name: str
|
||||
avatar_url: Optional[str] = None
|
||||
last_activity_time: datetime # 最近活动时间 (消息时间 or agent创建时间)
|
||||
latest_message_text: Optional[str] = None # 最新消息的文本内容
|
||||
|
||||
|
||||
class AgentListResponse(BaseModel):
|
||||
"""Agent list response with cursor-based pagination"""
|
||||
agents: list[AgentResponse]
|
||||
agents: list[AgentWithLatestMessage]
|
||||
next_cursor: Optional[str] = None
|
||||
has_more: bool = False
|
||||
|
||||
|
|
|
|||
|
|
@ -9,8 +9,10 @@ from schemas.agent import (
|
|||
AgentResponse,
|
||||
AgentListResponse,
|
||||
AgentTemplateResponse,
|
||||
AgentConfigResponse
|
||||
AgentConfigResponse,
|
||||
AgentWithLatestMessage
|
||||
)
|
||||
from utils.ulid import generate_template_id
|
||||
class AgentService:
|
||||
"""Agent service layer"""
|
||||
|
||||
|
|
@ -18,6 +20,38 @@ class AgentService:
|
|||
"""Get all agent templates"""
|
||||
templates = await AgentTemplate.get_all(db)
|
||||
return [AgentTemplateResponse.model_validate(t) for t in templates]
|
||||
|
||||
async def create_template(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
s3,
|
||||
name: str,
|
||||
description: str,
|
||||
voice_id: str,
|
||||
instruction: str,
|
||||
voice_opening: str,
|
||||
voice_closing: str,
|
||||
avatar: UploadFile
|
||||
) -> AgentTemplateResponse:
|
||||
"""Create a new agent template (all fields required)"""
|
||||
# Generate template_id
|
||||
template_id = generate_template_id()
|
||||
|
||||
# Upload avatar
|
||||
avatar_url = await FileRepository.upload_avatar(s3, avatar, template_id)
|
||||
|
||||
template = await AgentTemplate.create(
|
||||
db=db,
|
||||
template_id=template_id,
|
||||
name=name,
|
||||
avatar_url=avatar_url,
|
||||
description=description,
|
||||
voice_id=voice_id,
|
||||
instruction=instruction,
|
||||
voice_opening=voice_opening,
|
||||
voice_closing=voice_closing
|
||||
)
|
||||
return AgentTemplateResponse.model_validate(template)
|
||||
|
||||
async def get_agent_list(
|
||||
self,
|
||||
|
|
@ -27,27 +61,47 @@ class AgentService:
|
|||
page_size: int = 10
|
||||
) -> AgentListResponse:
|
||||
"""
|
||||
Get user's agent list with cursor-based pagination
|
||||
Get user's agent list with cursor-based pagination, ordered by latest message time
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
owner_id: User ID
|
||||
cursor: Pagination cursor (ISO datetime string)
|
||||
cursor: Pagination cursor (ISO datetime string of sort_time)
|
||||
page_size: Number of items per page
|
||||
|
||||
Returns:
|
||||
AgentListResponse with agents, next_cursor, and has_more
|
||||
AgentListResponse with agents (including latest message), next_cursor, and has_more
|
||||
"""
|
||||
agents, next_cursor, has_more = await Agent.get_agents_by_owner(
|
||||
rows, next_cursor, has_more = await Agent.get_agents_with_latest_message(
|
||||
db,
|
||||
owner_id=owner_id,
|
||||
cursor=cursor,
|
||||
limit=page_size
|
||||
)
|
||||
|
||||
agent_responses = [AgentResponse.model_validate(a) for a in agents]
|
||||
# Process rows into response format
|
||||
agents = []
|
||||
for row in rows:
|
||||
agent = row[0] # AgentModel instance
|
||||
|
||||
# Extract text content from latest message if exists
|
||||
latest_message_text = None
|
||||
if row.latest_message_content:
|
||||
for item in row.latest_message_content:
|
||||
if item.get('message_type') == 'text':
|
||||
latest_message_text = item.get('message_content')
|
||||
break
|
||||
|
||||
agents.append(AgentWithLatestMessage(
|
||||
agent_id=agent.agent_id,
|
||||
name=agent.name,
|
||||
avatar_url=agent.avatar_url,
|
||||
last_activity_time=row.sort_time,
|
||||
latest_message_text=latest_message_text
|
||||
))
|
||||
|
||||
return AgentListResponse(
|
||||
agents=agent_responses,
|
||||
agents=agents,
|
||||
next_cursor=next_cursor,
|
||||
has_more=has_more
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,9 +1,51 @@
|
|||
import os
|
||||
import re
|
||||
import yaml
|
||||
from collections.abc import Mapping
|
||||
from config.manage_api_client import init_service, get_server_config, get_agent_models
|
||||
from dotenv import load_dotenv
|
||||
|
||||
|
||||
# Environment variable pattern: ${VAR_NAME} or ${VAR_NAME:-default_value}
|
||||
ENV_VAR_PATTERN = re.compile(r'\$\{([^}:]+)(?::-([^}]*))?\}')
|
||||
|
||||
|
||||
def expand_env_vars(config):
|
||||
"""
|
||||
Recursively expand environment variable placeholders in config.
|
||||
|
||||
Supports two formats:
|
||||
- ${VAR_NAME} - Required, raises error if not set
|
||||
- ${VAR_NAME:-default} - Optional, uses default if not set
|
||||
|
||||
Examples:
|
||||
api_key: ${OPENAI_API_KEY}
|
||||
base_url: ${OPENAI_BASE_URL:-https://api.openai.com/v1}
|
||||
"""
|
||||
if isinstance(config, dict):
|
||||
return {k: expand_env_vars(v) for k, v in config.items()}
|
||||
elif isinstance(config, list):
|
||||
return [expand_env_vars(item) for item in config]
|
||||
elif isinstance(config, str):
|
||||
def replace_env_var(match):
|
||||
var_name = match.group(1)
|
||||
default_value = match.group(2) # None if no default specified
|
||||
|
||||
env_value = os.environ.get(var_name)
|
||||
|
||||
if env_value is not None:
|
||||
return env_value
|
||||
elif default_value is not None:
|
||||
return default_value
|
||||
else:
|
||||
# Keep original placeholder if env var not set and no default
|
||||
# This allows optional configs to remain as placeholders
|
||||
return match.group(0)
|
||||
|
||||
return ENV_VAR_PATTERN.sub(replace_env_var, config)
|
||||
return config
|
||||
|
||||
|
||||
def get_project_dir():
|
||||
"""获取项目根目录"""
|
||||
return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/"
|
||||
|
|
@ -24,34 +66,19 @@ def load_config():
|
|||
if cached_config is not None:
|
||||
return cached_config
|
||||
|
||||
# default_config_path = get_project_dir() + "config.yaml"
|
||||
custom_config_path = get_project_dir() + "custom_config.yaml"
|
||||
|
||||
# 加载默认配置
|
||||
# default_config = read_config(default_config_path)
|
||||
config = read_config(custom_config_path)
|
||||
config["read_config_from_live_agent_api"] = True
|
||||
# load environment variables
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
# tts
|
||||
select_tts_module = config["selected_module"]["TTS"]
|
||||
if os.environ.get("REGION") == "LOCAL" and select_tts_module == "FishSpeech":
|
||||
config["TTS"][select_tts_module]["api_key"] = os.environ.get("FISH_API_KEY")
|
||||
# asr
|
||||
select_asr_module = config["selected_module"]["ASR"]
|
||||
if os.environ.get("REGION") == "LOCAL" and select_asr_module == "GroqASR":
|
||||
config["ASR"][select_asr_module]["api_key"] = os.environ.get("GROQ_API_KEY")
|
||||
# llm
|
||||
select_llm_module = config["selected_module"]["LLM"]
|
||||
if os.environ.get("REGION") == "LOCAL" and select_llm_module == "GroqLLM":
|
||||
config["LLM"][select_llm_module]["api_key"] = os.environ.get("GROQ_API_KEY")
|
||||
if os.environ.get("REGION") == "LOCAL" and select_llm_module == "OpenaiLLM":
|
||||
config["LLM"][select_llm_module]["api_key"] = os.environ.get("OPENAI_API_KEY")
|
||||
# if custom_config.get("manager-api", {}).get("url"):
|
||||
# config = get_config_from_api(custom_config)
|
||||
# else:
|
||||
# # 合并配置
|
||||
# config = merge_configs(default_config, custom_config)
|
||||
|
||||
# Read YAML config
|
||||
config = read_config(custom_config_path)
|
||||
|
||||
# Expand environment variable placeholders (e.g., ${OPENAI_API_KEY})
|
||||
config = expand_env_vars(config)
|
||||
|
||||
config["read_config_from_live_agent_api"] = True
|
||||
|
||||
# 初始化目录
|
||||
ensure_directories(config)
|
||||
|
||||
|
|
|
|||
|
|
@ -416,7 +416,7 @@ ASR:
|
|||
# 2.创建api-key https://console.groq.com/keys
|
||||
# 3.模型可以选择whisper-large-v3-turbo或whisper-large-v3(distil-whisper-large-v3-en仅支持英语转录)
|
||||
type: openai
|
||||
api_key: your groq api key
|
||||
api_key: ${GROQ_API_KEY}
|
||||
base_url: https://api.groq.com/openai/v1
|
||||
model_name: whisper-large-v3-turbo
|
||||
output_dir: tmp/
|
||||
|
|
@ -542,7 +542,7 @@ LLM:
|
|||
type: openai
|
||||
model_name: gpt-4o
|
||||
base_url: https://api.openai.com/v1
|
||||
api_key: your openai api key
|
||||
api_key: ${OPENAI_API_KEY}
|
||||
OllamaLLM:
|
||||
# 定义LLM API类型
|
||||
type: ollama
|
||||
|
|
@ -782,7 +782,7 @@ TTS:
|
|||
channels: 1
|
||||
rate: 44100
|
||||
sample_rate: 16000
|
||||
api_key: "your fish speech api key"
|
||||
api_key: ${FISH_API_KEY}
|
||||
GPT_SOVITS_V2:
|
||||
# 定义TTS API类型
|
||||
#启动tts方法:
|
||||
|
|
|
|||
Loading…
Reference in a new issue