AI Agent 分层记忆体系实战:用 Redis 五类结构构建可淘汰、可追溯的长短期记忆

AI Agent 分层记忆体系实战:用 Redis 五类结构构建可淘汰、可追溯的长短期记忆

一句话结论 :记忆系统的难点不是「存下来」,而是在正确的时刻取出正确的少量内容,并让其余内容体面地过期。Redis 的五类结构分别承担「快照、画像、窗口、排序、生命周期」,缺一层都会在规模化后反噬。

版本基线:Redis 8.x(Hash 字段级 TTL 需 7.4+)/ redis-py 6.x / Python 3.12 / LangGraph 1.x(仅 checkpoint 小节依赖)。

前置阅读 :01 · 认知升维


1. 记忆不是一种东西:四层模型与各自的硬约束

认知科学里的记忆分类可以直接映射到工程约束,但不要生搬硬套。工程上真正决定设计的,是四个问题:

  1. 写多还是读多? 工作记忆每轮都写,长期画像偶尔写。
  2. 允不允许丢? 当前任务状态丢了可重试;用户明确说过的偏好丢了是事故。
  3. 按什么取? 按会话 ID、按时间、按重要性、按语义相似度,取法完全不同。
  4. 什么时候淘汰? 按时间、按容量、按重要性、按访问频次。
层 内容 写入频率 读取方式 淘汰策略 Redis 结构
工作记忆 当前会话消息、计划、工具中间结果 每轮 按 session 顺序读 会话结束/超时 List + String
情景记忆 某次任务发生了什么、结论、错误 每任务 按用户+时间/重要性 TTL + 下沉冷存储 Hash + ZSet + Stream
语义记忆 用户偏好、领域事实、稳定结论 低 按用户/标签/向量 版本覆盖、人工删除 Hash + Set + 向量索引
程序记忆 成功的工具调用序列、提示模板 低 按任务类型 版本管理 Hash/JSON

最常见的错误,是把四层都塞进一个 session:{id}:messages 列表。 结果是:上下文越来越长、token 成本线性上涨、旧偏好被最近噪声淹没、跨会话完全失忆。
#mermaid-svg-h55eJZ8efLyOj6t4{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-h55eJZ8efLyOj6t4 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-h55eJZ8efLyOj6t4 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-h55eJZ8efLyOj6t4 .error-icon{fill:#552222;}#mermaid-svg-h55eJZ8efLyOj6t4 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-h55eJZ8efLyOj6t4 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-h55eJZ8efLyOj6t4 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-h55eJZ8efLyOj6t4 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-h55eJZ8efLyOj6t4 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-h55eJZ8efLyOj6t4 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-h55eJZ8efLyOj6t4 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-h55eJZ8efLyOj6t4 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-h55eJZ8efLyOj6t4 .marker.cross{stroke:#333333;}#mermaid-svg-h55eJZ8efLyOj6t4 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-h55eJZ8efLyOj6t4 p{margin:0;}#mermaid-svg-h55eJZ8efLyOj6t4 .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-h55eJZ8efLyOj6t4 .cluster-label text{fill:#333;}#mermaid-svg-h55eJZ8efLyOj6t4 .cluster-label span{color:#333;}#mermaid-svg-h55eJZ8efLyOj6t4 .cluster-label span p{background-color:transparent;}#mermaid-svg-h55eJZ8efLyOj6t4 .label text,#mermaid-svg-h55eJZ8efLyOj6t4 span{fill:#333;color:#333;}#mermaid-svg-h55eJZ8efLyOj6t4 .node rect,#mermaid-svg-h55eJZ8efLyOj6t4 .node circle,#mermaid-svg-h55eJZ8efLyOj6t4 .node ellipse,#mermaid-svg-h55eJZ8efLyOj6t4 .node polygon,#mermaid-svg-h55eJZ8efLyOj6t4 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-h55eJZ8efLyOj6t4 .rough-node .label text,#mermaid-svg-h55eJZ8efLyOj6t4 .node .label text,#mermaid-svg-h55eJZ8efLyOj6t4 .image-shape .label,#mermaid-svg-h55eJZ8efLyOj6t4 .icon-shape .label{text-anchor:middle;}#mermaid-svg-h55eJZ8efLyOj6t4 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-h55eJZ8efLyOj6t4 .rough-node .label,#mermaid-svg-h55eJZ8efLyOj6t4 .node .label,#mermaid-svg-h55eJZ8efLyOj6t4 .image-shape .label,#mermaid-svg-h55eJZ8efLyOj6t4 .icon-shape .label{text-align:center;}#mermaid-svg-h55eJZ8efLyOj6t4 .node.clickable{cursor:pointer;}#mermaid-svg-h55eJZ8efLyOj6t4 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-h55eJZ8efLyOj6t4 .arrowheadPath{fill:#333333;}#mermaid-svg-h55eJZ8efLyOj6t4 .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-h55eJZ8efLyOj6t4 .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-h55eJZ8efLyOj6t4 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-h55eJZ8efLyOj6t4 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-h55eJZ8efLyOj6t4 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-h55eJZ8efLyOj6t4 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-h55eJZ8efLyOj6t4 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-h55eJZ8efLyOj6t4 .cluster text{fill:#333;}#mermaid-svg-h55eJZ8efLyOj6t4 .cluster span{color:#333;}#mermaid-svg-h55eJZ8efLyOj6t4 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-h55eJZ8efLyOj6t4 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-h55eJZ8efLyOj6t4 rect.text{fill:none;stroke-width:0;}#mermaid-svg-h55eJZ8efLyOj6t4 .icon-shape,#mermaid-svg-h55eJZ8efLyOj6t4 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-h55eJZ8efLyOj6t4 .icon-shape p,#mermaid-svg-h55eJZ8efLyOj6t4 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-h55eJZ8efLyOj6t4 .icon-shape rect,#mermaid-svg-h55eJZ8efLyOj6t4 .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-h55eJZ8efLyOj6t4 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-h55eJZ8efLyOj6t4 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-h55eJZ8efLyOj6t4 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 存储层
工作记忆

