| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- # app/services/agent/memory.py
- import json
- from typing import List, Dict, Any, Optional
- from app.core.redis import get_redis_client
- from app.core.logger import logger
- SESSION_KEY_PREFIX = "agent:session:"
- DEFAULT_SESSION_TTL = 86400 # 24小时过期
- class AgentMemory:
- """基于 Redis 的 Agent 会话上下文记忆管理器"""
- @classmethod
- def _make_key(cls, session_id: str) -> str:
- return f"{SESSION_KEY_PREFIX}{session_id.strip()}"
- @classmethod
- async def get_history(cls, session_id: Optional[str], max_messages: int = 20) -> List[Dict[str, Any]]:
- """获取指定 session 的历史消息"""
- if not session_id:
- return []
- try:
- redis = await get_redis_client()
- key = cls._make_key(session_id)
- raw = await redis.get(key)
- if not raw:
- return []
- history = json.loads(raw)
- if isinstance(history, list):
- return history[-max_messages:]
- return []
- except Exception as e:
- logger.warning(f"[AgentMemory] Failed to read history for session {session_id}: {e}")
- return []
- @classmethod
- async def append_messages(
- cls,
- session_id: Optional[str],
- new_messages: List[Dict[str, Any]],
- ttl: int = DEFAULT_SESSION_TTL,
- max_stored_messages: int = 40,
- ) -> None:
- """向 session 追加新消息并刷新 TTL"""
- if not session_id or not new_messages:
- return
- try:
- redis = await get_redis_client()
- key = cls._make_key(session_id)
- existing = await cls.get_history(session_id, max_messages=max_stored_messages)
- combined = existing + new_messages
- # 控制保存的历史最大长度,防止 token 溢出
- trimmed = combined[-max_stored_messages:]
- await redis.setex(key, ttl, json.dumps(trimmed, ensure_ascii=False))
- except Exception as e:
- logger.warning(f"[AgentMemory] Failed to append messages for session {session_id}: {e}")
- @classmethod
- async def clear_session(cls, session_id: str) -> bool:
- """清除指定 session 历史"""
- if not session_id:
- return False
- try:
- redis = await get_redis_client()
- key = cls._make_key(session_id)
- await redis.delete(key)
- return True
- except Exception as e:
- logger.warning(f"[AgentMemory] Failed to delete session {session_id}: {e}")
- return False
|