diff --git a/main/live-agent-api/api/v1/__init__.py b/main/live-agent-api/api/v1/__init__.py index a680f8b0f..2ccbcf33a 100644 --- a/main/live-agent-api/api/v1/__init__.py +++ b/main/live-agent-api/api/v1/__init__.py @@ -1,5 +1,5 @@ from fastapi import APIRouter -from api.v1 import user, templates, agents, voices, internal, files, chat +from api.v1 import user, templates, agents, voices, internal, files, chat, memories api_router = APIRouter() @@ -24,6 +24,13 @@ api_router.include_router( tags=["Agents"] ) +# Memory routes +api_router.include_router( + memories.router, + prefix="/memories", + tags=["Memories"] +) + # Voice routes api_router.include_router( voices.router, diff --git a/main/live-agent-api/api/v1/memories.py b/main/live-agent-api/api/v1/memories.py new file mode 100644 index 000000000..1c5a73ef2 --- /dev/null +++ b/main/live-agent-api/api/v1/memories.py @@ -0,0 +1,175 @@ +from fastapi import APIRouter, Depends +from sqlalchemy.ext.asyncio import AsyncSession + +from infra import get_db +from api.auth import get_current_user_id +from services.memory_service import memory_service +from utils.response import success_response +from schemas.memory import ( + MemorySearchRequest, + MemoryCreateRequest, + MemoryUpdateRequest, + MemoryDeleteRequest, + MemorySharingGetRequest, + MemorySharingUpdateRequest, +) + +router = APIRouter() + + +# ==================== Memory CRUD ==================== + +@router.post("/search", summary="Search memories") +async def search_memories( + request: MemorySearchRequest, + user_id: str = Depends(get_current_user_id), + db: AsyncSession = Depends(get_db) +): + """ + 搜索记忆(需要 Bearer Token 认证) + + Request Body: + - agent_id: Agent ID + - query: 搜索关键词(可选) + - type: 记忆类型筛选 profile | event(可选) + - cursor: 分页游标(可选) + - limit: 每页数量(默认 20) + - include_shared: 是否包含共享记忆(默认 true) + """ + result = await memory_service.search_memories( + db=db, + user_id=user_id, + agent_id=request.agent_id, + query=request.query, + memory_type=request.type, + cursor=request.cursor, + limit=request.limit, + include_shared=request.include_shared + ) + return success_response(data=result.model_dump()) + + +@router.post("/create", summary="Create memory") +async def create_memory( + request: MemoryCreateRequest, + user_id: str = Depends(get_current_user_id), + db: AsyncSession = Depends(get_db) +): + """ + 创建记忆(需要 Bearer Token 认证) + + Request Body: + - agent_id: Agent ID + - type: 记忆类型 profile | event + - content: 记忆内容 + - title: 标题(event 类型需要) + """ + result = await memory_service.create_memory( + user_id=user_id, + agent_id=request.agent_id, + memory_type=request.type, + content=request.content, + title=request.title + ) + return success_response(data=result.model_dump()) + + +@router.put("/update", summary="Update memory") +async def update_memory( + request: MemoryUpdateRequest, + user_id: str = Depends(get_current_user_id), + db: AsyncSession = Depends(get_db) +): + """ + 更新记忆(需要 Bearer Token 认证) + + Request Body: + - agent_id: Agent ID + - memory_id: 记忆 ID + - title: 新标题(可选) + - content: 新内容(可选) + """ + result = await memory_service.update_memory( + user_id=user_id, + agent_id=request.agent_id, + memory_id=request.memory_id, + title=request.title, + content=request.content + ) + return success_response(data=result.model_dump()) + + +@router.delete("/delete", summary="Delete memory") +async def delete_memory( + request: MemoryDeleteRequest, + user_id: str = Depends(get_current_user_id), + db: AsyncSession = Depends(get_db) +): + """ + 删除记忆(需要 Bearer Token 认证) + + Request Body: + - agent_id: Agent ID + - memory_id: 记忆 ID + """ + await memory_service.delete_memory( + user_id=user_id, + agent_id=request.agent_id, + memory_id=request.memory_id + ) + return success_response(data={"success": True}) + + +# ==================== Memory Sharing Config ==================== + +@router.post("/sharing/get", summary="Get sharing config") +async def get_memory_sharing( + request: MemorySharingGetRequest, + user_id: str = Depends(get_current_user_id), + db: AsyncSession = Depends(get_db) +): + """ + 获取记忆共享配置(需要 Bearer Token 认证) + + Request Body: + - agent_id: Agent ID + + Returns: + - share_type: none | specific | all + - shared_with: 共享目标 Agent ID 列表 + """ + result = await memory_service.get_memory_sharing( + db=db, + user_id=user_id, + agent_id=request.agent_id + ) + return success_response(data=result.model_dump()) + + +@router.put("/sharing/update", summary="Update sharing config") +async def update_memory_sharing( + request: MemorySharingUpdateRequest, + user_id: str = Depends(get_current_user_id), + db: AsyncSession = Depends(get_db) +): + """ + 更新记忆共享配置(需要 Bearer Token 认证) + + Request Body: + - agent_id: Agent ID + - share_type: none | specific | all + - shared_with: 共享目标 Agent ID 列表(share_type=specific 时需要) + + Share types: + - none: 不共享 + - specific: 共享给指定 agents + - all: 共享给所有 agents + """ + result = await memory_service.update_memory_sharing( + db=db, + user_id=user_id, + agent_id=request.agent_id, + share_type=request.share_type, + shared_with=request.shared_with + ) + return success_response(data=result.model_dump()) diff --git a/main/live-agent-api/config/settings.py b/main/live-agent-api/config/settings.py index 49ba9665e..8202ea9d0 100644 --- a/main/live-agent-api/config/settings.py +++ b/main/live-agent-api/config/settings.py @@ -34,6 +34,10 @@ class Settings(BaseSettings): OPENAI_MODEL: str = "gpt-4o-mini" OPENAI_BASE_URL: str = "https://api.openai.com/v1" + # MemU Configuration + MEMU_API_KEY: str = "" + MEMU_BASE_URL: str = "https://api.memu.so" + model_config = SettingsConfigDict( env_file=".env", env_file_encoding="utf-8", diff --git a/main/live-agent-api/init_db.sql b/main/live-agent-api/init_db.sql index 4c33116f3..db6ff32c5 100644 --- a/main/live-agent-api/init_db.sql +++ b/main/live-agent-api/init_db.sql @@ -178,6 +178,56 @@ CREATE TRIGGER update_agent_templates_updated_at FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); +-- ==================== Table: memory_sharing ==================== +-- Memory sharing configuration per user-agent +CREATE TABLE IF NOT EXISTS memory_sharing ( + id SERIAL PRIMARY KEY, + user_id VARCHAR(50) NOT NULL, + agent_id VARCHAR(50) NOT NULL, + share_type VARCHAR(20) NOT NULL CHECK (share_type IN ('none', 'specific', 'all')), + created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), + updated_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), + CONSTRAINT uk_memory_sharing_user_agent UNIQUE (user_id, agent_id) +); + +-- Indexes for memory_sharing table +CREATE INDEX IF NOT EXISTS idx_memory_sharing_user_id ON memory_sharing(user_id); +CREATE INDEX IF NOT EXISTS idx_memory_sharing_agent_id ON memory_sharing(agent_id); +CREATE INDEX IF NOT EXISTS idx_memory_sharing_share_type ON memory_sharing(share_type); + +-- Comments for memory_sharing table +COMMENT ON TABLE memory_sharing IS 'Memory sharing configuration per user-agent pair'; +COMMENT ON COLUMN memory_sharing.user_id IS 'User who owns the memories'; +COMMENT ON COLUMN memory_sharing.agent_id IS 'Source agent whose memories are being shared'; +COMMENT ON COLUMN memory_sharing.share_type IS 'none=no sharing, specific=share with specific agents, all=share with all agents'; + +-- ==================== Table: memory_sharing_targets ==================== +-- Target agents for specific sharing type +CREATE TABLE IF NOT EXISTS memory_sharing_targets ( + id SERIAL PRIMARY KEY, + sharing_id INT NOT NULL, + target_agent_id VARCHAR(50) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), + CONSTRAINT fk_memory_sharing_targets_sharing FOREIGN KEY (sharing_id) + REFERENCES memory_sharing(id) ON DELETE CASCADE, + CONSTRAINT uk_memory_sharing_targets UNIQUE (sharing_id, target_agent_id) +); + +-- Indexes for memory_sharing_targets table +CREATE INDEX IF NOT EXISTS idx_memory_sharing_targets_sharing_id ON memory_sharing_targets(sharing_id); +CREATE INDEX IF NOT EXISTS idx_memory_sharing_targets_target_agent_id ON memory_sharing_targets(target_agent_id); + +-- Comments for memory_sharing_targets table +COMMENT ON TABLE memory_sharing_targets IS 'Target agents for specific memory sharing'; +COMMENT ON COLUMN memory_sharing_targets.sharing_id IS 'Reference to memory_sharing record'; +COMMENT ON COLUMN memory_sharing_targets.target_agent_id IS 'Agent ID that can access the shared memories'; + +-- Create triggers for updated_at on memory_sharing table +CREATE TRIGGER update_memory_sharing_updated_at + BEFORE UPDATE ON memory_sharing + FOR EACH ROW + EXECUTE FUNCTION update_updated_at_column(); + -- ==================== Grant Permissions ==================== -- Grant necessary permissions to postgres user GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO postgres; diff --git a/main/live-agent-api/repositories/__init__.py b/main/live-agent-api/repositories/__init__.py index 817739a45..015efd674 100644 --- a/main/live-agent-api/repositories/__init__.py +++ b/main/live-agent-api/repositories/__init__.py @@ -8,6 +8,7 @@ from .agent import AgentModel from .agent_template import AgentTemplateModel from .voice import VoiceModel from .chat import ChatMessageModel +from .memory_sharing import MemorySharingModel, MemorySharingTargetModel # Import Repository classes from .user import User @@ -16,6 +17,7 @@ from .agent_template import AgentTemplate from .voice import Voice from .chat import ChatMessage from .file import FileRepository +from .memory_sharing import MemorySharingRepository __all__ = [ # ORM Models @@ -24,6 +26,8 @@ __all__ = [ "AgentTemplateModel", "VoiceModel", "ChatMessageModel", + "MemorySharingModel", + "MemorySharingTargetModel", # Repository classes "User", "Agent", @@ -31,5 +35,6 @@ __all__ = [ "Voice", "ChatMessage", "FileRepository", + "MemorySharingRepository", ] diff --git a/main/live-agent-api/repositories/memory_sharing.py b/main/live-agent-api/repositories/memory_sharing.py new file mode 100644 index 000000000..94eb8f8ba --- /dev/null +++ b/main/live-agent-api/repositories/memory_sharing.py @@ -0,0 +1,180 @@ +from datetime import datetime +from typing import Optional, List +from sqlalchemy import String, Integer, TIMESTAMP, ForeignKey, Index, select, delete +from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.ext.asyncio import AsyncSession + +from infra.database import Base, utc_now + + +# ==================== ORM Models ==================== + +class MemorySharingModel(Base): + """记忆共享配置表""" + __tablename__ = "memory_sharing" + + id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + user_id: Mapped[str] = mapped_column(String(50), nullable=False) + agent_id: Mapped[str] = mapped_column(String(50), nullable=False) + share_type: Mapped[str] = mapped_column(String(20), nullable=False) # none, specific, all + created_at: Mapped[datetime] = mapped_column( + TIMESTAMP(timezone=True), + default=utc_now, + nullable=False + ) + updated_at: Mapped[datetime] = mapped_column( + TIMESTAMP(timezone=True), + default=utc_now, + onupdate=utc_now, + nullable=False + ) + + __table_args__ = ( + Index('idx_memory_sharing_user_id', 'user_id'), + Index('idx_memory_sharing_agent_id', 'agent_id'), + ) + + +class MemorySharingTargetModel(Base): + """记忆共享目标表(specific 类型使用)""" + __tablename__ = "memory_sharing_targets" + + id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + sharing_id: Mapped[int] = mapped_column( + Integer, + ForeignKey("memory_sharing.id", ondelete="CASCADE"), + nullable=False + ) + target_agent_id: Mapped[str] = mapped_column(String(50), nullable=False) + created_at: Mapped[datetime] = mapped_column( + TIMESTAMP(timezone=True), + default=utc_now, + nullable=False + ) + + __table_args__ = ( + Index('idx_memory_sharing_targets_sharing_id', 'sharing_id'), + Index('idx_memory_sharing_targets_target_agent_id', 'target_agent_id'), + ) + + +# ==================== Repository ==================== + +class MemorySharingRepository: + """记忆共享配置 Repository""" + + @staticmethod + async def get_config( + db: AsyncSession, + user_id: str, + agent_id: str + ) -> Optional[MemorySharingModel]: + """获取共享配置""" + result = await db.execute( + select(MemorySharingModel).where( + MemorySharingModel.user_id == user_id, + MemorySharingModel.agent_id == agent_id + ) + ) + return result.scalar_one_or_none() + + @staticmethod + async def get_shared_with( + db: AsyncSession, + sharing_id: int + ) -> List[str]: + """获取共享目标 agent 列表""" + result = await db.execute( + select(MemorySharingTargetModel.target_agent_id).where( + MemorySharingTargetModel.sharing_id == sharing_id + ) + ) + return list(result.scalars().all()) + + @staticmethod + async def upsert_config( + db: AsyncSession, + user_id: str, + agent_id: str, + share_type: str, + shared_with: Optional[List[str]] = None + ) -> MemorySharingModel: + """创建或更新共享配置""" + # 查找现有配置 + config = await MemorySharingRepository.get_config(db, user_id, agent_id) + + if config: + # 更新 + config.share_type = share_type + else: + # 创建 + config = MemorySharingModel( + user_id=user_id, + agent_id=agent_id, + share_type=share_type + ) + db.add(config) + + await db.flush() # 获取 config.id + + # 更新共享目标(先删除旧的,再添加新的) + await db.execute( + delete(MemorySharingTargetModel).where( + MemorySharingTargetModel.sharing_id == config.id + ) + ) + + if share_type == "specific" and shared_with: + for target_agent_id in shared_with: + target = MemorySharingTargetModel( + sharing_id=config.id, + target_agent_id=target_agent_id + ) + db.add(target) + + await db.commit() + await db.refresh(config) + return config + + @staticmethod + async def get_agents_sharing_to( + db: AsyncSession, + user_id: str, + target_agent_id: str + ) -> List[str]: + """ + 获取共享记忆给指定 agent 的所有源 agent 列表 + + 条件: + 1. share_type = 'all' 的所有 agent(同一 user 下) + 2. share_type = 'specific' 且 target_agent_id 在 shared_with 列表中 + """ + # 1. share_type = 'all' 的 agents + all_sharing_result = await db.execute( + select(MemorySharingModel.agent_id).where( + MemorySharingModel.user_id == user_id, + MemorySharingModel.share_type == "all", + MemorySharingModel.agent_id != target_agent_id # 排除自己 + ) + ) + all_sharing_agents = list(all_sharing_result.scalars().all()) + + # 2. share_type = 'specific' 且包含 target_agent_id + specific_sharing_result = await db.execute( + select(MemorySharingModel.agent_id) + .join( + MemorySharingTargetModel, + MemorySharingModel.id == MemorySharingTargetModel.sharing_id + ) + .where( + MemorySharingModel.user_id == user_id, + MemorySharingModel.share_type == "specific", + MemorySharingModel.agent_id != target_agent_id, # 排除自己 + MemorySharingTargetModel.target_agent_id == target_agent_id + ) + ) + specific_sharing_agents = list(specific_sharing_result.scalars().all()) + + # 合并去重 + return list(set(all_sharing_agents + specific_sharing_agents)) + diff --git a/main/live-agent-api/schemas/memory.py b/main/live-agent-api/schemas/memory.py new file mode 100644 index 000000000..1016b1fc3 --- /dev/null +++ b/main/live-agent-api/schemas/memory.py @@ -0,0 +1,92 @@ +from datetime import datetime +from typing import Optional, List, Literal +from pydantic import BaseModel, Field + + +# ==================== 基础请求(agent_id,user_id 从 token 获取)==================== + +class MemoryBaseRequest(BaseModel): + """所有 Memory 请求的基类(user_id 从 JWT token 获取)""" + agent_id: str = Field(..., description="Agent ID") + + +# ==================== Memory CRUD 请求 ==================== + +class MemorySearchRequest(MemoryBaseRequest): + """搜索记忆请求""" + query: Optional[str] = Field(None, description="搜索关键词") + type: Optional[Literal["profile", "event"]] = Field(None, description="记忆类型筛选") + cursor: Optional[str] = Field(None, description="分页游标") + limit: int = Field(20, ge=1, le=100, description="每页数量") + include_shared: bool = Field(True, description="是否包含共享记忆") + + +class MemoryCreateRequest(MemoryBaseRequest): + """创建记忆请求""" + type: Literal["profile", "event"] = Field(..., description="记忆类型") + content: str = Field(..., description="记忆内容") + title: Optional[str] = Field(None, description="标题(event 类型需要)") + + +class MemoryUpdateRequest(MemoryBaseRequest): + """更新记忆请求""" + memory_id: str = Field(..., description="记忆 ID") + title: Optional[str] = Field(None, description="新标题") + content: Optional[str] = Field(None, description="新内容") + + +class MemoryDeleteRequest(MemoryBaseRequest): + """删除记忆请求""" + memory_id: str = Field(..., description="记忆 ID") + + +# ==================== Memory Sharing 请求 ==================== + +class MemorySharingGetRequest(MemoryBaseRequest): + """获取共享配置请求""" + pass + + +class MemorySharingUpdateRequest(MemoryBaseRequest): + """更新共享配置请求""" + share_type: Literal["none", "specific", "all"] = Field(..., description="共享类型") + shared_with: Optional[List[str]] = Field( + None, + description="共享目标 Agent ID 列表(share_type=specific 时需要)" + ) + + +# ==================== 响应 ==================== + +class MemoryResponse(BaseModel): + """记忆响应""" + id: str = Field(..., description="记忆 ID") + agent_id: str = Field(..., description="记忆所属的 Agent ID") + type: Literal["profile", "event"] = Field(..., description="记忆类型") + title: Optional[str] = Field(None, description="标题") + content: str = Field(..., description="记忆内容") + created_at: datetime = Field(..., description="创建时间") + updated_at: datetime = Field(..., description="更新时间") + is_shared: bool = Field(False, description="是否为共享记忆") + shared_from: Optional[str] = Field(None, description="共享来源 Agent ID") + + class Config: + from_attributes = True + + +class MemoryListResponse(BaseModel): + """记忆列表响应""" + memories: List[MemoryResponse] = Field(default_factory=list) + next_cursor: Optional[str] = Field(None, description="下一页游标") + has_more: bool = Field(False, description="是否有更多") + + +class MemorySharingConfig(BaseModel): + """共享配置响应""" + share_type: Literal["none", "specific", "all"] = Field(..., description="共享类型") + shared_with: Optional[List[str]] = Field(None, description="共享目标 Agent ID 列表") + + +class MemoryDeleteResponse(BaseModel): + """删除响应""" + success: bool = Field(True, description="是否成功") diff --git a/main/live-agent-api/services/memory_service.py b/main/live-agent-api/services/memory_service.py new file mode 100644 index 000000000..796c4e5ec --- /dev/null +++ b/main/live-agent-api/services/memory_service.py @@ -0,0 +1,347 @@ +from typing import Optional, List, Set +from sqlalchemy.ext.asyncio import AsyncSession +import httpx +import uuid +from datetime import datetime + +from config import settings +from utils.exceptions import NotFoundException, BadRequestException +from schemas.memory import ( + MemoryResponse, + MemoryListResponse, + MemorySharingConfig, +) +from repositories.memory_sharing import MemorySharingRepository + + +class MemoryService: + """Memory service - 调用下游 MemU API + 本地共享逻辑""" + + # Mock 数据存储(内存中,重启后清空) + _mock_memories: dict = {} + + def __init__(self): + self.base_url = settings.MEMU_BASE_URL if hasattr(settings, 'MEMU_BASE_URL') else "https://api.memu.so" + self.api_key = settings.MEMU_API_KEY if hasattr(settings, 'MEMU_API_KEY') else "" + # 当 MemU 不可用时自动 fallback 到 mock 模式 + self.use_mock = True + + @property + def _headers(self) -> dict: + """构造请求头""" + return { + "Content-Type": "application/json", + "X-API-Key": self.api_key + } + + async def _request( + self, + method: str, + endpoint: str, + payload: Optional[dict] = None, + params: Optional[dict] = None + ) -> dict: + """统一的 HTTP 请求方法(调用 MemU 下游 API)""" + url = f"{self.base_url}{endpoint}" + async with httpx.AsyncClient(timeout=30.0) as client: + response = await client.request( + method=method, + url=url, + json=payload, + params=params, + headers=self._headers + ) + if response.status_code == 404: + raise NotFoundException("Resource not found") + response.raise_for_status() + return response.json() + + # ==================== Mock 数据方法 ==================== + + def _mock_key(self, user_id: str, agent_id: str) -> str: + """生成 mock 存储的 key""" + return f"{user_id}:{agent_id}" + + def _mock_create(self, user_id: str, agent_id: str, memory_type: str, summary: str) -> dict: + """Mock: 创建记忆""" + now = datetime.utcnow().isoformat() + "Z" + memory_id = str(uuid.uuid4()) + item = { + "id": memory_id, + "user_id": user_id, + "agent_id": agent_id, + "memory_type": memory_type, + "summary": summary, + "created_at": now, + "updated_at": now + } + key = self._mock_key(user_id, agent_id) + if key not in self._mock_memories: + self._mock_memories[key] = {} + self._mock_memories[key][memory_id] = item + return item + + def _mock_update(self, user_id: str, agent_id: str, memory_id: str, summary: str) -> dict: + """Mock: 更新记忆""" + key = self._mock_key(user_id, agent_id) + if key in self._mock_memories and memory_id in self._mock_memories[key]: + self._mock_memories[key][memory_id]["summary"] = summary + self._mock_memories[key][memory_id]["updated_at"] = datetime.utcnow().isoformat() + "Z" + return self._mock_memories[key][memory_id] + raise NotFoundException("Memory not found") + + def _mock_delete(self, user_id: str, agent_id: str, memory_id: str) -> dict: + """Mock: 删除记忆""" + key = self._mock_key(user_id, agent_id) + if key in self._mock_memories and memory_id in self._mock_memories[key]: + del self._mock_memories[key][memory_id] + return {"success": True} + raise NotFoundException("Memory not found") + + def _mock_search(self, user_id: str, agent_ids: List[str], query: str) -> dict: + """Mock: 搜索记忆""" + items = [] + for agent_id in agent_ids: + key = self._mock_key(user_id, agent_id) + if key in self._mock_memories: + for item in self._mock_memories[key].values(): + if query.lower() in item.get("summary", "").lower(): + items.append(item) + return {"memory_items": items} + + # ==================== 下游 MemU API 调用(带 Mock Fallback)==================== + + async def _memu_create(self, user_id: str, agent_id: str, memory_type: str, summary: str) -> dict: + """POST /memory-items(失败时 fallback 到 mock)""" + try: + payload = { + "user_id": user_id, + "agent_id": agent_id, + "memory_type": memory_type, + "summary": summary + } + return await self._request("POST", "/memory-items", payload=payload) + except Exception: + if self.use_mock: + return self._mock_create(user_id, agent_id, memory_type, summary) + raise + + async def _memu_update(self, user_id: str, agent_id: str, memory_item_id: str, summary: str) -> dict: + """PUT /memory-items/{memory-item-id}(失败时 fallback 到 mock)""" + try: + payload = { + "user_id": user_id, + "agent_id": agent_id, + "summary": summary + } + return await self._request("PUT", f"/memory-items/{memory_item_id}", payload=payload) + except Exception: + if self.use_mock: + return self._mock_update(user_id, agent_id, memory_item_id, summary) + raise + + async def _memu_delete(self, user_id: str, agent_id: str, memory_item_id: str) -> dict: + """DELETE /memory-items/{memory-item-id}(失败时 fallback 到 mock)""" + try: + params = {"user_id": user_id, "agent_id": agent_id} + return await self._request("DELETE", f"/memory-items/{memory_item_id}", params=params) + except Exception: + if self.use_mock: + 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: str) -> dict: + """POST /memory-items/search(失败时 fallback 到 mock)""" + try: + payload = { + "user_id": user_id, + "agent_ids": agent_ids, + "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 + + # ==================== 对外 API:Memory CRUD ==================== + + async def search_memories( + self, + db: AsyncSession, + user_id: str, + agent_id: str, + query: Optional[str] = None, + memory_type: Optional[str] = None, + cursor: Optional[str] = None, + limit: int = 20, + include_shared: bool = True + ) -> MemoryListResponse: + """搜索记忆 + + 1. 从 DB 查询共享给该 agent 的源 agent 列表 + 2. 合并自己的 agent_id,构建查询列表 + 3. 一次性调用 MemU 批量查询 + """ + if not query: + return MemoryListResponse(memories=[], next_cursor=None, has_more=False) + + # 1. 构建需要查询的 agent 列表(自己 + 共享源) + agent_ids_to_query = [agent_id] # 自己 + shared_agent_ids = set() + + if include_shared: + shared_source_agents = await MemorySharingRepository.get_agents_sharing_to( + db, user_id, agent_id + ) + agent_ids_to_query.extend(shared_source_agents) + shared_agent_ids = set(shared_source_agents) + + # 2. 一次性调用 MemU 批量查询 + try: + data = await self._memu_search(user_id, agent_ids_to_query, query) + except Exception: + return MemoryListResponse(memories=[], next_cursor=None, has_more=False) + + # 3. 转换结果,标记共享来源 + all_memories = self._convert_memu_list_with_sharing(data, agent_id, shared_agent_ids) + + # 4. 筛选类型 + if memory_type: + all_memories = [m for m in all_memories if m.type == memory_type] + + # 5. 分页 + has_more = len(all_memories) > limit + memories = all_memories[:limit] + next_cursor = memories[-1].id if has_more and memories else None + + return MemoryListResponse( + memories=memories, + next_cursor=next_cursor, + has_more=has_more + ) + + async def create_memory( + self, + user_id: str, + agent_id: str, + memory_type: str, + content: str, + title: Optional[str] = None + ) -> MemoryResponse: + """创建记忆""" + summary = f"{title}: {content}" if title else content + data = await self._memu_create(user_id, agent_id, memory_type, summary) + return self._convert_to_memory_response(data, agent_id) + + async def update_memory( + self, + user_id: str, + agent_id: str, + memory_id: str, + title: Optional[str] = None, + content: Optional[str] = None + ) -> MemoryResponse: + """更新记忆""" + if title is None and content is None: + raise BadRequestException("At least one field (title or content) is required") + + summary = f"{title}: {content}" if title and content else (content or title or "") + data = await self._memu_update(user_id, agent_id, memory_id, summary) + return self._convert_to_memory_response(data, agent_id) + + async def delete_memory(self, user_id: str, agent_id: str, memory_id: str) -> bool: + """删除记忆""" + await self._memu_delete(user_id, agent_id, memory_id) + return True + + # ==================== Memory Sharing Config ==================== + + async def get_memory_sharing( + self, + db: AsyncSession, + user_id: str, + agent_id: str + ) -> MemorySharingConfig: + """获取记忆共享配置""" + config = await MemorySharingRepository.get_config(db, user_id, agent_id) + + if not config: + return MemorySharingConfig(share_type="none", shared_with=[]) + + shared_with = None + if config.share_type == "specific": + shared_with = await MemorySharingRepository.get_shared_with(db, config.id) + + return MemorySharingConfig( + share_type=config.share_type, + shared_with=shared_with + ) + + async def update_memory_sharing( + self, + db: AsyncSession, + user_id: str, + agent_id: str, + share_type: str, + shared_with: Optional[List[str]] = None + ) -> MemorySharingConfig: + """更新记忆共享配置""" + if share_type not in ("none", "specific", "all"): + raise BadRequestException("share_type must be one of: none, specific, all") + + if share_type == "specific" and not shared_with: + raise BadRequestException("shared_with is required when share_type is 'specific'") + + # 更新数据库 + await MemorySharingRepository.upsert_config( + db=db, + user_id=user_id, + agent_id=agent_id, + share_type=share_type, + shared_with=shared_with if share_type == "specific" else None + ) + + return MemorySharingConfig( + share_type=share_type, + shared_with=shared_with if share_type == "specific" else None + ) + + # ==================== 工具方法 ==================== + + def _convert_to_memory_response(self, data: dict, agent_id: str, is_shared: bool = False, shared_from: Optional[str] = None) -> MemoryResponse: + """将 MemU 响应转换为对外格式""" + now = datetime.now().isoformat() + return MemoryResponse( + id=data.get("id") or data.get("memory_item_id", ""), + agent_id=agent_id, + type=data.get("memory_type", "profile"), + title=None, + content=data.get("summary", ""), + created_at=datetime.fromisoformat(data.get("created_at", now).replace("Z", "+00:00")), + updated_at=datetime.fromisoformat(data.get("updated_at", now).replace("Z", "+00:00")), + is_shared=is_shared, + shared_from=shared_from + ) + + def _convert_memu_list_with_sharing( + self, + data: dict, + current_agent_id: str, + shared_agent_ids: Set[str] + ) -> List[MemoryResponse]: + """将 MemU 批量查询结果转换为列表,自动标记共享来源""" + items = data.get("memory_items", []) if isinstance(data, dict) else data + if not isinstance(items, list): + items = [] + + result = [] + for item in items: + item_agent_id = item.get("agent_id", current_agent_id) + is_shared = item_agent_id in shared_agent_ids + shared_from = item_agent_id if is_shared else None + result.append(self._convert_to_memory_response(item, item_agent_id, is_shared, shared_from)) + return result + + +memory_service = MemoryService() diff --git a/main/memu.py b/main/memu.py index cd444408a..0206ecf2f 100644 --- a/main/memu.py +++ b/main/memu.py @@ -1,5 +1,4 @@ import os -import time from memu import MemuClient # Initialize MemU client @@ -8,4 +7,4 @@ memu_client = MemuClient( api_key=os.getenv("MEMU_API_KEY") ) -print("✅ MemU client initialized successfully!") \ No newline at end of file +print("✅ MemU client initialized successfully!") diff --git a/main/xiaozhi-server/core/providers/memory/memu/memu.py b/main/xiaozhi-server/core/providers/memory/memu/memu.py index f6bdf3bcc..c836ff74a 100644 --- a/main/xiaozhi-server/core/providers/memory/memu/memu.py +++ b/main/xiaozhi-server/core/providers/memory/memu/memu.py @@ -1,4 +1,8 @@ import traceback +from functools import wraps +from typing import Optional, Dict, Any, List, Callable + +import requests from ..base import MemoryProviderBase, logger from memu import MemuClient @@ -6,33 +10,90 @@ from core.utils.util import check_model_key TAG = __name__ +# 常量定义 +DEFAULT_AGENT_ID = "xiaozhi_agent" +DEFAULT_BASE_URL = "https://api.memu.so" + + +def require_memu(func: Callable) -> Callable: + """装饰器:检查 MemU 服务是否可用""" + @wraps(func) + def wrapper(self, *args, **kwargs): + if not self.use_memu: + return {"success": False, "error": "MemU 服务未启用"} + return func(self, *args, **kwargs) + return wrapper + class MemoryProvider(MemoryProviderBase): - def __init__(self, config, summary_memory=None): + """MemU 记忆服务提供者""" + + def __init__(self, config: dict, summary_memory=None): super().__init__(config) self.api_key = config.get("api_key", "") - self.base_url = config.get("base_url", "https://api.memu.so") + self.base_url = config.get("base_url", DEFAULT_BASE_URL) self.user_name = config.get("user_name", "用户") self.agent_name = config.get("agent_name", "小智") + self.agent_id = config.get("agent_id", DEFAULT_AGENT_ID) + self.use_memu = False + self.client = None model_key_msg = check_model_key("MemU", self.api_key) if model_key_msg: logger.bind(tag=TAG).error(model_key_msg) - self.use_memu = False return - else: - self.use_memu = True try: - self.client = MemuClient( - base_url=self.base_url, - api_key=self.api_key - ) + self.client = MemuClient(base_url=self.base_url, api_key=self.api_key) + self.use_memu = True logger.bind(tag=TAG).info("成功连接到 MemU 服务") except Exception as e: - logger.bind(tag=TAG).error(f"连接到 MemU 服务时发生错误: {str(e)}") - logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") - self.use_memu = False + logger.bind(tag=TAG).error(f"连接 MemU 服务失败: {e}") + logger.bind(tag=TAG).debug(traceback.format_exc()) + + # ==================== 内部工具方法 ==================== + + @property + def _headers(self) -> Dict[str, str]: + """构造请求头""" + return { + "Content-Type": "application/json", + "X-API-Key": self.api_key + } + + def _base_payload(self, **extra) -> Dict[str, Any]: + """构造基础请求体,包含 user_id 和 agent_id""" + payload = {"user_id": self.role_id, "agent_id": self.agent_id} + payload.update(extra) + return payload + + def _request( + self, + method: str, + endpoint: str, + payload: Optional[Dict] = None, + params: Optional[Dict] = None + ) -> Dict[str, Any]: + """统一的 HTTP 请求方法""" + url = f"{self.base_url}{endpoint}" + try: + response = requests.request( + method=method, + url=url, + json=payload, + params=params, + headers=self._headers, + timeout=30 + ) + response.raise_for_status() + return {"success": True, "data": response.json()} + except requests.exceptions.HTTPError as e: + error_msg = f"HTTP {e.response.status_code}: {e.response.text}" + logger.bind(tag=TAG).error(f"请求失败 [{method} {endpoint}]: {error_msg}") + return {"success": False, "error": error_msg} + except Exception as e: + logger.bind(tag=TAG).error(f"请求异常 [{method} {endpoint}]: {e}") + return {"success": False, "error": str(e)} async def save_memory(self, msgs, context=None): if not self.use_memu: @@ -157,3 +218,47 @@ class MemoryProvider(MemoryProviderBase): logger.bind(tag=TAG).error(f"查询记忆失败: {str(e)}") logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") return "" + + # ==================== Memory Item CRUD ==================== + + @require_memu + def create_memory_item(self, memory_type: str, summary: str) -> Dict[str, Any]: + """创建单条记忆记录 + + Args: + memory_type: 记忆类型 + summary: 记忆摘要内容 + """ + payload = self._base_payload(memory_type=memory_type, summary=summary) + return self._request("POST", "/memory-items", payload=payload) + + @require_memu + def update_memory_item(self, memory_item_id: str, summary: str) -> Dict[str, Any]: + """修改单条记忆记录 + + Args: + memory_item_id: 记忆记录 ID + summary: 新的摘要内容 + """ + payload = self._base_payload(summary=summary) + return self._request("PUT", f"/memory-items/{memory_item_id}", payload=payload) + + @require_memu + def delete_memory_item(self, memory_item_id: str) -> Dict[str, Any]: + """删除单条记忆记录 + + Args: + memory_item_id: 记忆记录 ID + """ + 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)