List + TTL
情景记忆

Hash + ZSet + Stream
语义记忆

Hash + Set + 向量索引
程序记忆

Hash/JSON
记忆管理器
上下文构造

token 预算 + turn 边界
LLM
巩固与淘汰

摘要 / 打分 / 归档 / TTL


2. Key 设计与编码:先决定「一个对象」是什么

2.1 Key 规范

text 复制代码
{tenant}:agent:session:{sid}:meta          Hash    会话元数据(用户、模型、预算)
{tenant}:agent:session:{sid}:turns         List    有界对话轮次(每元素一个完整 turn)
{tenant}:agent:session:{sid}:checkpoint    String  LangGraph/自定义状态快照
{tenant}:agent:profile:{uid}               Hash    结构化画像
{tenant}:agent:mem:{uid}:{mid}             Hash    单条长期记忆
{tenant}:agent:memidx:{uid}                ZSet    记忆重要性索引
{tenant}:agent:memtags:{uid}:{tag}         Set     标签倒排
{tenant}:agent:events                      Stream  记忆写入/巩固事件

Cluster 下,同一租户的 mem、memidx、memtags 需要在同一槽做原子操作时,使用 hash tag:

text 复制代码
{tenant}:agent:mem:{uid}:{mid}
{tenant}:agent:memidx:{uid}
{tenant}:agent:memtags:{uid}:{tag}

注意:hash tag 会让同一租户的所有数据落到同一分片。超级租户会成为热槽 ,需要按 tenant:shard 分桶(第 7 篇展开)。如果更希望按用户分散,可统一改成 {tenant:uid},但所有读写脚本必须使用同一套 tag,不能一半 {tenant}、一半 {tenant:uid}。

2.2 序列化选择

方案 优点 缺点 适用
JSON(orjson) 可读、跨语言、易演进 体积大、浮点精度 调试、小对象、跨语言
MessagePack 紧凑、快 可读性差、需 schema 约束 会话快照、批量记忆
Protobuf 最强约束、最小体积 需编译、演进需 proto 管理 高吞吐内部服务
pickle 方便 禁止:反序列化执行任意代码,版本脆弱 永不用于 Redis

生产建议:对外/调试用 JSON,对内高频用 MessagePack,所有对象带 schema_version 字段。 不要依赖「字段缺失就默认」的隐式兼容,显式迁移。

2.3 大小控制

单个 value 超过 10 KB 时,先问三个问题:

  1. 是否包含可直接外置的大块内容(工具返回的网页、文件、图片 base64)?
  2. 是否可以用「摘要 + 引用」替代原文?
  3. 是否真的需要每次全量读取?

大块内容放对象存储,Redis 只存 uri + sha256 + summary。这不是为了省内存,而是为了避免单次读写放大、fork COW 峰值和网络传输抖动。


3. 工作记忆:有界窗口与 checkpoint

3.1 为什么用 List 存「轮次」而不是「消息」

如果把每条消息作为一个 List 元素,LTRIM 很容易把 assistant(tool_call) 和 tool(result) 截断成不合法序列。正确做法是以 turn 为单位序列化:

python 复制代码
from dataclasses import dataclass, field, asdict
from typing import Any
import orjson


@dataclass
class Turn:
    role: str
    content: str = ""
    tool_calls: list[dict[str, Any]] = field(default_factory=list)
    tool_results: list[dict[str, Any]] = field(default_factory=list)
    created_at: int = 0
    tokens: int = 0
    schema_version: int = 1

    def to_bytes(self) -> bytes:
        return orjson.dumps(asdict(self))

    @classmethod
    def from_bytes(cls, raw: bytes) -> "Turn":
        return cls(**orjson.loads(raw))

写入与截断:

python 复制代码
async def append_turn(r, tenant: str, sid: str, turn: Turn,
                      keep: int = 40) -> None:
    key = f"{{{tenant}}}:agent:session:{sid}:turns"
    async with r.pipeline(transaction=False) as pipe:
        pipe.lpush(key, turn.to_bytes())
        pipe.ltrim(key, 0, keep - 1)      # 保留最新 keep 个 turn
        pipe.expire(key, 6 * 3600)        # 会话级 TTL
        await pipe.execute()

LTRIM 的复杂度是 O(N),N 为被删除的元素数;每次只删 1 个时是 O(1),不要一次保留 10 万再截到 10 个。

