mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge pull request #39 from Plaud-AI/feat_agent_config
Feat agent config
This commit is contained in:
commit
c410fad3c5
9 changed files with 272 additions and 35 deletions
193
main/docker-compose_dokploy.yml
Normal file
193
main/docker-compose_dokploy.yml
Normal file
|
|
@ -0,0 +1,193 @@
|
||||||
|
services:
|
||||||
|
# ============================================================================
|
||||||
|
# xiaozhi-server (Python WebSocket Server)
|
||||||
|
# ============================================================================
|
||||||
|
xiaozhi-esp32-server:
|
||||||
|
build:
|
||||||
|
context: ./xiaozhi-server/
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
image: xiaozhi-esp32-server:local
|
||||||
|
container_name: xiaozhi-esp32-server
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
depends_on:
|
||||||
|
xiaozhi-esp32-server-db:
|
||||||
|
condition: service_healthy
|
||||||
|
xiaozhi-esp32-server-redis:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- xiaozhi-network
|
||||||
|
ports:
|
||||||
|
# WebSocket server
|
||||||
|
- "8000:8000"
|
||||||
|
# HTTP server for vision analysis and OTA
|
||||||
|
- "8003:8003"
|
||||||
|
security_opt:
|
||||||
|
- seccomp:unconfined
|
||||||
|
environment:
|
||||||
|
- TZ=Asia/Shanghai
|
||||||
|
- PYTHONUNBUFFERED=1
|
||||||
|
- LOG_LEVEL=INFO
|
||||||
|
- REGION=LOCAL
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
volumes:
|
||||||
|
# Configuration directory
|
||||||
|
- /home/ubuntu/live-agent/main/xiaozhi-server/data:/opt/xiaozhi-esp32-server/data
|
||||||
|
# Custom config (optional override, uncomment if you need to customize)
|
||||||
|
- /home/ubuntu/live-agent/main/xiaozhi-server/custom_config.yaml:/opt/xiaozhi-esp32-server/custom_config.yaml
|
||||||
|
# Model files (important!)
|
||||||
|
- /home/ubuntu/live-agent/main/xiaozhi-server/models/SenseVoiceSmall:/opt/xiaozhi-esp32-server/models/SenseVoiceSmall
|
||||||
|
- /home/ubuntu/live-agent/main/xiaozhi-server/models/snakers4_silero-vad:/opt/xiaozhi-esp32-server/models/snakers4_silero-vad
|
||||||
|
# Temporary files
|
||||||
|
- /home/ubuntu/live-agent/main/xiaozhi-server/tmp:/opt/xiaozhi-esp32-server/tmp
|
||||||
|
# Music files (optional)
|
||||||
|
- /home/ubuntu/live-agent/main/xiaozhi-server/music:/opt/xiaozhi-esp32-server/music
|
||||||
|
# Logs (optional, for debugging)
|
||||||
|
- /home/ubuntu/live-agent/main/xiaozhi-server/logs:/opt/xiaozhi-esp32-server/logs
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# MySQL Database (for xiaozhi-esp32-server)
|
||||||
|
# ============================================================================
|
||||||
|
xiaozhi-esp32-server-db:
|
||||||
|
image: mysql:8.0
|
||||||
|
container_name: xiaozhi-esp32-server-db
|
||||||
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- xiaozhi-network
|
||||||
|
ports:
|
||||||
|
# Expose MySQL port for debugging (optional)
|
||||||
|
- "3307:3306"
|
||||||
|
volumes:
|
||||||
|
# Persistent database storage
|
||||||
|
- /home/ubuntu/live-agent/main/xiaozhi-server/mysql/data:/var/lib/mysql
|
||||||
|
# MySQL configuration (optional)
|
||||||
|
# - /home/ubuntu/live-agent/main/xiaozhi-server/mysql/conf:/etc/mysql/conf.d
|
||||||
|
environment:
|
||||||
|
- TZ=Asia/Shanghai
|
||||||
|
- MYSQL_ROOT_PASSWORD=123456
|
||||||
|
- MYSQL_DATABASE=xiaozhi_esp32_server
|
||||||
|
- MYSQL_INITDB_ARGS=--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
|
||||||
|
command:
|
||||||
|
- --character-set-server=utf8mb4
|
||||||
|
- --collation-server=utf8mb4_unicode_ci
|
||||||
|
- --default-authentication-plugin=mysql_native_password
|
||||||
|
- --max_connections=1000
|
||||||
|
- --max_allowed_packet=256M
|
||||||
|
logging:
|
||||||
|
driver: "json-file"
|
||||||
|
options:
|
||||||
|
max-size: "10m"
|
||||||
|
max-file: "3"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p123456"]
|
||||||
|
timeout: 45s
|
||||||
|
interval: 10s
|
||||||
|
retries: 10
|
||||||
|
start_period: 60s
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Redis Cache (for xiaozhi-esp32-server)
|
||||||
|
# ============================================================================
|
||||||
|
xiaozhi-esp32-server-redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
container_name: xiaozhi-esp32-server-redis
|
||||||
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- xiaozhi-network
|
||||||
|
ports:
|
||||||
|
# Expose Redis port for debugging (optional)
|
||||||
|
- "6380:6379"
|
||||||
|
volumes:
|
||||||
|
# Persistent Redis data (optional)
|
||||||
|
- /home/ubuntu/live-agent/main/xiaozhi-server/redis/data:/data
|
||||||
|
environment:
|
||||||
|
- TZ=Asia/Shanghai
|
||||||
|
command: redis-server --appendonly yes --maxmemory 512mb --maxmemory-policy allkeys-lru
|
||||||
|
logging:
|
||||||
|
driver: "json-file"
|
||||||
|
options:
|
||||||
|
max-size: "5m"
|
||||||
|
max-file: "3"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 10s
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# live-agent-api Dependencies: Postgres + Minio
|
||||||
|
# ============================================================================
|
||||||
|
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:
|
||||||
|
- /home/ubuntu/live-agent/main/live-agent-api/data/postgres:/var/lib/postgresql/data
|
||||||
|
- /home/ubuntu/live-agent/main/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:
|
||||||
|
- "19000:9000"
|
||||||
|
- "19001:9001"
|
||||||
|
volumes:
|
||||||
|
- /home/ubuntu/live-agent/main/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
|
||||||
|
# ============================================================================
|
||||||
|
live-agent-api:
|
||||||
|
build:
|
||||||
|
context: ./live-agent-api
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: live-agent-api
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: postgresql+asyncpg://postgres:postgres@live-agent-postgres:5432/live_agent
|
||||||
|
S3_ENDPOINT_URL: http://live-agent-minio:9000
|
||||||
|
DEBUG: "True" # 如果是正式生产,可改成 "False"
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
networks:
|
||||||
|
- xiaozhi-network
|
||||||
|
depends_on:
|
||||||
|
live-agent-postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
live-agent-minio:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Networks
|
||||||
|
# ============================================================================
|
||||||
|
networks:
|
||||||
|
xiaozhi-network:
|
||||||
|
driver: bridge
|
||||||
|
name: xiaozhi-network
|
||||||
|
|
@ -98,6 +98,7 @@ async def resolve_agent_by_wake(
|
||||||
data=DeviceAgentResolveResponse(
|
data=DeviceAgentResolveResponse(
|
||||||
device_id=resolved.device_id,
|
device_id=resolved.device_id,
|
||||||
agent_id=resolved.agent_id,
|
agent_id=resolved.agent_id,
|
||||||
|
owner_id=resolved.owner_id, # Device owner's user_id for memory storage
|
||||||
is_default=resolved.is_default,
|
is_default=resolved.is_default,
|
||||||
match_type=resolved.match_type,
|
match_type=resolved.match_type,
|
||||||
agent_config=agent_cfg,
|
agent_config=agent_cfg,
|
||||||
|
|
|
||||||
|
|
@ -44,6 +44,11 @@ DEBUG=True
|
||||||
# External Services
|
# External Services
|
||||||
FISH_API_KEY=your-fish-audio-api-key-here
|
FISH_API_KEY=your-fish-audio-api-key-here
|
||||||
|
|
||||||
|
# MemU Configuration (Memory Service)
|
||||||
|
# Get your API key from: https://app.memu.so/api-key/
|
||||||
|
MEMU_API_KEY=your-memu-api-key-here
|
||||||
|
MEMU_BASE_URL=https://api.memu.so
|
||||||
|
|
||||||
# OpenAI Configuration
|
# OpenAI Configuration
|
||||||
OPENAI_API_KEY=sk-your-openai-api-key-here
|
OPENAI_API_KEY=sk-your-openai-api-key-here
|
||||||
OPENAI_MODEL=gpt-4o-mini
|
OPENAI_MODEL=gpt-4o-mini
|
||||||
|
|
|
||||||
|
|
@ -65,6 +65,7 @@ class DeviceAgentResolveResponse(BaseModel):
|
||||||
"""Resolve agent for device by wake word or default"""
|
"""Resolve agent for device by wake word or default"""
|
||||||
device_id: str
|
device_id: str
|
||||||
agent_id: str
|
agent_id: str
|
||||||
|
owner_id: Optional[str] = None # Device owner's user_id for memory storage
|
||||||
is_default: bool
|
is_default: bool
|
||||||
match_type: Literal["wake_word", "default"]
|
match_type: Literal["wake_word", "default"]
|
||||||
agent_config: AgentConfigResponse
|
agent_config: AgentConfigResponse
|
||||||
|
|
|
||||||
|
|
@ -267,6 +267,7 @@ class DeviceService:
|
||||||
return DeviceAgentResolveResponse(
|
return DeviceAgentResolveResponse(
|
||||||
device_id=device_id,
|
device_id=device_id,
|
||||||
agent_id=matched_agent.agent_id,
|
agent_id=matched_agent.agent_id,
|
||||||
|
owner_id=device.owner_id, # Device owner's user_id for memory storage
|
||||||
is_default=matched_binding.is_default,
|
is_default=matched_binding.is_default,
|
||||||
match_type=match_type,
|
match_type=match_type,
|
||||||
agent_config=agent_config,
|
agent_config=agent_config,
|
||||||
|
|
|
||||||
|
|
@ -28,10 +28,11 @@ class MemoryService:
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def _headers(self) -> dict:
|
def _headers(self) -> dict:
|
||||||
"""构造请求头"""
|
"""构造请求头(MEMu API v2 使用 Bearer Token)"""
|
||||||
return {
|
return {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
"X-API-Key": self.api_key
|
"Accept": "application/json",
|
||||||
|
"Authorization": f"Bearer {self.api_key}"
|
||||||
}
|
}
|
||||||
|
|
||||||
async def _request(
|
async def _request(
|
||||||
|
|
@ -151,24 +152,58 @@ class MemoryService:
|
||||||
return self._mock_delete(user_id, agent_id, memory_item_id)
|
return self._mock_delete(user_id, agent_id, memory_item_id)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
async def _memu_search(self, user_id: str, agent_ids: List[str], summary: Optional[str] = None) -> dict:
|
async def _memu_search(self, user_id: str, agent_ids: List[str], query: Optional[str] = None) -> dict:
|
||||||
"""POST /memory-items/search(失败时 fallback 到 mock)
|
"""调用 MEMu API v2 查询记忆(失败时 fallback 到 mock)
|
||||||
|
|
||||||
summary 为空时返回该 agent 的全量记忆
|
统一使用 /api/v2/memory/retrieve/related-memory-items 搜索接口
|
||||||
|
- 有 query 时:使用具体关键词搜索
|
||||||
|
- 无 query 时:使用通用 query 获取全量记忆
|
||||||
|
|
||||||
|
注意:MEMu API 每次只支持单个 agent_id,需要对多个 agent 分别查询后合并
|
||||||
"""
|
"""
|
||||||
|
all_items = []
|
||||||
|
|
||||||
|
# 无 query 时使用通用搜索词获取全量记忆
|
||||||
|
search_query = query if query else "记忆 用户 事件 偏好"
|
||||||
|
|
||||||
|
for agent_id in agent_ids:
|
||||||
try:
|
try:
|
||||||
payload = {
|
payload = {
|
||||||
"user_id": user_id,
|
"user_id": user_id,
|
||||||
"agent_ids": agent_ids,
|
"agent_id": agent_id,
|
||||||
|
"query": search_query,
|
||||||
|
"top_k": 100, # 获取更多结果
|
||||||
|
"min_similarity": 0.1 if not query else 0.3 # 无 query 时降低相似度阈值
|
||||||
}
|
}
|
||||||
# 只有 summary 有值时才加入 payload
|
data = await self._request("POST", "/api/v2/memory/retrieve/related-memory-items", payload=payload)
|
||||||
if summary:
|
|
||||||
payload["summary"] = summary
|
# 提取 related_memories 列表,解析嵌套的 memory 对象
|
||||||
return await self._request("POST", "/memory-items/search", payload=payload)
|
related_memories = data.get("related_memories", [])
|
||||||
except Exception:
|
for rm in related_memories:
|
||||||
if self.use_mock:
|
memory = rm.get("memory", {})
|
||||||
return self._mock_search(user_id, agent_ids, summary)
|
if memory:
|
||||||
raise
|
# 标准化字段名
|
||||||
|
item = {
|
||||||
|
"id": memory.get("memory_id", ""),
|
||||||
|
"agent_id": agent_id,
|
||||||
|
"user_id": user_id,
|
||||||
|
"memory_type": memory.get("category", "profile"),
|
||||||
|
"summary": memory.get("content", ""),
|
||||||
|
"created_at": memory.get("created_at", ""),
|
||||||
|
"updated_at": memory.get("updated_at", ""),
|
||||||
|
}
|
||||||
|
all_items.append(item)
|
||||||
|
except Exception as e:
|
||||||
|
# 单个 agent 查询失败,继续处理其他 agent
|
||||||
|
import logging
|
||||||
|
logging.warning(f"MEMu query failed for agent {agent_id}: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 如果所有 agent 都失败,尝试 mock fallback
|
||||||
|
if not all_items and self.use_mock:
|
||||||
|
return self._mock_search(user_id, agent_ids, query)
|
||||||
|
|
||||||
|
return {"memory_items": all_items}
|
||||||
|
|
||||||
# ==================== 对外 API:Memory CRUD ====================
|
# ==================== 对外 API:Memory CRUD ====================
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -260,16 +260,22 @@ class MemuHandler(BaseHandler):
|
||||||
# 将MEMu对象转换为可序列化的字典
|
# 将MEMu对象转换为可序列化的字典
|
||||||
data = self._convert_to_dict(result)
|
data = self._convert_to_dict(result)
|
||||||
|
|
||||||
# 确保metadata被正确返回
|
# 提取 related_memories 列表(SDK 返回结构为 {related_memories: [...], query: ..., total_found: N})
|
||||||
if data and isinstance(data, list):
|
memories = []
|
||||||
for memory in data:
|
if isinstance(data, dict):
|
||||||
if "metadata" not in memory:
|
memories = data.get("related_memories", [])
|
||||||
|
elif isinstance(data, list):
|
||||||
|
memories = data
|
||||||
|
|
||||||
|
# 确保 metadata 被正确返回
|
||||||
|
for memory in memories:
|
||||||
|
if isinstance(memory, dict) and "metadata" not in memory:
|
||||||
memory["metadata"] = {}
|
memory["metadata"] = {}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"success": True,
|
"success": True,
|
||||||
"data": data,
|
"data": memories,
|
||||||
"message": f"搜索成功,找到 {len(data) if data else 0} 条记忆"
|
"message": f"搜索成功,找到 {len(memories)} 条记忆"
|
||||||
}
|
}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.bind(tag=TAG).error(f"搜索记忆失败: {e}")
|
self.logger.bind(tag=TAG).error(f"搜索记忆失败: {e}")
|
||||||
|
|
|
||||||
|
|
@ -81,6 +81,7 @@ class ConnectionHandler:
|
||||||
self.websocket = None
|
self.websocket = None
|
||||||
self.headers = None
|
self.headers = None
|
||||||
self.device_id = None
|
self.device_id = None
|
||||||
|
self.owner_id = None # Device owner's user_id for memory storage
|
||||||
self.client_ip = None
|
self.client_ip = None
|
||||||
self.prompt = None
|
self.prompt = None
|
||||||
self.welcome_msg = None
|
self.welcome_msg = None
|
||||||
|
|
@ -790,8 +791,10 @@ class ConnectionHandler:
|
||||||
if self.memory is None:
|
if self.memory is None:
|
||||||
return
|
return
|
||||||
"""初始化记忆模块"""
|
"""初始化记忆模块"""
|
||||||
|
# Use owner_id (real user_id) for memory storage, fallback to device_id if not available
|
||||||
|
memory_user_id = self.owner_id if self.owner_id else self.device_id
|
||||||
self.memory.init_memory(
|
self.memory.init_memory(
|
||||||
role_id=self.device_id,
|
role_id=memory_user_id,
|
||||||
llm=self.llm,
|
llm=self.llm,
|
||||||
agent_id=self.agent_id,
|
agent_id=self.agent_id,
|
||||||
summary_memory=self.config.get("summaryMemory", None),
|
summary_memory=self.config.get("summaryMemory", None),
|
||||||
|
|
@ -966,6 +969,7 @@ class ConnectionHandler:
|
||||||
self.need_bind = True
|
self.need_bind = True
|
||||||
return False
|
return False
|
||||||
self.agent_id = resolved.get("agent_id")
|
self.agent_id = resolved.get("agent_id")
|
||||||
|
self.owner_id = resolved.get("owner_id") # Device owner's user_id
|
||||||
private_config = resolved.get("agent_config")
|
private_config = resolved.get("agent_config")
|
||||||
|
|
||||||
if private_config is None:
|
if private_config is None:
|
||||||
|
|
|
||||||
|
|
@ -313,12 +313,3 @@ class MemoryProvider(MemoryProviderBase):
|
||||||
params = {"user_id": self.role_id, "agent_id": self.agent_id}
|
params = {"user_id": self.role_id, "agent_id": self.agent_id}
|
||||||
return self._request("DELETE", f"/memory-items/{memory_item_id}", params=params)
|
return self._request("DELETE", f"/memory-items/{memory_item_id}", params=params)
|
||||||
|
|
||||||
@require_memu
|
|
||||||
def search_memory_items(self, summary: str) -> Dict[str, Any]:
|
|
||||||
"""查询记忆记录
|
|
||||||
|
|
||||||
Args:
|
|
||||||
summary: 搜索关键词
|
|
||||||
"""
|
|
||||||
payload = self._base_payload(summary=summary)
|
|
||||||
return self._request("POST", "/memory-items/search", payload=payload)
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue