智能体记忆怎么删除?用 LangGraph 清理用户偏好与会话检查点

区分 LangGraph 用户偏好与会话检查点,分别删除 store 条目和指定 thread 并验证结果。

LangGraph 中的用户偏好和会话历史存放在不同位置:store 保存跨会话条目,checkpointer 保存按 thread_id 划分的图状态。因此“删除这个用户的记忆”先要明确删除范围;删一条偏好不会顺带删除会话检查点,删一条 thread 也不会清空该用户的 store。

用虚构数据建一条可删除的记录

下面的示例只用进程内存储,适合验证接口,不处理真实用户资料。安装当前版 langgraph 后保存为 delete_demo.py。LangGraph Memory 官方文档区分短期 checkpointer 与长期 store,并给出 delete_thread 删除指定 thread 所有检查点的接口。

智能体记忆怎么删除?用 LangGraph 清理用户偏好与会话检查点

from typing import TypedDict
from langgraph.graph import StateGraph, START
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.store.memory import InMemoryStore

class State(TypedDict):
    message: str

def pass_through(state: State) -> State:
    return state

checkpointer = InMemorySaver()
store = InMemoryStore()
builder = StateGraph(State)
builder.add_node("pass_through", pass_through)
builder.add_edge(START, "pass_through")
graph = builder.compile(checkpointer=checkpointer, store=store)

user_namespace = ("users", "demo-user-7", "preferences")
thread_id = "demo-user-7-session-a"
config = {"configurable": {"thread_id": thread_id}}
store.put(user_namespace, "theme", {"value": "dark"})
graph.invoke({"message": "你好"}, config)
assert store.get(user_namespace, "theme") is not None
assert checkpointer.get(config) is not None

store.delete(user_namespace, "theme")
checkpointer.delete_thread(thread_id)
assert store.get(user_namespace, "theme") is None
assert checkpointer.get(config) is None
print("偏好条目与该 thread 检查点均已清理")

InMemoryStore 官方 API 参考列出按命名空间和 key 删除条目的方法。运行后预期打印最后一行,且两个读取断言均为 None。若只调用 store.delete,检查点仍在;若只调用 delete_thread,偏好条目仍在。可先注释其中一行分别验证这两个边界。

接入真实应用时的删除清单

先从已认证的用户身份找到该用户的命名空间与相关 thread ID,列出需保留的法律或业务记录,再由有权限的服务端执行删除。多条偏好需逐个列出 key 删除;多个 thread 也需逐个处理,不能凭一个展示名猜全部会话。删除后以同一用户和另一个用户的测试账号分别读取,确认目标记录消失且其他用户仍可访问自己的资料。数据库备份、导出文件和外部平台日志有各自的保留规则,以上两个 API 调用不保证这些副本同步删除。

本文示例使用 InMemory 实现,进程结束后数据本来也会消失;生产数据库的删除语义、事务和备份保留期应按所用实现核对。本文未触碰读者真实用户记忆,也不把本地断言等同于生产删除证明。

Ai菜鸟网。发布者:AI小管家,转载请注明出处:https://www.alyyhw.com/29990.html

赞 (0)
AI小管家的头像AI小管家
智能体调用成本怎么控制?按 token 预估、记账并设置预算阈值
上一篇 1天前
HubSpot Breeze Assistant 怎么写社交媒体帖文?生成、改写与发布前核对
下一篇 1天前

相关推荐

联系我们

联系我们

1

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信
关注微信
分享本页
返回顶部