| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- # 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
- def sanitize_messages(cls, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- 清洗消息列表,确保严格符合 OpenAI / DeepSeek API 的结构约束:
- 1. 任何 role=='tool' 的消息前面必须紧跟一个包含该 tool_call_id 的 assistant 消息;
- 2. 任何带有 tool_calls 的 assistant 消息必须紧随其所有对应的 tool 返回消息;
- 3. 剔除孤立的 tool 消息或截断导致的残缺调用块,防止 DeepSeek HTTP 400 报错。
- """
- clean: List[Dict[str, Any]] = []
- i = 0
- n = len(messages)
- while i < n:
- msg = messages[i]
- role = msg.get("role")
- if role == "tool":
- # 孤立的 tool 消息,前一个不是合法 assistant tool_calls,直接丢弃
- if not clean or clean[-1].get("role") != "assistant" or not clean[-1].get("tool_calls"):
- i += 1
- continue
- matching_ids = {tc.get("id") for tc in clean[-1].get("tool_calls", [])}
- if msg.get("tool_call_id") not in matching_ids:
- i += 1
- continue
- clean.append(msg)
- i += 1
- elif role == "assistant" and msg.get("tool_calls"):
- expected_ids = {tc.get("id") for tc in msg.get("tool_calls", []) if tc.get("id")}
- j = i + 1
- tool_msgs = []
- while j < n and messages[j].get("role") == "tool":
- tool_msgs.append(messages[j])
- j += 1
- found_ids = {tm.get("tool_call_id") for tm in tool_msgs}
- if expected_ids and expected_ids.issubset(found_ids):
- clean.append(msg)
- clean.extend(tool_msgs)
- i = j
- else:
- if msg.get("content"):
- clean.append({"role": "assistant", "content": msg["content"]})
- i = j
- else:
- clean.append(msg)
- i += 1
- return clean
- @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):
- sliced = history[-max_messages:]
- return cls.sanitize_messages(sliced)
- 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
|