3.2 Token 预算:按预算截断,不按条数截断

条数不是预算。同样的 20 条消息,可能 2k token,也可能 40k token。上下文构造应按 token 预算从新到旧装入:

python 复制代码
from typing import Protocol


class TokenCounter(Protocol):
    def count(self, text: str) -> int: ...


async def build_context(
    r,
    tenant: str,
    sid: str,
    counter: TokenCounter,
    system_prompt: str,
    current_user: str,
    context_budget: int,
    output_reserve: int,
) -> tuple[list[dict], list[Turn]]:
    """
    返回 (可直接送给模型的 messages, 被丢弃的 turns)。
    预算 = 模型上下文 - 输出预留 - 系统提示 - 安全余量。
    """
    system_tokens = counter.count(system_prompt)
    current_tokens = counter.count(current_user)
    budget = context_budget - output_reserve - system_tokens - current_tokens
    if budget <= 0:
        raise ValueError("系统提示与当前输入已超出上下文预算")

    raw = await r.lrange(f"{{{tenant}}}:agent:session:{sid}:turns", 0, -1)
    turns = [Turn.from_bytes(x) for x in raw]  # 新 -> 旧
    kept: list[Turn] = []
    used = 0
    dropped: list[Turn] = []

    for turn in turns:
        cost = turn.tokens or counter.count(turn.content)
        if used + cost > budget:
            dropped.extend(turns[len(kept):])
            break
        kept.append(turn)
        used += cost

    kept.reverse()  # 旧 -> 新
    messages = [{"role": "system", "content": system_prompt}]
    for t in kept:
        messages.append({"role": t.role, "content": t.content})
    messages.append({"role": "user", "content": current_user})
    return messages, dropped

三个工程细节:

  1. tokens 在写入时算好并落库 ,不要每次请求重新分词;模型/tokenizer 变更时批量重算并升 schema_version。
  2. 丢弃的 turns 不要直接消失:异步摘要后写入情景记忆,下一轮以「历史摘要」注入。
  3. 工具结果必须成对 :一个 turn 内的 tool_calls 与 tool_results 要么都保留,要么都丢弃;上面按 turn 截断天然满足。

上面的 messages 是简化示意。真实模型协议里,assistant 的 tool_calls 与 tool 角色的结果必须按厂商格式展开;不要把整个 turn 当作纯文本 content 拼接,否则工具调用会失效。存储层按 turn 保留结构,渲染层再按模型协议转换,这是「存储模型」与「传输模型」的分离。

3.3 何时该用 Stream 替代 List

List 适合「只看最近 N 轮」的工作记忆。以下情况改用 Stream:

  • 需要多消费者读取同一会话事件(审计、实时 UI、离线分析);
  • 需要按时间范围回放 或 consumer group 断点续读;
  • 需要保留消息 ID 做幂等。

Stream 的代价是每条消息有 ID 与 radix tree 开销,且 XTRIM 的精确/近似语义需要理解(第 4 篇展开)。工作记忆默认 List,事件审计默认 Stream,不要用 Stream 存纯上下文窗口。

3.4 Checkpoint:跨节点续跑与写放大

LangGraph 的 Redis checkpoint 把每个 super-step 的状态落盘,进程崩溃后可从中断点恢复:

python 复制代码
from langgraph.checkpoint.redis import RedisSaver

REDIS_URL = "redis://127.0.0.1:6379/0"

with RedisSaver.from_conn_string(REDIS_URL) as saver:
    saver.setup()  # 创建索引/结构,首次部署必须执行
    graph = builder.compile(checkpointer=saver)
    result = graph.invoke(
        {"messages": [{"role": "user", "content": "帮我查订单"}]},
        config={"configurable": {"thread_id": "sess-01J..."}},
    )

异步版本为 langgraph.checkpoint.redis.aio.AsyncRedisSaver,初始化后需 await saver.asetup();具体导入路径以安装版本为准。

写放大的来源:每步都存完整状态。一个 20 步、每步 50 KB 的图,会产生 1 MB 的 checkpoint 写入;多副本 + AOF 后实际磁盘/网络放大更明显。控制手段:

  • 状态里只放可恢复所需的最小集,大结果外置;
  • 对超过阈值的字段压缩(zstd)后再存;
  • 为 checkpoint key 设置保留期(会话结束后 N 天),不要永久堆积;
  • 监控 checkpoint key 数量与平均大小,而不是只看 Redis 总内存。

如果你的框架不支持 TTL,写一个按 SCAN + OBJECT IDLETIME 的清理任务;不要用 KEYS。

3.5 三种上下文压缩策略

策略 成本 保留什么 风险
截断 最低 最近 N 轮 丢失早期承诺/约束
摘要 一次 LLM 调用 事实、偏好、承诺、结论 摘要漂移、遗漏
检索 索引 + 召回 与当前 query 相关的片段 召回不准、上下文碎片化

生产上通常组合:

text 复制代码
上下文预算 =
  系统提示(固定,20%)
  + 最近 K 轮原文(40%)
  + 历史摘要(20%)
  + 检索到的长期记忆/知识(20%)

