diff --git a/main/docker-compose_dokploy.yml b/main/docker-compose_dokploy.yml new file mode 100644 index 000000000..32a432091 --- /dev/null +++ b/main/docker-compose_dokploy.yml @@ -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 diff --git a/main/live-agent-api/api/v1/internal.py b/main/live-agent-api/api/v1/internal.py index 5e7800eb0..f83ad43db 100644 --- a/main/live-agent-api/api/v1/internal.py +++ b/main/live-agent-api/api/v1/internal.py @@ -98,6 +98,7 @@ async def resolve_agent_by_wake( data=DeviceAgentResolveResponse( device_id=resolved.device_id, agent_id=resolved.agent_id, + owner_id=resolved.owner_id, # Device owner's user_id for memory storage is_default=resolved.is_default, match_type=resolved.match_type, agent_config=agent_cfg, diff --git a/main/live-agent-api/env.example b/main/live-agent-api/env.example index d5f94b7e5..754798dde 100644 --- a/main/live-agent-api/env.example +++ b/main/live-agent-api/env.example @@ -44,6 +44,11 @@ DEBUG=True # External Services 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_API_KEY=sk-your-openai-api-key-here OPENAI_MODEL=gpt-4o-mini diff --git a/main/live-agent-api/schemas/device.py b/main/live-agent-api/schemas/device.py index 631f8450c..d8f6d931e 100644 --- a/main/live-agent-api/schemas/device.py +++ b/main/live-agent-api/schemas/device.py @@ -65,6 +65,7 @@ class DeviceAgentResolveResponse(BaseModel): """Resolve agent for device by wake word or default""" device_id: str agent_id: str + owner_id: Optional[str] = None # Device owner's user_id for memory storage is_default: bool match_type: Literal["wake_word", "default"] agent_config: AgentConfigResponse diff --git a/main/live-agent-api/services/device_service.py b/main/live-agent-api/services/device_service.py index a2b66e764..36ed03ad5 100644 --- a/main/live-agent-api/services/device_service.py +++ b/main/live-agent-api/services/device_service.py @@ -267,6 +267,7 @@ class DeviceService: return DeviceAgentResolveResponse( device_id=device_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, match_type=match_type, agent_config=agent_config, diff --git a/main/live-agent-api/services/memory_service.py b/main/live-agent-api/services/memory_service.py index cfdf826fd..78d5481c8 100644 --- a/main/live-agent-api/services/memory_service.py +++ b/main/live-agent-api/services/memory_service.py @@ -28,10 +28,11 @@ class MemoryService: @property def _headers(self) -> dict: - """构造请求头""" + """构造请求头(MEMu API v2 使用 Bearer Token)""" return { "Content-Type": "application/json", - "X-API-Key": self.api_key + "Accept": "application/json", + "Authorization": f"Bearer {self.api_key}" } async def _request( @@ -151,24 +152,58 @@ class MemoryService: return self._mock_delete(user_id, agent_id, memory_item_id) raise - async def _memu_search(self, user_id: str, agent_ids: List[str], summary: Optional[str] = None) -> dict: - """POST /memory-items/search(失败时 fallback 到 mock) + async def _memu_search(self, user_id: str, agent_ids: List[str], query: Optional[str] = None) -> dict: + """调用 MEMu API v2 查询记忆(失败时 fallback 到 mock) - summary 为空时返回该 agent 的全量记忆 + 统一使用 /api/v2/memory/retrieve/related-memory-items 搜索接口 + - 有 query 时:使用具体关键词搜索 + - 无 query 时:使用通用 query 获取全量记忆 + + 注意:MEMu API 每次只支持单个 agent_id,需要对多个 agent 分别查询后合并 """ - try: - payload = { - "user_id": user_id, - "agent_ids": agent_ids, - } - # 只有 summary 有值时才加入 payload - if summary: - payload["summary"] = summary - return await self._request("POST", "/memory-items/search", payload=payload) - except Exception: - if self.use_mock: - return self._mock_search(user_id, agent_ids, summary) - raise + all_items = [] + + # 无 query 时使用通用搜索词获取全量记忆 + search_query = query if query else "记忆 用户 事件 偏好" + + for agent_id in agent_ids: + try: + payload = { + "user_id": user_id, + "agent_id": agent_id, + "query": search_query, + "top_k": 100, # 获取更多结果 + "min_similarity": 0.1 if not query else 0.3 # 无 query 时降低相似度阈值 + } + data = await self._request("POST", "/api/v2/memory/retrieve/related-memory-items", payload=payload) + + # 提取 related_memories 列表,解析嵌套的 memory 对象 + related_memories = data.get("related_memories", []) + for rm in related_memories: + memory = rm.get("memory", {}) + if memory: + # 标准化字段名 + 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 ==================== diff --git a/main/xiaozhi-server/core/api/memu_handler.py b/main/xiaozhi-server/core/api/memu_handler.py index 5b02d55aa..ec96ca61e 100644 --- a/main/xiaozhi-server/core/api/memu_handler.py +++ b/main/xiaozhi-server/core/api/memu_handler.py @@ -260,16 +260,22 @@ class MemuHandler(BaseHandler): # 将MEMu对象转换为可序列化的字典 data = self._convert_to_dict(result) - # 确保metadata被正确返回 - if data and isinstance(data, list): - for memory in data: - if "metadata" not in memory: - memory["metadata"] = {} + # 提取 related_memories 列表(SDK 返回结构为 {related_memories: [...], query: ..., total_found: N}) + memories = [] + if isinstance(data, dict): + 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"] = {} return { "success": True, - "data": data, - "message": f"搜索成功,找到 {len(data) if data else 0} 条记忆" + "data": memories, + "message": f"搜索成功,找到 {len(memories)} 条记忆" } except Exception as e: self.logger.bind(tag=TAG).error(f"搜索记忆失败: {e}") diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index a91bc355d..957537997 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -81,6 +81,7 @@ class ConnectionHandler: self.websocket = None self.headers = None self.device_id = None + self.owner_id = None # Device owner's user_id for memory storage self.client_ip = None self.prompt = None self.welcome_msg = None @@ -790,8 +791,10 @@ class ConnectionHandler: if self.memory is None: 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( - role_id=self.device_id, + role_id=memory_user_id, llm=self.llm, agent_id=self.agent_id, summary_memory=self.config.get("summaryMemory", None), @@ -966,6 +969,7 @@ class ConnectionHandler: self.need_bind = True return False 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") if private_config is None: diff --git a/main/xiaozhi-server/core/providers/memory/memu/memu.py b/main/xiaozhi-server/core/providers/memory/memu/memu.py index ec45f67d8..3bb4b09bf 100644 --- a/main/xiaozhi-server/core/providers/memory/memu/memu.py +++ b/main/xiaozhi-server/core/providers/memory/memu/memu.py @@ -313,12 +313,3 @@ class MemoryProvider(MemoryProviderBase): params = {"user_id": self.role_id, "agent_id": self.agent_id} 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)