From d3f152de2eb534e6467870b2901e0ac62cc448ae Mon Sep 17 00:00:00 2001 From: Harold Date: Thu, 27 Nov 2025 13:59:09 +0800 Subject: [PATCH 1/3] feat: remote aws ec2 container deployment --- main/.env.example | 31 +++++++++ main/docker-compose_local_all.yml | 4 +- main/live-agent-api/.env.example | 35 ---------- main/xiaozhi-server/config/config_loader.py | 77 ++++++++++++++------- main/xiaozhi-server/custom_config.yaml | 6 +- 5 files changed, 89 insertions(+), 64 deletions(-) create mode 100644 main/.env.example delete mode 100644 main/live-agent-api/.env.example diff --git a/main/.env.example b/main/.env.example new file mode 100644 index 000000000..783b93cc0 --- /dev/null +++ b/main/.env.example @@ -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= \ No newline at end of file diff --git a/main/docker-compose_local_all.yml b/main/docker-compose_local_all.yml index 695e7df25..641e5cf69 100644 --- a/main/docker-compose_local_all.yml +++ b/main/docker-compose_local_all.yml @@ -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 diff --git a/main/live-agent-api/.env.example b/main/live-agent-api/.env.example deleted file mode 100644 index 0666c9a15..000000000 --- a/main/live-agent-api/.env.example +++ /dev/null @@ -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 - diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py index 1e66e234a..c0e3c3a2b 100644 --- a/main/xiaozhi-server/config/config_loader.py +++ b/main/xiaozhi-server/config/config_loader.py @@ -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) diff --git a/main/xiaozhi-server/custom_config.yaml b/main/xiaozhi-server/custom_config.yaml index d8f29d6c5..9e63bfb7e 100644 --- a/main/xiaozhi-server/custom_config.yaml +++ b/main/xiaozhi-server/custom_config.yaml @@ -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方法: From 1adc603666f91f37d355b4147fdf80dc0d963519 Mon Sep 17 00:00:00 2001 From: Harold Date: Thu, 27 Nov 2025 14:49:43 +0800 Subject: [PATCH 2/3] feat: dockerignore --- main/live-agent-api/.dockerignore | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 main/live-agent-api/.dockerignore diff --git a/main/live-agent-api/.dockerignore b/main/live-agent-api/.dockerignore new file mode 100644 index 000000000..4574a717b --- /dev/null +++ b/main/live-agent-api/.dockerignore @@ -0,0 +1,6 @@ +.git +__pycache__ +*.pyc +Dockerfile +tmp/ +data/ \ No newline at end of file From 9b2339c947dac8def50f6b6784ef17a3b60992e4 Mon Sep 17 00:00:00 2001 From: Harold Date: Fri, 28 Nov 2025 17:53:20 +0800 Subject: [PATCH 3/3] feat: list with latest message && new add template api --- main/live-agent-api/api/v1/templates.py | 41 ++++++++- main/live-agent-api/repositories/agent.py | 92 ++++++++++++++++++- .../repositories/agent_template.py | 28 ++++++ main/live-agent-api/schemas/agent.py | 15 ++- main/live-agent-api/services/agent_service.py | 68 ++++++++++++-- 5 files changed, 228 insertions(+), 16 deletions(-) diff --git a/main/live-agent-api/api/v1/templates.py b/main/live-agent-api/api/v1/templates.py index 5e4383af5..c31041f3d 100644 --- a/main/live-agent-api/api/v1/templates.py +++ b/main/live-agent-api/api/v1/templates.py @@ -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()) + diff --git a/main/live-agent-api/repositories/agent.py b/main/live-agent-api/repositories/agent.py index 012bb505a..636f490e7 100644 --- a/main/live-agent-api/repositories/agent.py +++ b/main/live-agent-api/repositories/agent.py @@ -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 + diff --git a/main/live-agent-api/repositories/agent_template.py b/main/live-agent-api/repositories/agent_template.py index e0c0f4cad..0fffa7c37 100644 --- a/main/live-agent-api/repositories/agent_template.py +++ b/main/live-agent-api/repositories/agent_template.py @@ -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 + diff --git a/main/live-agent-api/schemas/agent.py b/main/live-agent-api/schemas/agent.py index 9b197aae6..64f018a19 100644 --- a/main/live-agent-api/schemas/agent.py +++ b/main/live-agent-api/schemas/agent.py @@ -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 diff --git a/main/live-agent-api/services/agent_service.py b/main/live-agent-api/services/agent_service.py index 29f69dcac..4a5478d18 100644 --- a/main/live-agent-api/services/agent_service.py +++ b/main/live-agent-api/services/agent_service.py @@ -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 )