预算比例不是固定的:客服/工单场景要保留更多承诺与状态;知识问答可以给检索更多空间。摘要和检索都要带来源与版本,出问题时可回溯。


4. 长期记忆:Hash 画像 + ZSet 排序 + Set 标签

4.1 结构化画像:Hash 的字段级更新

用户画像天然是「多字段、局部更新、读多写少」。用 String 存整个 JSON 的问题是:改一个字段要 GET → 反序列化 → 修改 → 序列化 → SET,并发下会丢更新,且大对象每次全量传输。

python 复制代码
async def update_profile(r, tenant: str, uid: str,
                         fields: dict[str, str]) -> None:
    key = f"{{{tenant}}}:agent:profile:{uid}"
    async with r.pipeline(transaction=True) as pipe:
        pipe.hset(key, mapping=fields)
        pipe.hset(key, "updated_at", str(now_ms()))
        pipe.expire(key, 180 * 86400)
        await pipe.execute()

但 Hash 不是无条件更快:

  • 小 Hash(默认 ≤128 字段、单值 ≤64 字节)用 listpack 编码,字段更新可能触发整个 listpack 重写,复杂度 O(N);N 很小时可忽略,字段上千时要评估。
  • 大 Hash 转为 hashtable,字段读写 O(1),但内存开销显著上升(dict entry、指针、allocator 碎片)。
  • 需要按字段设置不同 TTL 时,Redis 7.4+ 的 HEXPIRE/HTTL 可用;旧版本只能整 Key 过期或在值里存过期时间由业务判断。

建议:画像字段控制在几十个以内;高频变化的行为计数不要混进画像,放独立的计数 Key 或 ZSet。

4.2 单条记忆的数据模型

一条长期记忆至少需要:内容、类型、来源、创建时间、最后访问、访问次数、显式重要度、版本。

text 复制代码
HSET {acme}:agent:mem:u_42:m_01
  text        "用户偏好简洁回答,不需要寒暄"
  kind        "preference"
  source      "session:sess-01J..."
  created_at  1760000000000
  last_access 1760003600000
  access_count 3
  importance  0.8
  schema_version 1

对应的 ZSet 索引:

text 复制代码
ZADD {acme}:agent:memidx:u_42 <score> m_01

标签倒排:

text 复制代码
SADD {acme}:agent:memtags:u_42:preference m_01
SADD {acme}:agent:memtags:u_42:locale m_01

标签用多个 Set,而不是把标签塞进一个字符串再 SCAN。Set 的交集能在 O(N×M) 内完成,且天然去重。跨租户绝不共用标签 Key。

4.3 重要性打分:一个可解释、可调的公式

不要用「LLM 打个分」作为唯一排序依据------它不可复现、成本高、随模型漂移。用一个可计算的基线,LLM 只做离线校准:

text 复制代码
score = w_r · exp(-Δt / τ) + w_f · min(1, log(1+freq)/log(1+freq_max)) + w_i · importance
  • Δt:距上次访问的毫秒数;
  • τ:半衰期参数,例如 7 天;
  • freq:访问次数;
  • importance:写入时由规则/人工/LLM 给出的 0,1 值;
  • 权重满足 w_r + w_f + w_i = 1,初值可用 0.45 / 0.25 / 0.30。

为什么用指数衰减而不是线性? 线性衰减会让所有旧记忆在某个时间点同时归零,排序退化;指数衰减保持相对差异,且计算稳定。

衰减什么时候重算? 两种策略:

  1. 读时更新 (touch):每次召回后更新 last_access、access_count、score;排序最新,但每次读取都有写放大。
  2. 批量重算:定时任务按用户重算 Top N;读路径只读,写路径便宜,但排序有延迟。

