mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat: fit with new api
This commit is contained in:
parent
03eb1d8636
commit
600cba974a
17 changed files with 319 additions and 100 deletions
|
|
@ -6,6 +6,7 @@ from infra import get_db, get_s3
|
||||||
from services.agent_service import agent_service
|
from services.agent_service import agent_service
|
||||||
from utils.response import success_response
|
from utils.response import success_response
|
||||||
from api.auth import get_current_user_id
|
from api.auth import get_current_user_id
|
||||||
|
from schemas.agent import AgentResponse
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
@ -43,7 +44,20 @@ async def get_agent_detail(
|
||||||
):
|
):
|
||||||
"""Get agent detail"""
|
"""Get agent detail"""
|
||||||
agent = await agent_service.get_agent_detail(db=db, agent_id=agent_id)
|
agent = await agent_service.get_agent_detail(db=db, agent_id=agent_id)
|
||||||
return success_response(data=agent.model_dump())
|
|
||||||
|
|
||||||
|
agent_response = AgentResponse(
|
||||||
|
agent_id=agent.agent_id,
|
||||||
|
name=agent.name,
|
||||||
|
avatar_url=agent.avatar_url,
|
||||||
|
description=agent.description,
|
||||||
|
voice_id=agent.voice_id,
|
||||||
|
instruction=agent.instruction,
|
||||||
|
voice_opening=agent.voice_opening,
|
||||||
|
voice_closing=agent.voice_closing,
|
||||||
|
created_at=agent.created_at,
|
||||||
|
)
|
||||||
|
return success_response(data=agent_response.model_dump())
|
||||||
|
|
||||||
|
|
||||||
@router.post("", summary="Create Agent")
|
@router.post("", summary="Create Agent")
|
||||||
|
|
|
||||||
|
|
@ -2,18 +2,58 @@ from fastapi import APIRouter, Depends
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from infra import get_db
|
from infra import get_db
|
||||||
|
from infra.fishaudio import get_fish_audio
|
||||||
from services.agent_service import agent_service
|
from services.agent_service import agent_service
|
||||||
from utils.response import success_response
|
from utils.response import success_response
|
||||||
|
from schemas.agent import AgentConfigResponse
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
@router.get("/agents/{agent_id}/config", summary="Get a specified agent's config")
|
@router.get("/agents/{agent_id}/config", summary="Get agent config for backend services")
|
||||||
async def get_agent_config(
|
async def get_agent_config(
|
||||||
agent_id: str,
|
agent_id: str,
|
||||||
db: AsyncSession = Depends(get_db)
|
db: AsyncSession = Depends(get_db),
|
||||||
|
fish_client = Depends(get_fish_audio)
|
||||||
):
|
):
|
||||||
"""Get agent configuration for xiaozhi-server"""
|
"""
|
||||||
config = await agent_service.get_agent_config(db=db, agent_id=agent_id)
|
Get agent runtime configuration for xiaozhi-server
|
||||||
return success_response(data=config.model_dump())
|
|
||||||
|
This is an internal API for service-to-service communication:
|
||||||
|
- No authentication required
|
||||||
|
- Returns agent config with voice language info from Fish Audio
|
||||||
|
- Used by xiaozhi-server to drive AI conversations
|
||||||
|
|
||||||
|
Flow:
|
||||||
|
1. Get agent config by agent_id
|
||||||
|
2. If voice_id exists, fetch voice info from Fish Audio
|
||||||
|
3. Extract language and merge into response
|
||||||
|
"""
|
||||||
|
# Step 1: Get agent config
|
||||||
|
agent = await agent_service.get_agent_detail(db=db, agent_id=agent_id)
|
||||||
|
|
||||||
|
# Step 2: If voice_id exists, fetch language from Fish Audio
|
||||||
|
language = None
|
||||||
|
if agent.voice_id:
|
||||||
|
try:
|
||||||
|
fish_voice = await fish_client.voices.get(agent.voice_id)
|
||||||
|
if fish_voice and hasattr(fish_voice, 'languages') and fish_voice.languages:
|
||||||
|
# Fish Audio returns a list of languages, take the first one
|
||||||
|
language = fish_voice.languages[0] if isinstance(fish_voice.languages, list) else fish_voice.languages
|
||||||
|
except Exception as e:
|
||||||
|
# If Fish Audio API fails, log but don't fail the request
|
||||||
|
print(f"Warning: Failed to fetch voice language for {agent.voice_id}: {e}")
|
||||||
|
|
||||||
|
# Step 3: Merge voice language into response
|
||||||
|
response = AgentConfigResponse(
|
||||||
|
agent_id=agent.agent_id,
|
||||||
|
name=agent.name,
|
||||||
|
voice_id=agent.voice_id,
|
||||||
|
language=language,
|
||||||
|
instruction=agent.instruction,
|
||||||
|
voice_opening=agent.voice_opening,
|
||||||
|
voice_closing=agent.voice_closing,
|
||||||
|
)
|
||||||
|
|
||||||
|
return success_response(data=response.model_dump())
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,6 @@ class AgentResponse(BaseModel):
|
||||||
voice_opening: Optional[str] = None
|
voice_opening: Optional[str] = None
|
||||||
voice_closing: Optional[str] = None
|
voice_closing: Optional[str] = None
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
updated_at: datetime
|
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
from_attributes = True
|
from_attributes = True
|
||||||
|
|
@ -53,10 +52,8 @@ class AgentConfigResponse(BaseModel):
|
||||||
agent_id: str
|
agent_id: str
|
||||||
name: str
|
name: str
|
||||||
voice_id: Optional[str] = None
|
voice_id: Optional[str] = None
|
||||||
|
language: Optional[str] = None # Voice language from Fish Audio
|
||||||
instruction: str
|
instruction: str
|
||||||
voice_opening: Optional[str] = None
|
voice_opening: Optional[str] = None
|
||||||
voice_closing: Optional[str] = None
|
voice_closing: Optional[str] = None
|
||||||
|
|
||||||
class Config:
|
|
||||||
from_attributes = True
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,7 @@ class AgentService:
|
||||||
"""
|
"""
|
||||||
agents, next_cursor, has_more = await Agent.get_agents_by_owner(
|
agents, next_cursor, has_more = await Agent.get_agents_by_owner(
|
||||||
db,
|
db,
|
||||||
owner_id=owner_id,
|
owner_id=owner_id,
|
||||||
cursor=cursor,
|
cursor=cursor,
|
||||||
limit=page_size
|
limit=page_size
|
||||||
)
|
)
|
||||||
|
|
@ -56,13 +56,13 @@ class AgentService:
|
||||||
self,
|
self,
|
||||||
db: AsyncSession,
|
db: AsyncSession,
|
||||||
agent_id: str
|
agent_id: str
|
||||||
) -> AgentResponse:
|
) -> AgentModel:
|
||||||
"""Get agent detail"""
|
"""Get agent detail"""
|
||||||
agent = await Agent.get_by_id(db, agent_id)
|
agent = await Agent.get_by_id(db, agent_id)
|
||||||
if not agent:
|
if not agent:
|
||||||
raise NotFoundException("Agent not found")
|
raise NotFoundException("Agent not found")
|
||||||
|
|
||||||
return AgentResponse.model_validate(agent)
|
return agent
|
||||||
|
|
||||||
async def create_agent(
|
async def create_agent(
|
||||||
self,
|
self,
|
||||||
|
|
@ -178,18 +178,7 @@ class AgentService:
|
||||||
|
|
||||||
# Delete agent
|
# Delete agent
|
||||||
await Agent.delete(db, agent_id)
|
await Agent.delete(db, agent_id)
|
||||||
|
|
||||||
async def get_agent_config(
|
|
||||||
self,
|
|
||||||
db: AsyncSession,
|
|
||||||
agent_id: str
|
|
||||||
) -> AgentConfigResponse:
|
|
||||||
"""Get agent configuration for xiaozhi-server"""
|
|
||||||
agent = await Agent.get_by_id(db, agent_id)
|
|
||||||
if not agent:
|
|
||||||
raise NotFoundException("Agent not found")
|
|
||||||
|
|
||||||
return AgentConfigResponse.model_validate(agent)
|
|
||||||
|
|
||||||
|
|
||||||
agent_service = AgentService()
|
agent_service = AgentService()
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import os
|
||||||
import yaml
|
import yaml
|
||||||
from collections.abc import Mapping
|
from collections.abc import Mapping
|
||||||
from config.manage_api_client import init_service, get_server_config, get_agent_models
|
from config.manage_api_client import init_service, get_server_config, get_agent_models
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
def get_project_dir():
|
def get_project_dir():
|
||||||
"""获取项目根目录"""
|
"""获取项目根目录"""
|
||||||
|
|
@ -29,10 +29,24 @@ def load_config():
|
||||||
|
|
||||||
# 加载默认配置
|
# 加载默认配置
|
||||||
# default_config = read_config(default_config_path)
|
# default_config = read_config(default_config_path)
|
||||||
custom_config = read_config(custom_config_path)
|
config = read_config(custom_config_path)
|
||||||
|
config["read_config_from_live_agent_api"] = True
|
||||||
if custom_config.get("manager-api", {}).get("url"):
|
# load environment variables
|
||||||
config = get_config_from_api(custom_config)
|
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 custom_config.get("manager-api", {}).get("url"):
|
||||||
|
# config = get_config_from_api(custom_config)
|
||||||
# else:
|
# else:
|
||||||
# # 合并配置
|
# # 合并配置
|
||||||
# config = merge_configs(default_config, custom_config)
|
# config = merge_configs(default_config, custom_config)
|
||||||
|
|
|
||||||
49
main/xiaozhi-server/config/live_agent_api_client.py
Normal file
49
main/xiaozhi-server/config/live_agent_api_client.py
Normal file
|
|
@ -0,0 +1,49 @@
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from config.logger import setup_logging
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
logger = setup_logging()
|
||||||
|
|
||||||
|
def get_agent_config_from_api(agent_id: str, config: dict) -> Optional[dict]:
|
||||||
|
"""
|
||||||
|
Get agent configuration from live-agent-api
|
||||||
|
|
||||||
|
Args:
|
||||||
|
agent_id: Agent ID
|
||||||
|
config: System config containing live-agent-api URL
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Agent config dict or None if failed
|
||||||
|
"""
|
||||||
|
|
||||||
|
live_api_config = config.get("live-agent-api", {})
|
||||||
|
base_url = live_api_config.get("url", "http://live-agent-api:8080/api/live_agent/v1")
|
||||||
|
timeout = live_api_config.get("timeout", 10)
|
||||||
|
|
||||||
|
url = f"{base_url}/internal/agents/{agent_id}/config"
|
||||||
|
|
||||||
|
try:
|
||||||
|
with httpx.Client(timeout=timeout) as client:
|
||||||
|
response = client.request("GET", url)
|
||||||
|
response.raise_for_status()
|
||||||
|
result = response.json()
|
||||||
|
|
||||||
|
# Extract data from success_response format
|
||||||
|
if result.get("code") == 200 and "data" in result:
|
||||||
|
agent_config = result["data"]
|
||||||
|
logger.info(f"Successfully fetched agent config for agent_id={agent_id}")
|
||||||
|
return agent_config
|
||||||
|
else:
|
||||||
|
logger.error(f"Invalid response format from live-agent-api: {result}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
except httpx.HTTPStatusError as e:
|
||||||
|
if e.response.status_code == 404:
|
||||||
|
logger.error(f"Agent not found: agent_id={agent_id}")
|
||||||
|
else:
|
||||||
|
logger.error(f"HTTP error fetching agent config: {e}")
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to fetch agent config for {agent_id}: {e}")
|
||||||
|
return None
|
||||||
|
|
@ -80,7 +80,7 @@ class OTAHandler(BaseHandler):
|
||||||
self.logger.bind(tag=TAG).info(f"OTA请求ClientID: {client_id}")
|
self.logger.bind(tag=TAG).info(f"OTA请求ClientID: {client_id}")
|
||||||
else:
|
else:
|
||||||
raise Exception("OTA请求ClientID为空")
|
raise Exception("OTA请求ClientID为空")
|
||||||
|
|
||||||
data_json = json.loads(data)
|
data_json = json.loads(data)
|
||||||
|
|
||||||
server_config = self.config["server"]
|
server_config = self.config["server"]
|
||||||
|
|
|
||||||
|
|
@ -41,9 +41,9 @@ from config.manage_api_client import DeviceNotFoundException, DeviceBindExceptio
|
||||||
from core.utils.prompt_manager import PromptManager
|
from core.utils.prompt_manager import PromptManager
|
||||||
from core.utils.voiceprint_provider import VoiceprintProvider
|
from core.utils.voiceprint_provider import VoiceprintProvider
|
||||||
from core.utils import textUtils
|
from core.utils import textUtils
|
||||||
|
from config.live_agent_api_client import get_agent_config_from_api
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
auto_import_modules("plugins_func.functions")
|
auto_import_modules("plugins_func.functions")
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -71,6 +71,7 @@ class ConnectionHandler:
|
||||||
self.need_bind = False
|
self.need_bind = False
|
||||||
self.bind_code = None
|
self.bind_code = None
|
||||||
self.read_config_from_api = self.config.get("read_config_from_api", False)
|
self.read_config_from_api = self.config.get("read_config_from_api", False)
|
||||||
|
self.read_config_from_live_agent_api = self.config.get("read_config_from_live_agent_api", False)
|
||||||
|
|
||||||
self.websocket = None
|
self.websocket = None
|
||||||
self.headers = None
|
self.headers = None
|
||||||
|
|
@ -160,6 +161,12 @@ class ConnectionHandler:
|
||||||
# 初始化提示词管理器
|
# 初始化提示词管理器
|
||||||
self.prompt_manager = PromptManager(config, self.logger)
|
self.prompt_manager = PromptManager(config, self.logger)
|
||||||
|
|
||||||
|
# agent-related configs
|
||||||
|
self._instruction = None
|
||||||
|
self._voice_opening = None
|
||||||
|
self._voice_closing = None
|
||||||
|
self._language = None
|
||||||
|
|
||||||
async def handle_connection(self, ws):
|
async def handle_connection(self, ws):
|
||||||
try:
|
try:
|
||||||
# 获取并验证headers
|
# 获取并验证headers
|
||||||
|
|
@ -176,6 +183,7 @@ class ConnectionHandler:
|
||||||
)
|
)
|
||||||
|
|
||||||
self.device_id = self.headers.get("device-id", None)
|
self.device_id = self.headers.get("device-id", None)
|
||||||
|
self.agent_id = self.headers.get("agent-id", None)
|
||||||
|
|
||||||
# 认证通过,继续处理
|
# 认证通过,继续处理
|
||||||
self.websocket = ws
|
self.websocket = ws
|
||||||
|
|
@ -192,11 +200,12 @@ class ConnectionHandler:
|
||||||
# 启动超时检查任务
|
# 启动超时检查任务
|
||||||
self.timeout_task = asyncio.create_task(self._check_timeout())
|
self.timeout_task = asyncio.create_task(self._check_timeout())
|
||||||
|
|
||||||
|
# todo: welcome message need to be set after private config is loaded
|
||||||
self.welcome_msg = self.config["xiaozhi"]
|
self.welcome_msg = self.config["xiaozhi"]
|
||||||
self.welcome_msg["session_id"] = self.session_id
|
self.welcome_msg["session_id"] = self.session_id
|
||||||
|
|
||||||
# 获取差异化配置
|
# 获取差异化配置
|
||||||
self._initialize_private_config()
|
self._initialize_agent_config()
|
||||||
# 异步初始化
|
# 异步初始化
|
||||||
self.executor.submit(self._initialize_components)
|
self.executor.submit(self._initialize_components)
|
||||||
|
|
||||||
|
|
@ -404,16 +413,6 @@ class ConnectionHandler:
|
||||||
)
|
)
|
||||||
self.logger = create_connection_logger(self.selected_module_str)
|
self.logger = create_connection_logger(self.selected_module_str)
|
||||||
|
|
||||||
"""初始化组件"""
|
|
||||||
if self.config.get("prompt") is not None:
|
|
||||||
user_prompt = self.config["prompt"]
|
|
||||||
# 使用快速提示词进行初始化
|
|
||||||
prompt = self.prompt_manager.get_quick_prompt(user_prompt)
|
|
||||||
self.change_system_prompt(prompt)
|
|
||||||
self.logger.bind(tag=TAG).info(
|
|
||||||
f"快速初始化组件: prompt成功 {prompt[:50]}..."
|
|
||||||
)
|
|
||||||
|
|
||||||
"""初始化本地组件"""
|
"""初始化本地组件"""
|
||||||
if self.vad is None:
|
if self.vad is None:
|
||||||
self.vad = self._vad
|
self.vad = self._vad
|
||||||
|
|
@ -466,9 +465,10 @@ class ConnectionHandler:
|
||||||
|
|
||||||
# 构建增强的系统提示词(返回 (enhanced_prompt, role_tts_config))
|
# 构建增强的系统提示词(返回 (enhanced_prompt, role_tts_config))
|
||||||
result = self.prompt_manager.build_enhanced_prompt(
|
result = self.prompt_manager.build_enhanced_prompt(
|
||||||
self.config["prompt"],
|
user_prompt=self._instruction,
|
||||||
self.device_id,
|
device_id=self.device_id,
|
||||||
self.client_ip,
|
client_ip=self.client_ip,
|
||||||
|
language=self._language,
|
||||||
user_persona=user_persona,
|
user_persona=user_persona,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -655,35 +655,6 @@ class ConnectionHandler:
|
||||||
init_vad = check_vad_update(self.common_config, private_config)
|
init_vad = check_vad_update(self.common_config, private_config)
|
||||||
init_asr = check_asr_update(self.common_config, private_config)
|
init_asr = check_asr_update(self.common_config, private_config)
|
||||||
|
|
||||||
if init_vad:
|
|
||||||
self.config["VAD"] = private_config["VAD"]
|
|
||||||
self.config["selected_module"]["VAD"] = private_config["selected_module"][
|
|
||||||
"VAD"
|
|
||||||
]
|
|
||||||
if init_asr:
|
|
||||||
self.config["ASR"] = private_config["ASR"]
|
|
||||||
self.config["selected_module"]["ASR"] = private_config["selected_module"][
|
|
||||||
"ASR"
|
|
||||||
]
|
|
||||||
if private_config.get("TTS", None) is not None:
|
|
||||||
init_tts = True
|
|
||||||
self.config["TTS"] = private_config["TTS"]
|
|
||||||
self.config["selected_module"]["TTS"] = private_config["selected_module"][
|
|
||||||
"TTS"
|
|
||||||
]
|
|
||||||
# 标记 API 已设置 TTS 配置(优先级1)
|
|
||||||
self.config["_api_tts_applied"] = True
|
|
||||||
if private_config.get("LLM", None) is not None:
|
|
||||||
init_llm = True
|
|
||||||
self.config["LLM"] = private_config["LLM"]
|
|
||||||
self.config["selected_module"]["LLM"] = private_config["selected_module"][
|
|
||||||
"LLM"
|
|
||||||
]
|
|
||||||
if private_config.get("VLLM", None) is not None:
|
|
||||||
self.config["VLLM"] = private_config["VLLM"]
|
|
||||||
self.config["selected_module"]["VLLM"] = private_config["selected_module"][
|
|
||||||
"VLLM"
|
|
||||||
]
|
|
||||||
if private_config.get("Memory", None) is not None:
|
if private_config.get("Memory", None) is not None:
|
||||||
init_memory = True
|
init_memory = True
|
||||||
self.config["Memory"] = private_config["Memory"]
|
self.config["Memory"] = private_config["Memory"]
|
||||||
|
|
@ -835,6 +806,56 @@ class ConnectionHandler:
|
||||||
if hasattr(self, "loop") and self.loop:
|
if hasattr(self, "loop") and self.loop:
|
||||||
asyncio.run_coroutine_threadsafe(self.func_handler._initialize(), self.loop)
|
asyncio.run_coroutine_threadsafe(self.func_handler._initialize(), self.loop)
|
||||||
|
|
||||||
|
def _initialize_agent_config(self):
|
||||||
|
"""initialize agent config"""
|
||||||
|
if not self.read_config_from_live_agent_api:
|
||||||
|
return
|
||||||
|
private_config = get_agent_config_from_api(self.agent_id, self.config)
|
||||||
|
# self.logger.bind(tag=TAG).info(f"private_config: {private_config}")
|
||||||
|
# self.logger.bind(tag=TAG).info(f"self.config: {self.config}")
|
||||||
|
self.config["TTS"]["FishSpeech"]["reference_id"] = private_config["voice_id"]
|
||||||
|
self._instruction = private_config["instruction"]
|
||||||
|
self._voice_opening = private_config["voice_opening"]
|
||||||
|
self._voice_closing = private_config["voice_closing"]
|
||||||
|
self._language = private_config["language"]
|
||||||
|
|
||||||
|
init_llm, init_tts, init_memory, init_intent = (
|
||||||
|
True,
|
||||||
|
True,
|
||||||
|
False,
|
||||||
|
False,
|
||||||
|
)
|
||||||
|
|
||||||
|
init_vad = False
|
||||||
|
init_asr = True
|
||||||
|
|
||||||
|
try:
|
||||||
|
modules = initialize_modules(
|
||||||
|
self.logger,
|
||||||
|
self.config,
|
||||||
|
init_vad,
|
||||||
|
init_asr,
|
||||||
|
init_llm,
|
||||||
|
init_tts,
|
||||||
|
init_memory,
|
||||||
|
init_intent,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}")
|
||||||
|
modules = {}
|
||||||
|
if modules.get("tts", None) is not None:
|
||||||
|
self.tts = modules["tts"]
|
||||||
|
if modules.get("vad", None) is not None:
|
||||||
|
self.vad = modules["vad"]
|
||||||
|
if modules.get("asr", None) is not None:
|
||||||
|
self.asr = modules["asr"]
|
||||||
|
if modules.get("llm", None) is not None:
|
||||||
|
self.llm = modules["llm"]
|
||||||
|
if modules.get("intent", None) is not None:
|
||||||
|
self.intent = modules["intent"]
|
||||||
|
if modules.get("memory", None) is not None:
|
||||||
|
self.memory = modules["memory"]
|
||||||
|
|
||||||
def change_system_prompt(self, prompt):
|
def change_system_prompt(self, prompt):
|
||||||
self.prompt = prompt
|
self.prompt = prompt
|
||||||
# 更新系统prompt至上下文
|
# 更新系统prompt至上下文
|
||||||
|
|
|
||||||
|
|
@ -82,12 +82,16 @@ class TTSProvider(TTSProviderBase):
|
||||||
super().__init__(config, delete_audio_file)
|
super().__init__(config, delete_audio_file)
|
||||||
|
|
||||||
self.model = config.get("model", "s1")
|
self.model = config.get("model", "s1")
|
||||||
if config.get("private_voice"):
|
# if config.get("private_voice"):
|
||||||
self.reference_id = config.get("private_voice")
|
# self.reference_id = config.get("private_voice")
|
||||||
else:
|
# else:
|
||||||
self.reference_id = (
|
# self.reference_id = (
|
||||||
None if not config.get("reference_id") else config.get("reference_id")
|
# None if not config.get("reference_id") else config.get("reference_id")
|
||||||
)
|
# )
|
||||||
|
if config.get("reference_id"):
|
||||||
|
self.reference_id = config.get("reference_id")
|
||||||
|
else:
|
||||||
|
self.reference_id = None
|
||||||
self.reference_audio = parse_string_to_list(
|
self.reference_audio = parse_string_to_list(
|
||||||
config.get('ref_audio')if config.get('ref_audio') else config.get("reference_audio")
|
config.get('ref_audio')if config.get('ref_audio') else config.get("reference_audio")
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
from core.utils import tts, llm, intent, memory, vad, asr
|
from core.utils import tts, llm, intent, memory, vad, asr
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
import os
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
|
||||||
|
|
@ -156,6 +156,7 @@ class PromptManager:
|
||||||
device_id: str,
|
device_id: str,
|
||||||
client_ip: str = None,
|
client_ip: str = None,
|
||||||
user_persona: str = None,
|
user_persona: str = None,
|
||||||
|
language: str = None,
|
||||||
*args,
|
*args,
|
||||||
**kwargs
|
**kwargs
|
||||||
) -> str:
|
) -> str:
|
||||||
|
|
@ -170,7 +171,7 @@ class PromptManager:
|
||||||
# 优先使用 API 传入的 prompt(正式部署场景)
|
# 优先使用 API 传入的 prompt(正式部署场景)
|
||||||
profile = user_prompt
|
profile = user_prompt
|
||||||
timezone = self.config.get("timezone", "Asia/Shanghai")
|
timezone = self.config.get("timezone", "Asia/Shanghai")
|
||||||
language = self.config.get("language", "en")
|
language = language
|
||||||
self.logger.bind(tag=TAG).info("使用 API 下发的 profile")
|
self.logger.bind(tag=TAG).info("使用 API 下发的 profile")
|
||||||
else:
|
else:
|
||||||
# API 未提供 prompt,尝试加载本地 role 配置(本地开发场景)
|
# API 未提供 prompt,尝试加载本地 role 配置(本地开发场景)
|
||||||
|
|
|
||||||
|
|
@ -21,8 +21,8 @@ class WebSocketServer:
|
||||||
self.logger,
|
self.logger,
|
||||||
self.config,
|
self.config,
|
||||||
"VAD" in self.config["selected_module"],
|
"VAD" in self.config["selected_module"],
|
||||||
"ASR" in self.config["selected_module"],
|
False,
|
||||||
"LLM" in self.config["selected_module"],
|
False,
|
||||||
False,
|
False,
|
||||||
"Memory" in self.config["selected_module"],
|
"Memory" in self.config["selected_module"],
|
||||||
"Intent" in self.config["selected_module"],
|
"Intent" in self.config["selected_module"],
|
||||||
|
|
@ -75,6 +75,8 @@ class WebSocketServer:
|
||||||
websocket.request.headers["device-id"] = query_params["device-id"][0]
|
websocket.request.headers["device-id"] = query_params["device-id"][0]
|
||||||
if "client-id" in query_params:
|
if "client-id" in query_params:
|
||||||
websocket.request.headers["client-id"] = query_params["client-id"][0]
|
websocket.request.headers["client-id"] = query_params["client-id"][0]
|
||||||
|
if "agent-id" in query_params:
|
||||||
|
websocket.request.headers["agent-id"] = query_params["agent-id"][0]
|
||||||
if "authorization" in query_params:
|
if "authorization" in query_params:
|
||||||
websocket.request.headers["authorization"] = query_params[
|
websocket.request.headers["authorization"] = query_params[
|
||||||
"authorization"
|
"authorization"
|
||||||
|
|
|
||||||
|
|
@ -40,6 +40,9 @@ manager-api:
|
||||||
# This secret is used for local development, it will be replaced by the actual secret when the server is deployed
|
# This secret is used for local development, it will be replaced by the actual secret when the server is deployed
|
||||||
secret: 613be043-dc7e-4f5e-b775-e318e5bc87a3
|
secret: 613be043-dc7e-4f5e-b775-e318e5bc87a3
|
||||||
|
|
||||||
|
live-agent-api:
|
||||||
|
url: http://live-agent-api:8080/api/live_agent/v1
|
||||||
|
|
||||||
# MySQL配置(用于聊天记录和记忆关联)
|
# MySQL配置(用于聊天记录和记忆关联)
|
||||||
mysql:
|
mysql:
|
||||||
host: localhost
|
host: localhost
|
||||||
|
|
@ -189,11 +192,6 @@ prompt: |
|
||||||
# 默认系统提示词模板文件
|
# 默认系统提示词模板文件
|
||||||
prompt_template: agent-base-prompt.txt
|
prompt_template: agent-base-prompt.txt
|
||||||
|
|
||||||
# Role 配置
|
|
||||||
# 指定要加载的 role 配置文件(位于 core/roles/data/目录)
|
|
||||||
# 如果不指定或加载失败,将使用 prompt 字段的内容作为 profile
|
|
||||||
role_id: hospital_assistant
|
|
||||||
|
|
||||||
# 时区配置(用于系统提示词中的时间显示)
|
# 时区配置(用于系统提示词中的时间显示)
|
||||||
# 支持的时区格式:Asia/Shanghai, America/New_York, Europe/London 等
|
# 支持的时区格式:Asia/Shanghai, America/New_York, Europe/London 等
|
||||||
# 默认:Asia/Shanghai
|
# 默认:Asia/Shanghai
|
||||||
|
|
@ -407,7 +405,7 @@ ASR:
|
||||||
# 3.模型可以选择gpt-4o-transcribe或GPT-4o mini Transcribe
|
# 3.模型可以选择gpt-4o-transcribe或GPT-4o mini Transcribe
|
||||||
type: openai
|
type: openai
|
||||||
api_key: 你的OpenAI API密钥
|
api_key: 你的OpenAI API密钥
|
||||||
base_url: https://api.openai.com/v1/audio/transcriptions
|
base_url: https://api.openai.com/v1
|
||||||
model_name: gpt-4o-mini-transcribe
|
model_name: gpt-4o-mini-transcribe
|
||||||
output_dir: tmp/
|
output_dir: tmp/
|
||||||
GroqASR:
|
GroqASR:
|
||||||
|
|
@ -417,8 +415,8 @@ ASR:
|
||||||
# 2.创建api-key https://console.groq.com/keys
|
# 2.创建api-key https://console.groq.com/keys
|
||||||
# 3.模型可以选择whisper-large-v3-turbo或whisper-large-v3(distil-whisper-large-v3-en仅支持英语转录)
|
# 3.模型可以选择whisper-large-v3-turbo或whisper-large-v3(distil-whisper-large-v3-en仅支持英语转录)
|
||||||
type: openai
|
type: openai
|
||||||
api_key: 你的Groq API密钥
|
api_key: your groq api key
|
||||||
base_url: https://api.groq.com/openai/v1/audio/transcriptions
|
base_url: https://api.groq.com/openai/v1
|
||||||
model_name: whisper-large-v3-turbo
|
model_name: whisper-large-v3-turbo
|
||||||
output_dir: tmp/
|
output_dir: tmp/
|
||||||
VoskASR:
|
VoskASR:
|
||||||
|
|
@ -534,6 +532,11 @@ LLM:
|
||||||
model_name: glm-4-flash
|
model_name: glm-4-flash
|
||||||
url: https://open.bigmodel.cn/api/paas/v4/
|
url: https://open.bigmodel.cn/api/paas/v4/
|
||||||
api_key: 你的chat-glm web key
|
api_key: 你的chat-glm web key
|
||||||
|
GroqLLM:
|
||||||
|
type: openai
|
||||||
|
model_name: openai/gpt-oss-20b
|
||||||
|
base_url: https://api.groq.com/openai/v1
|
||||||
|
api_key: your groq api key
|
||||||
OllamaLLM:
|
OllamaLLM:
|
||||||
# 定义LLM API类型
|
# 定义LLM API类型
|
||||||
type: ollama
|
type: ollama
|
||||||
|
|
@ -759,10 +762,8 @@ TTS:
|
||||||
# 参照教程:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/fish-speech-integration.md
|
# 参照教程:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/fish-speech-integration.md
|
||||||
type: fishspeech
|
type: fishspeech
|
||||||
output_dir: tmp/
|
output_dir: tmp/
|
||||||
response_format: wav
|
response_format: pcm
|
||||||
reference_id: null
|
reference_id: null
|
||||||
reference_audio: ["config/assets/wakeup_words.wav",]
|
|
||||||
reference_text: ["哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",]
|
|
||||||
normalize: true
|
normalize: true
|
||||||
max_new_tokens: 1024
|
max_new_tokens: 1024
|
||||||
chunk_length: 200
|
chunk_length: 200
|
||||||
|
|
@ -774,8 +775,8 @@ TTS:
|
||||||
seed: null
|
seed: null
|
||||||
channels: 1
|
channels: 1
|
||||||
rate: 44100
|
rate: 44100
|
||||||
api_key: "你的api_key"
|
sample_rate: 16000
|
||||||
api_url: "http://127.0.0.1:8080/v1/tts"
|
api_key: "your fish speech api key"
|
||||||
GPT_SOVITS_V2:
|
GPT_SOVITS_V2:
|
||||||
# 定义TTS API类型
|
# 定义TTS API类型
|
||||||
#启动tts方法:
|
#启动tts方法:
|
||||||
|
|
@ -1057,3 +1058,14 @@ TTS:
|
||||||
# volume: 50 # 音量:0-100
|
# volume: 50 # 音量:0-100
|
||||||
# speed: 50 # 语速:0-100
|
# speed: 50 # 语速:0-100
|
||||||
# pitch: 50 # 语调:0-100
|
# pitch: 50 # 语调:0-100
|
||||||
|
# ===============================================================================
|
||||||
|
# ============================= Module Selection ================================
|
||||||
|
# ===============================================================================
|
||||||
|
selected_module:
|
||||||
|
VAD: SileroVAD
|
||||||
|
ASR: GroqASR
|
||||||
|
LLM: GroqLLM
|
||||||
|
VLLM: ChatGLMVLLM
|
||||||
|
TTS: FishSpeech
|
||||||
|
Memory: memu
|
||||||
|
Intent: function_call
|
||||||
|
|
@ -164,6 +164,71 @@ services:
|
||||||
retries: 3
|
retries: 3
|
||||||
start_period: 10s
|
start_period: 10s
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# live-agent-api Services
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
live-agent-postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
container_name: live-agent-postgres
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: live_agent
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_PASSWORD: postgres
|
||||||
|
ports:
|
||||||
|
- "5432:5432"
|
||||||
|
volumes:
|
||||||
|
- ../live-agent-api/data/postgres:/var/lib/postgresql/data
|
||||||
|
- ../live-agent-api/init_db.sql:/docker-entrypoint-initdb.d/init_db.sql
|
||||||
|
networks:
|
||||||
|
- xiaozhi-network
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
live-agent-minio:
|
||||||
|
image: minio/minio:latest
|
||||||
|
container_name: live-agent-minio
|
||||||
|
command: server /data --console-address ":9001"
|
||||||
|
environment:
|
||||||
|
MINIO_ROOT_USER: minioadmin
|
||||||
|
MINIO_ROOT_PASSWORD: minioadmin
|
||||||
|
ports:
|
||||||
|
- "9000:9000"
|
||||||
|
- "9001:9001"
|
||||||
|
volumes:
|
||||||
|
- ../live-agent-api/data/minio:/data
|
||||||
|
networks:
|
||||||
|
- xiaozhi-network
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
live-agent-api:
|
||||||
|
build:
|
||||||
|
context: ../live-agent-api
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: live-agent-api
|
||||||
|
env_file:
|
||||||
|
- ../live-agent-api/.env
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: postgresql+asyncpg://postgres:postgres@live-agent-postgres:5432/live_agent
|
||||||
|
S3_ENDPOINT_URL: http://live-agent-minio:9000
|
||||||
|
DEBUG: "True"
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
networks:
|
||||||
|
- xiaozhi-network
|
||||||
|
depends_on:
|
||||||
|
live-agent-postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
live-agent-minio:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
# Networks
|
# Networks
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
|
|
|
||||||
|
|
@ -43,4 +43,6 @@ redis>=4.0.0,<5.0.0
|
||||||
elevenlabs>=1.11.0
|
elevenlabs>=1.11.0
|
||||||
cartesia>=1.0.0
|
cartesia>=1.0.0
|
||||||
deepgram-sdk>=3.0.0
|
deepgram-sdk>=3.0.0
|
||||||
fish-audio-sdk==2025.6.3
|
fish-audio-sdk==2025.6.3
|
||||||
|
|
||||||
|
python-dotenv>=1.0.0
|
||||||
|
|
@ -37,7 +37,7 @@ export async function webSocketConnect(otaUrl, config) {
|
||||||
// 添加认证参数(保持原有逻辑)
|
// 添加认证参数(保持原有逻辑)
|
||||||
connUrl.searchParams.append('device-id', config.deviceId);
|
connUrl.searchParams.append('device-id', config.deviceId);
|
||||||
connUrl.searchParams.append('client-id', config.clientId);
|
connUrl.searchParams.append('client-id', config.clientId);
|
||||||
|
connUrl.searchParams.append('agent-id', config.agentId);
|
||||||
const wsurl = connUrl.toString()
|
const wsurl = connUrl.toString()
|
||||||
|
|
||||||
log(`正在连接: ${wsurl}`, 'info');
|
log(`正在连接: ${wsurl}`, 'info');
|
||||||
|
|
@ -82,7 +82,8 @@ async function sendOTA(otaUrl, config) {
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Device-Id': config.deviceId,
|
'Device-Id': config.deviceId,
|
||||||
'Client-Id': config.clientId
|
'Client-Id': config.clientId,
|
||||||
|
'Agent-Id': config.agentId
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
version: 0,
|
version: 0,
|
||||||
|
|
|
||||||
|
|
@ -275,6 +275,10 @@
|
||||||
<label for="token">认证Token:</label>
|
<label for="token">认证Token:</label>
|
||||||
<input type="text" id="token" value="your-token1" placeholder="认证Token">
|
<input type="text" id="token" value="your-token1" placeholder="认证Token">
|
||||||
</div>
|
</div>
|
||||||
|
<div class="config-item">
|
||||||
|
<label for="agentId">Agent ID:</label>
|
||||||
|
<input type="text" id="agentId" value="agent_01KAGYH1ABYDV5JME6WEN45FBY" placeholder="Agent ID">
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -1791,12 +1795,14 @@
|
||||||
// 获取配置值
|
// 获取配置值
|
||||||
function getConfig() {
|
function getConfig() {
|
||||||
const deviceMac = document.getElementById('deviceMac').value.trim();
|
const deviceMac = document.getElementById('deviceMac').value.trim();
|
||||||
|
log(`AgentID: ${document.getElementById('agentId').value.trim()}`, 'info');
|
||||||
return {
|
return {
|
||||||
deviceId: deviceMac, // 使用MAC地址作为deviceId
|
deviceId: deviceMac, // 使用MAC地址作为deviceId
|
||||||
deviceName: document.getElementById('deviceName').value.trim(),
|
deviceName: document.getElementById('deviceName').value.trim(),
|
||||||
deviceMac: deviceMac,
|
deviceMac: deviceMac,
|
||||||
clientId: document.getElementById('clientId').value.trim(),
|
clientId: document.getElementById('clientId').value.trim(),
|
||||||
token: document.getElementById('token').value.trim()
|
token: document.getElementById('token').value.trim(),
|
||||||
|
agentId: document.getElementById('agentId').value.trim()
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue