惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
The Exploit Database - CXSecurity.com
F
Fortinet All Blogs
U
Unit 42
F
Full Disclosure
雷峰网
雷峰网
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
The Cloudflare Blog
Last Week in AI
Last Week in AI
罗磊的独立博客
D
DataBreaches.Net
C
Check Point Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
O
OpenAI News
C
CXSECURITY Database RSS Feed - CXSecurity.com
aimingoo的专栏
aimingoo的专栏
S
Security @ Cisco Blogs
大猫的无限游戏
大猫的无限游戏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
SegmentFault 最新的问题
NISL@THU
NISL@THU
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Hacker News
The Hacker News
Webroot Blog
Webroot Blog
Security Latest
Security Latest
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
N
News | PayPal Newsroom
P
Proofpoint News Feed
B
Blog RSS Feed
MongoDB | Blog
MongoDB | Blog
C
Cybersecurity and Infrastructure Security Agency CISA
N
News and Events Feed by Topic
Google Online Security Blog
Google Online Security Blog
H
Help Net Security
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
I
Intezer
Application and Cybersecurity Blog
Application and Cybersecurity Blog
M
MIT News - Artificial intelligence
Vercel News
Vercel News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
IT之家
IT之家
MyScale Blog
MyScale Blog
腾讯CDC

博客园 - 三叶草╮

DeepAgents 长期记忆相关组件详解 Python 机器学习03 - 常见分类算法 Python 机器学习02 - 常见分类算法 Python uv 包管理 Python机器学习01 - Sklearn Python高级编程笔记 (线程/进程/协程) Python高级编程笔记 Python 基础笔记 Pandas 常用操作 (缺失值处理/排序/字符串处理/Index/Merge/合并) Python Pandas Python playwright 笔记 pipreqs:快速准确生成当前项目的requirements.txt,还有和freeze的对比 WPF 4款 UI 库 C# Selenium [转]在WPF中自定义控件 UserControl [转]WPF的依赖属性是怎么节约内存的 [转]WPF中的导航框架 [转]C#对Excel报表进行操作(读写和基本操作) C# 模拟http请求网页数据 [网页爬虫]
DeepAgents 长期记忆 笔记
三叶草╮ · 2026-03-19 · via 博客园 - 三叶草╮

Code :

import dotenv
from langchain.chat_models import init_chat_model
import httpx
import os
from deepagents import create_deep_agent
from deepagents.backends import StoreBackend
from langgraph.checkpoint.memory import InMemorySaver
from langchain_core.messages import HumanMessage
from langgraph.store.sqlite import SqliteStore

dotenv.load_dotenv("example.env")

llm = init_chat_model(
    model="saas.qwen3-235b-a22b-instruct",
    api_key=os.getenv("OPENAI_API_KEY"),
    model_provider="openai",
    base_url=os.getenv("OPENAI_BASE_URL"),
    temperature=0.7,
    http_client=httpx.Client(verify=False),
    http_async_client=httpx.AsyncClient(verify=False),
)

config1 = {"configurable": {"thread_id": "1"}}
config2 = {"configurable": {"thread_id": "2"}}

MEMORY_FILE = "/memories/AGENTS.md"
NAMESPACE = ("memories",)

with SqliteStore.from_conn_string("checkpoints.db") as store:
    if store.get(NAMESPACE, MEMORY_FILE) is None:
        store.put(NAMESPACE, MEMORY_FILE, {
            "content": ["# Agent Memory", "", "This file stores long-term memories."],
            "created_at": "2025-01-01T00:00:00",
            "modified_at": "2025-01-01T00:00:00"
        })
        print(f"Created initial memory file: {MEMORY_FILE}")

    agent = create_deep_agent(
        model=llm,
        system_prompt="你是一个智能助手,长期记忆请记录在/memories",
        backend=(lambda rt: StoreBackend(rt, namespace=lambda ctx: NAMESPACE)),
        checkpointer=InMemorySaver(),
        store=store,
        memory=[MEMORY_FILE]
    )
    
    print("\n=== 第一次对话: 记住公司主题色 ===")
    for step in agent.stream(
        {"messages": [HumanMessage("记住公司的主题色是#FD5108")]},
        stream_mode="values",
        config=config1
    ):
        latest = step["messages"][-1]
        if hasattr(latest, 'pretty_print'):
            latest.pretty_print()
    
    print("\n=== 第二次对话: 查询记忆 ===")
    for step in agent.stream(
        {"messages": [HumanMessage("你有哪些记忆")]},
        stream_mode="values",
        config=config2
    ):
        latest = step["messages"][-1]
        if hasattr(latest, 'pretty_print'):
            latest.pretty_print()
    
    print("\n=== 验证 Store 内容 ===")
    item = store.get(NAMESPACE, MEMORY_FILE)
    if item:
        print(f"Memory file content:\n{item.value}")

AI 注释:

backend/checkpointer/store/memory 四个组件的职责详解