生产上常用混合:读时只更新计数(INCR),排序分由分钟级任务重算。这样既保留频次信号,又避免每读一次写一个 ZSet。
#mermaid-svg-QPrEEao9uJA3vcMA{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-QPrEEao9uJA3vcMA .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-QPrEEao9uJA3vcMA .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-QPrEEao9uJA3vcMA .error-icon{fill:#552222;}#mermaid-svg-QPrEEao9uJA3vcMA .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-QPrEEao9uJA3vcMA .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-QPrEEao9uJA3vcMA .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-QPrEEao9uJA3vcMA .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-QPrEEao9uJA3vcMA .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-QPrEEao9uJA3vcMA .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-QPrEEao9uJA3vcMA .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-QPrEEao9uJA3vcMA .marker{fill:#333333;stroke:#333333;}#mermaid-svg-QPrEEao9uJA3vcMA .marker.cross{stroke:#333333;}#mermaid-svg-QPrEEao9uJA3vcMA svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-QPrEEao9uJA3vcMA p{margin:0;}#mermaid-svg-QPrEEao9uJA3vcMA .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-QPrEEao9uJA3vcMA .cluster-label text{fill:#333;}#mermaid-svg-QPrEEao9uJA3vcMA .cluster-label span{color:#333;}#mermaid-svg-QPrEEao9uJA3vcMA .cluster-label span p{background-color:transparent;}#mermaid-svg-QPrEEao9uJA3vcMA .label text,#mermaid-svg-QPrEEao9uJA3vcMA span{fill:#333;color:#333;}#mermaid-svg-QPrEEao9uJA3vcMA .node rect,#mermaid-svg-QPrEEao9uJA3vcMA .node circle,#mermaid-svg-QPrEEao9uJA3vcMA .node ellipse,#mermaid-svg-QPrEEao9uJA3vcMA .node polygon,#mermaid-svg-QPrEEao9uJA3vcMA .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-QPrEEao9uJA3vcMA .rough-node .label text,#mermaid-svg-QPrEEao9uJA3vcMA .node .label text,#mermaid-svg-QPrEEao9uJA3vcMA .image-shape .label,#mermaid-svg-QPrEEao9uJA3vcMA .icon-shape .label{text-anchor:middle;}#mermaid-svg-QPrEEao9uJA3vcMA .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-QPrEEao9uJA3vcMA .rough-node .label,#mermaid-svg-QPrEEao9uJA3vcMA .node .label,#mermaid-svg-QPrEEao9uJA3vcMA .image-shape .label,#mermaid-svg-QPrEEao9uJA3vcMA .icon-shape .label{text-align:center;}#mermaid-svg-QPrEEao9uJA3vcMA .node.clickable{cursor:pointer;}#mermaid-svg-QPrEEao9uJA3vcMA .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-QPrEEao9uJA3vcMA .arrowheadPath{fill:#333333;}#mermaid-svg-QPrEEao9uJA3vcMA .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-QPrEEao9uJA3vcMA .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-QPrEEao9uJA3vcMA .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-QPrEEao9uJA3vcMA .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-QPrEEao9uJA3vcMA .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-QPrEEao9uJA3vcMA .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-QPrEEao9uJA3vcMA .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-QPrEEao9uJA3vcMA .cluster text{fill:#333;}#mermaid-svg-QPrEEao9uJA3vcMA .cluster span{color:#333;}#mermaid-svg-QPrEEao9uJA3vcMA div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-QPrEEao9uJA3vcMA .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-QPrEEao9uJA3vcMA rect.text{fill:none;stroke-width:0;}#mermaid-svg-QPrEEao9uJA3vcMA .icon-shape,#mermaid-svg-QPrEEao9uJA3vcMA .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-QPrEEao9uJA3vcMA .icon-shape p,#mermaid-svg-QPrEEao9uJA3vcMA .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-QPrEEao9uJA3vcMA .icon-shape rect,#mermaid-svg-QPrEEao9uJA3vcMA .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-QPrEEao9uJA3vcMA .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-QPrEEao9uJA3vcMA .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-QPrEEao9uJA3vcMA :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 新记忆
内容哈希

幂等去重
写 Hash + ZSet 初始分
读时 HINCRBY 计数
分钟级重算

衰减 + 频次 + 重要度
ZSet TopK 召回
语义相似度重排
上下文

4.4 原子更新脚本

读-改-写必须原子,否则并发 touch 会丢计数。用 Lua 把「校验存在 → 更新字段 → 更新 ZSet」放在一次执行里:

lua 复制代码
-- KEYS[1] = {tenant}:agent:mem:{uid}:{mid}
-- KEYS[2] = {tenant}:agent:memidx:{uid}
-- ARGV[1] = mid, ARGV[2] = now_ms, ARGV[3] = tau_ms
-- ARGV[4..6] = w_recency, w_freq, w_importance
local mem_key = KEYS[1]
local idx_key = KEYS[2]
local mid = ARGV[1]
local now_ms = tonumber(ARGV[2])
local tau_ms = tonumber(ARGV[3])
local w_r = tonumber(ARGV[4])
local w_f = tonumber(ARGV[5])
local w_i = tonumber(ARGV[6])

if redis.call('EXISTS', mem_key) == 0 then
  return redis.error_reply('MEM_NOT_FOUND')
end

local last = tonumber(redis.call('HGET', mem_key, 'last_access') or now_ms)
local cnt = tonumber(redis.call('HGET', mem_key, 'access_count') or '0')
local imp = tonumber(redis.call('HGET', mem_key, 'importance') or '0.5')

local dt = math.max(0, now_ms - last)
local recency = math.exp(-dt / tau_ms)
cnt = cnt + 1
local freq = math.log(1 + cnt) / math.log(11)  -- 10 次访问约等于 1.0
if freq > 1 then freq = 1 end

local score = w_r * recency + w_f * freq + w_i * imp
redis.call('HSET', mem_key,
  'last_access', now_ms,
  'access_count', cnt)
redis.call('ZADD', idx_key, score, mid)
return tostring(score)

调用侧:

python 复制代码
async def touch_memory(r, tenant: str, uid: str, mid: str,
                       now_ms: int) -> float:
    # 首次调用时注册,之后走 EVALSHA;NOSCRIPT 由客户端回退 EVAL
    script = getattr(r, "_touch_script", None)
    if script is None:
        script = r.register_script(TOUCH_LUA)
        r._touch_script = script

    tag = f"{{{tenant}}}"
    score = await script(
        keys=[f"{tag}:agent:mem:{uid}:{mid}", f"{tag}:agent:memidx:{uid}"],
        args=[mid, now_ms, 7 * 86400 * 1000, 0.45, 0.25, 0.30],
        client=r,
    )
    return float(score)

