memory.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # app/services/agent/memory.py
  2. import json
  3. from typing import List, Dict, Any, Optional
  4. from app.core.redis import get_redis_client
  5. from app.core.logger import logger
  6. SESSION_KEY_PREFIX = "agent:session:"
  7. DEFAULT_SESSION_TTL = 86400 # 24小时过期
  8. class AgentMemory:
  9. """基于 Redis 的 Agent 会话上下文记忆管理器"""
  10. @classmethod
  11. def _make_key(cls, session_id: str) -> str:
  12. return f"{SESSION_KEY_PREFIX}{session_id.strip()}"
  13. @classmethod
  14. async def get_history(cls, session_id: Optional[str], max_messages: int = 20) -> List[Dict[str, Any]]:
  15. """获取指定 session 的历史消息"""
  16. if not session_id:
  17. return []
  18. try:
  19. redis = await get_redis_client()
  20. key = cls._make_key(session_id)
  21. raw = await redis.get(key)
  22. if not raw:
  23. return []
  24. history = json.loads(raw)
  25. if isinstance(history, list):
  26. return history[-max_messages:]
  27. return []
  28. except Exception as e:
  29. logger.warning(f"[AgentMemory] Failed to read history for session {session_id}: {e}")
  30. return []
  31. @classmethod
  32. async def append_messages(
  33. cls,
  34. session_id: Optional[str],
  35. new_messages: List[Dict[str, Any]],
  36. ttl: int = DEFAULT_SESSION_TTL,
  37. max_stored_messages: int = 40,
  38. ) -> None:
  39. """向 session 追加新消息并刷新 TTL"""
  40. if not session_id or not new_messages:
  41. return
  42. try:
  43. redis = await get_redis_client()
  44. key = cls._make_key(session_id)
  45. existing = await cls.get_history(session_id, max_messages=max_stored_messages)
  46. combined = existing + new_messages
  47. # 控制保存的历史最大长度,防止 token 溢出
  48. trimmed = combined[-max_stored_messages:]
  49. await redis.setex(key, ttl, json.dumps(trimmed, ensure_ascii=False))
  50. except Exception as e:
  51. logger.warning(f"[AgentMemory] Failed to append messages for session {session_id}: {e}")
  52. @classmethod
  53. async def clear_session(cls, session_id: str) -> bool:
  54. """清除指定 session 历史"""
  55. if not session_id:
  56. return False
  57. try:
  58. redis = await get_redis_client()
  59. key = cls._make_key(session_id)
  60. await redis.delete(key)
  61. return True
  62. except Exception as e:
  63. logger.warning(f"[AgentMemory] Failed to delete session {session_id}: {e}")
  64. return False