```
┌─────────────────────────────────────────────────────────────────────────┐
│                           Agent Application                              │
└─────────────────────────────────────────────────────────────────────────┘
                                      │
        ┌─────────────┬───────────────┼───────────────┬─────────────┐
        │             │               │               │             │
        ▼             ▼               ▼               ▼             │
┌─────────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐          │
│   backend   │ │    store  │ │checkpointer│ │   memory  │          │
│  (操作环境)  │ │  (数据库)  │ │  (存档器)  │ │  (记忆加载)│          │
├─────────────┤ ├───────────┤ ├───────────┤ ├───────────┤          │
│ 文件读写     │ │ 键值存储   │ │ 状态快照   │ │ 加载记忆   │          │
│ 命令执行     │ │ 跨会话共享 │ │ 暂停/恢复  │ │ 注入提示   │          │
└──────┬──────┘ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘          │
       │              │             │             │                 │
       │              │             │             │                 │
       ▼              ▼             ▼             ▼                 │
┌─────────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐          │
│ 文件系统    │ │ 结构化数据 │ │ 对话状态   │ │ 记忆文件   │          │
│ 执行环境    │ │ 长期记忆   │ │ 执行进度   │ │ AGENTS.md │          │
└─────────────┘ └───────────┘ └───────────┘ └───────────┘          │
                                                                   │
        ┌──────────────────────────────────────────────────────────┘
        │
        ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                              数据流向                                    │
│                                                                          │
│  memory ──加载──▶ system prompt ──▶ AI 决策 ──▶ backend 写入 ──▶ store  │
│                                          │                               │
│                                          ▼                               │
│                                    checkpointer 保存状态                 │
└─────────────────────────────────────────────────────────────────────────┘
```
## 1. backend - 操作环境
```
backend=(lambda rt: StoreBackend(rt, namespace=lambda ctx: NAMESPACE))
```
职责 :管理 AI 与外部环境的交互

功能 说明

📁 文件操作 read_file , write_file , edit_file , ls , glob , grep

🔧 命令执行 execute (需要实现 SandboxBackendProtocol )

🗂️ 存储位置 决定文件存在哪里(内存、文件系统、数据库)

常见实现 :

- StateBackend - 文件存在 agent 状态中(临时)
- FilesystemBackend - 文件存在本地文件系统
- StoreBackend - 文件存在 LangGraph Store 中(持久化)

PS:StateBackend 和StoreBackend  单词接近,注意区别


## 2. checkpointer - 状态快照
```
checkpointer=InMemorySaver()
```
职责 :保存对话的执行状态

功能 说明 📸 状态快照 定期保存图的执行状态 ⏸️ 暂停/恢复 支持 human-in-the-loop 🔄 故障恢复 从断点继续执行 💬 对话历史 保存消息记录

常见实现 :

- InMemorySaver - 内存中(临时,重启丢失)
- SqliteSaver - SQLite 数据库(持久化)
- PostgresSaver - PostgreSQL(生产环境)


## 3. store - 结构化数据存储
```
store=store  # SqliteStore 实例
```
职责 :提供跨会话的持久化存储

功能 说明 💾 键值存储 put(namespace, key, value) 🔍 命名空间 按命名空间组织数据 🌐 跨会话共享 所有线程/用户共享数据 🧠 长期记忆 存储需要长期保留的信息

常见实现 :

- InMemoryStore - 内存中(临时)
- SqliteStore - SQLite 数据库
- PostgresStore - PostgreSQL(支持向量搜索)


## 4. memory - 记忆加载
```
memory=[MEMORY_FILE]  # ["/memories/AGENTS.md"]
```
职责 :启动时加载记忆文件到系统提示

功能 说明

📖 自动加载 会话开始时读取指定文件

💉 注入提示 将内容添加到 system prompt

📝 指导更新 告诉 AI 何时/如何更新记忆

## 对比总结表
组件 类比 管理的数据 生命周期 典型用途

backend 操作系统 文件内容、执行结果 取决于实现 文件读写、命令执行

checkpointer 游戏存档 对话状态、消息历史 会话级别 暂停恢复、对话历史

store 数据库 业务数据、长期记忆 持久化 跨会话数据共享

memory 配置文件 记忆文件路径 启动时加载 加载项目上下文

## 在你的代码中的工作流程
```
# 第一次对话: "记住公司的主题色是#FD5108"

# 1. memory 加载 /memories/AGENTS.md 到 system prompt
# 2. AI 决定使用 edit_file 工具更新记忆
# 3. backend (StoreBackend) 执行文件编辑
# 4. store (SqliteStore) 持久化保存数据
# 5. checkpointer 保存当前对话状态

# 第二次对话: "你有哪些记忆"
#
# 1. memory 再次加载 /memories/AGENTS.md(已包含主题色)
# 2. AI 从 system prompt 中读取到记忆内容
# 3. AI 回答: "公司主题色为 #FD5108"
```
关键区别 :

- checkpointer 保存的是 对话进度 (thread 级别)
- store 保存的是 业务数据 (全局共享)
- backend 是 操作接口 (怎么读写)
- memory 是 加载机制 (读什么)

sqlite 数据库截图:

image

程序输出:

=== 第一次对话: 记住公司主题色 ===
================================ Human Message =================================

记住公司的主题色是#FD5108
================================ Human Message =================================

记住公司的主题色是#FD5108
================================ Human Message =================================

记住公司的主题色是#FD5108
================================== Ai Message ==================================

公司主题色已记录为 #FD5108。

=== 第二次对话: 查询记忆 ===
================================ Human Message =================================

你有哪些记忆
================================ Human Message =================================

你有哪些记忆
================================ Human Message =================================

你有哪些记忆
================================== Ai Message ==================================

我目前的记忆是:公司主题色为 #FD5108。

=== 验证 Store 内容 ===
Memory file content:
{'content': ['# Agent Memory', '', 'This file stores long-term memories.', '', '- 公司主题色: #FD5108'], 'created_at': '2025-01-01T00:00:00', 'modified_at': '2026-03-18T07:08:33.505249+00:00'}

View Code