Cluster 注意 :两个 Key 必须同槽。上面的 {tenant} 保证了这一点;mem 与 memidx 的 hash tag 都是租户,同槽成立。如果选择按用户分槽,所有 Key 统一改成 {tenant:uid},不能混用。

Lua 的边界 :脚本内不要遍历大集合、不要调用 KEYS、不要做可能超时的远程逻辑。Lua 执行期间整个 Redis 实例阻塞,一个 10 ms 的脚本会让所有客户端多等 10 ms。

4.5 召回:先排序,再取详情

python 复制代码
async def recall(r, tenant: str, uid: str, top_k: int = 8) -> list[dict]:
    tag = f"{{{tenant}}}"
    idx = f"{tag}:agent:memidx:{uid}"
    ids = await r.zrevrange(idx, 0, top_k - 1)
    if not ids:
        return []
    async with r.pipeline(transaction=False) as pipe:
        for mid in ids:
            pipe.hgetall(f"{tag}:agent:mem:{uid}:{mid}")
        rows = await pipe.execute()
    return [row for row in rows if row]

这里是 1 次 ZSet 范围读 + 1 次 Pipeline ,而不是 K 次串行 HGETALL。在 1 ms RTT 的环境里,K=8 时串行是 8 ms,Pipeline 是约 1--2 ms。

如果需要「标签过滤 + 重要性排序」,不要把候选全部拉回客户端再过滤(TopK 可能被过滤光)。两种做法:

  1. 先用 SINTER 得到候选集合,再与 ZSet 做交集排序(ZINTERSTORE 到临时 Key,注意清理与并发);
  2. 维护「标签 + 用户」的独立 ZSet,按标签直接取 TopK。

对 Agent 记忆,标签数量有限、每用户记忆量有限时,方案 2 更简单可控。方案 1 的临时 Key 在高并发下容易成为污染源。

4.6 语义召回:ZSet 不是向量索引

ZSet 只能按标量分数排序,不能算余弦相似度。语义召回需要向量索引(Redis Query Engine,第 6 篇详述);ZSet 在这里的角色是预过滤/重要性加权:

text 复制代码
最终得分 = α · 语义相似度 + β · 重要性分数 + γ · 时效性

先用向量检索取 Top 50,再用 ZSet 里的重要性做重排,而不是反过来。否则高重要性但语义无关的记忆会污染上下文。

4.7 记忆冲突:新偏好覆盖旧偏好,不是简单追加

用户说「以后都用英文回答」,旧记忆里可能还有「用户偏好中文」。两条都召回,模型会困惑。

处理规则:

  1. 确定性覆盖 :同一 subject + predicate 只保留最新值;用 HSET 覆盖或写入新 version,旧版本标记 superseded_by;
  2. 时间有效性 :记忆带 valid_from/valid_to,召回时只取当前有效;
  3. 冲突检测 :写入前按 subject/predicate 查现有记忆;冲突时要么覆盖,要么让用户确认;
  4. 不可覆盖的记忆:安全规则、合规限制、人工置顶的记忆有更高优先级,不能被低信任来源覆盖;
  5. 审计:保留变更历史,能回答「为什么现在这样回答」。

记忆不是日志。日志追加,记忆要收敛;不收敛的记忆会让 Agent 的行为随历史噪声漂移。


5. 生命周期:TTL、老化与冷热分层

5.1 分层 TTL 建议

层 TTL 刷新策略 说明
工作记忆(turns) 6--24 h 每次写入刷新 会话结束可提前删
checkpoint 1--7 d 不刷新 支持断点续跑即可
情景记忆 30--90 d 访问刷新 高价值转语义记忆
语义记忆(画像) 90--365 d 写入刷新 用户可删除
精确缓存 5 min--24 h 不刷新 按数据变更周期
语义缓存 1 h--7 d 命中刷新 需版本化失效

5.2 过期不是删除

Redis 的过期键通过惰性删除 + 定期抽样回收:

  • 访问时发现过期才删(惰性);
  • 后台每 100 ms 抽样过期字典,按 active-expire-effort 调整强度;
  • 从库不会主动过期,等待主库的 DEL 传播;
  • 过期键在被删除前仍占内存。

所以:

  • 大量 Key 同一时刻过期 会造成 CPU 抖动与内存尖峰。给 TTL 加抖动:ttl = base + random(0, base*0.1)。
  • 不要用「过期」做精确的业务时点控制;业务判断仍要看值里的时间戳。
  • 监控 expired_keys、evicted_keys、active_expire_effort,而不是只看内存曲线。

5.3 冷热分层:淘汰前先归档

依赖 maxmemory-policy 淘汰长期记忆,等于把「用户说过的话」交给随机算法。正确顺序是:

  1. 业务归档任务 按 ZSet 低分扫描(ZRANGEBYSCORE 分页),把内容写入 PostgreSQL/S3;
  2. 确认落库成功后,ZREM + DEL(或用 UNLINK);
  3. 设置 maxmemory-policy noeviction 保护状态实例;缓存实例单独部署,允许淘汰。

不要依赖 keyspace notification 做归档:通知是至多一次,消费者离线就丢;而且淘汰事件在高压力下可能延迟。归档必须是主动扫描 + 幂等落库 + 对账。

5.4 记忆巩固:把情景压成语义

每 N 轮或上下文超预算时,触发巩固任务:

python 复制代码
CONSOLIDATE_PROMPT = """\
你是记忆整理器。把下面的对话片段压缩为可长期复用的语义记忆。
要求:
1. 只保留稳定事实、用户偏好、未完成承诺、关键结论;
2. 丢弃寒暄、重复内容、临时推理;
3. 输出 JSON:{"memories":[{"text":"...","kind":"preference|fact|commitment","importance":0.0}]}
"""


async def consolidate(r, llm, uid: str, turns: list[Turn]) -> None:
    raw = "\n".join(f"{t.role}: {t.content}" for t in turns if t.content)
    result = await llm.complete_json(CONSOLIDATE_PROMPT + "\n\n" + raw)
    for item in result.get("memories", []):
        mid = content_hash(uid, item["text"])  # 幂等:同一内容只写一次
        await write_memory(
            r, uid, mid,
            text=item["text"],
            kind=item["kind"],
            importance=float(item.get("importance", 0.5)),
            source="consolidation",
        )

三个必须做对的点:

  1. 幂等 :用内容哈希作为 mid,重复巩固不会产生重复记忆;写入用 HSETNX 或先 EXISTS 校验。
  2. 可追溯 :保留 source(来自哪些 session/turn),便于用户质询「你为什么记得这个」。
  3. 可删除:用户要求删除时,Hash、ZSet、标签 Set、向量索引必须一起删;只删 Hash 会留下「幽灵记忆」被召回。删除流程用 Lua(同槽)或补偿任务 + 对账。

5.5 删除与合规:一条记忆有多个副本

用户行使删除权时,需要覆盖:

text 复制代码
mem Hash
memidx ZSet
memtags Set(所有标签)
向量索引(如启用)
摘要/巩固产物中引用该记忆的条目
缓存中由该记忆生成的答案(如果可追溯)
备份(按保留策略到期删除,不能承诺立即)

工程实现:

  1. 删除请求写入一个持久任务(Stream/DB),不依赖单次同步调用;
  2. 任务逐项删除,记录进度,失败可重试;
  3. 用「删除墓碑」防止并发写入把已删记忆重新加回;
  4. 删除完成后写审计日志;
  5. 对用户可见的 SLA 要诚实:热层立即删,备份按周期过期。

只删 Hash 不删索引,等于没删。 第 3、6 篇的缓存/RAG 索引同理。


6. 并发正确性:三种更新方式怎么选

方式 原子性 适用 风险
单命令(HSET/HINCRBY) 单命令原子 字段独立更新 多字段条件更新不原子
WATCH/MULTI/EXEC 乐观事务 冲突低、逻辑在客户端 冲突需重试;Cluster 同槽
Lua / FUNCTION 服务端原子 读-改-写、条件扣减 阻塞事件循环;无回滚

WATCH 的典型写法:

python 复制代码
async def cas_profile(r, key: str, expected_version: int, fields: dict[str, str],
                      max_retries: int = 3) -> bool:
    for _ in range(max_retries):
        async with r.pipeline(transaction=True) as pipe:
            try:
                await pipe.watch(key)
                current = int(await pipe.hget(key, "version") or 0)
                if current != expected_version:
                    await pipe.unwatch()
                    return False
                pipe.multi()
                pipe.hset(key, mapping={**fields, "version": current + 1})
                await pipe.execute()
                return True
            except redis.WatchError:
                continue
    return False

什么时候用 Lua 而不是 WATCH? 冲突频繁、重试成本高、逻辑固定时用 Lua;逻辑复杂、需要调用外部服务时用 WATCH 或应用层状态机。永远不要在 Lua 里做网络调用。


7. 容量与性能:用公式和工具,不用感觉

7.1 内存估算

text 复制代码
单条记忆 ≈ 文本字节 + Hash 字段开销(约 50--100 B/字段)+ ZSet 成员开销(约 50--100 B)
每用户总内存 ≈ 记忆条数 × 单条 + 标签 Set + 向量索引(若启用)

算例(假设):

  • 100 万用户,人均 50 条记忆,每条 300 B 文本;
  • 文本 15 GB,Hash/ZSet 开销按 2 倍估,约 30 GB;
  • 若再加 100 万条 768 维向量,原始向量 3 GB,HNSW 图结构另计。

这个量级下,单机放不下,必须分片;而分片后跨用户的标签统计、去重、向量检索都会变复杂。先问「是否真的需要为 100 万用户保留 50 条记忆」,再谈数据结构。

7.2 必测指标

bash 复制代码
# 精确内存(SAMPLES 0 表示全量采样,较慢)
redis-cli MEMORY USAGE "{acme}:agent:mem:u_42:m_01" SAMPLES 0

# 大 Key 扫描
redis-cli --bigkeys

# 按内存排序的 Key(Redis 7+)
redis-cli --memkeys

# 慢命令
redis-cli SLOWLOG GET 20
redis-cli LATENCY DOCTOR

应用侧至少记录:

  • recall 的 p50/p95/p99 与返回条数;
  • touch 的 QPS 与 Lua 执行时间;
  • checkpoint 平均大小、写入频率、Key 数量;
  • 每用户记忆条数分布(关注 p99 与最大值,热用户会拖垮单槽)。

7.3 一个可复现实验:Hash vs String 画像更新

python 复制代码
import asyncio, json, time
import redis.asyncio as redis

FIELDS = {f"f{i}": "x" * 40 for i in range(20)}


async def bench(r, rounds: int = 5000) -> None:
    # 两个对象都先写入相同的 20 个字段,保证比较公平
    await r.hset("bench:hash", mapping=FIELDS)
    payload = json.dumps(FIELDS)
    await r.set("bench:str", payload)

    # Hash:单字段更新
    t0 = time.perf_counter()
    for i in range(rounds):
        await r.hset("bench:hash", "f0", str(i))
    t1 = time.perf_counter()

    # String:读-改-写整个 JSON
    t2 = time.perf_counter()
    for i in range(rounds):
        raw = await r.get("bench:str")
        obj = json.loads(raw)
        obj["f0"] = str(i)
        await r.set("bench:str", json.dumps(obj))
    t3 = time.perf_counter()

    print(f"hash update:   {(t1-t0)/rounds*1000:.3f} ms/op")
    print(f"string rmw:    {(t3-t2)/rounds*1000:.3f} ms/op")
    print("hash memory:", await r.memory_usage("bench:hash"))
    print("str memory: ", await r.memory_usage("bench:str"))


asyncio.run(bench(redis.Redis(decode_responses=True)))

这个实验只测「客户端视角的往返 + 序列化」,不测并发与网络抖动。请在自己的网络与 Redis 版本上跑,不要引用别人的数字。


8. 失效模式清单

症状 根因 修复
上下文越来越长、成本翻倍 无边界写入 + 按条数截断 turn 级存储 + token 预算 + 异步摘要
工具调用报「消息序列非法」 LTRIM 截断 tool_call/result 对 以 turn 为单位序列化与截断
画像更新丢字段 String 全量读改写竞态 Hash 字段更新 / CAS / Lua
召回总是旧记忆 只按创建时间排序 重要性衰减 + 访问频次 + 语义召回
用户删除后仍被召回 Hash 删了,ZSet/标签/向量没删 统一删除协议 + 对账任务
内存周期性尖峰 TTL 同时到期 + 大 Key 删除 TTL 抖动 + UNLINK + 拆分大 Key
单槽 CPU 打满 超级用户 hash tag 集中 按 uid 分桶 / 拆分索引 / 限流
checkpoint 拖慢主库 每步全量写 + AOF 外置大结果 + 压缩 + 保留期
从库读到旧记忆 异步复制延迟 关键读走主库 / WAIT(有代价)

9. 生产检查清单

  • 四层记忆各自有 Key 规范、TTL、淘汰策略;
  • 工作记忆以 turn 为单位存储,工具调用与结果不可分离;
  • 上下文按 token 预算构造,写入时已计算 token;
  • 长期画像使用 Hash 字段更新,禁止全量 JSON 读改写;
  • 记忆写入幂等(内容哈希/业务唯一键);
  • 记忆删除是跨结构事务或可对账的补偿流程;
  • ZSet 分数更新用 Lua 或批量任务,不在请求路径做全量重排;
  • TTL 带抖动,监控过期/淘汰速率;
  • checkpoint 大小与数量有上限,大结果外置;
  • 热用户/热槽有分桶与限流方案;
  • 归档先落库再生效删除,不依赖 keyspace notification。

参考资料

  1. Redis 官方文档:Hashes、Lists、Sorted sets、Streams、Key expiration、Memory optimization。
  2. Redis 7.4 release notes:hash field expiration(HEXPIRE 系列)。
  3. LangGraph 官方文档:Persistence / Checkpointers;langgraph-checkpoint-redis。
  4. Redis 源码:t_hash.c、t_zset.c、expire.c、object.c。
  5. Ebbinghaus 遗忘曲线原始实验;用于衰减参数直觉,不构成工程常数。
相关推荐
CyrusYiVPP11 分钟前
新用户第二周还剩几个?pandas做留存率cohort分析,数据分析实战第6期
人工智能·python
谙弆悕博士21 分钟前
多智能体架构详解:网状去中心化架构(Mesh对等P2P)
人工智能·架构·去中心化·p2p·多智能体·智能体·langgraph
IT规划师37 分钟前
Redis 核心机制 | 事务:执行序列的原子性、乐观锁与 8.x 条件写
redis·.net
吴佳浩7 小时前
我把 HAMi 摆回一台双卡机器上跑了一遍:GPU 编排的性能账,到底记在谁头上
人工智能·gpu
Henry-SAP10 小时前
PP的生产调度员(Production Scheduler)的角色与配置
数据库
forest_0911 小时前
《AI 编程 Harness 实战手册》04|审批这道门:点了一百次“允许”,还剩多少作用?
人工智能·算法·prompt·agi
火山引擎开发者社区12 小时前
当 RPA 遇上 Agent:MUA 混合执行 Workflow 深度拆解
人工智能