deep-agents-memory by langchain-ai/langchain-skills
npx skills add https://github.com/langchain-ai/langchain-skills --skill deep-agents-memory短期存储(StateBackend):在单个线程内持久化,线程结束时丢失
长期存储(StoreBackend):跨线程和会话持久化
混合存储(CompositeBackend):将不同路径路由到不同的后端
FilesystemMiddleware 提供了工具:ls、read_file、write_file、edit_file、glob、grep
| 使用场景 | 后端 | 原因 |
|---|---|---|
| 临时工作文件 | StateBackend | 默认,无需设置 |
| 本地开发 CLI |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| FilesystemBackend |
| 直接磁盘访问 |
| 跨会话记忆 | StoreBackend | 跨线程持久化 |
| 混合存储 | CompositeBackend | 混合临时 + 持久化 |
agent = create_deep_agent() # 默认:StateBackend
result = agent.invoke({
"messages": [{"role": "user", "content": "Write notes to /draft.txt"}]
}, config={"configurable": {"thread_id": "thread-1"}})
# /draft.txt 在线程结束时丢失
默认的 StateBackend 在线程内临时存储文件。
import { createDeepAgent } from "deepagents";
const agent = await createDeepAgent(); // 默认:StateBackend
const result = await agent.invoke({
messages: [{ role: "user", content: "Write notes to /draft.txt" }]
}, { configurable: { thread_id: "thread-1" } });
// /draft.txt 在线程结束时丢失
store = InMemoryStore()
composite_backend = lambda rt: CompositeBackend(
default=StateBackend(rt),
routes={"/memories/": StoreBackend(rt)}
)
agent = create_deep_agent(backend=composite_backend, store=store)
# /draft.txt -> 临时存储 (StateBackend)
# /memories/user-prefs.txt -> 持久化存储 (StoreBackend)
配置 CompositeBackend 将路径路由到不同的存储后端。
import { createDeepAgent, CompositeBackend, StateBackend, StoreBackend } from "deepagents";
import { InMemoryStore } from "@langchain/langgraph";
const store = new InMemoryStore();
const agent = await createDeepAgent({
backend: (config) => new CompositeBackend(
new StateBackend(config),
{ "/memories/": new StoreBackend(config) }
),
store
});
// /draft.txt -> 临时存储 (StateBackend)
// /memories/user-prefs.txt -> 持久化存储 (StoreBackend)
config2 = {"configurable": {"thread_id": "thread-2"}}
agent.invoke({"messages": [{"role": "user", "content": "Read /memories/style.txt"}]}, config=config2)
# 线程 2 可以读取线程 1 保存的文件
通过 StoreBackend 路由,/memories/ 中的文件可以跨线程持久化。
// 使用上一个例子中的 CompositeBackend
const config1 = { configurable: { thread_id: "thread-1" } };
await agent.invoke({ messages: [{ role: "user", content: "Save to /memories/style.txt" }] }, config1);
const config2 = { configurable: { thread_id: "thread-2" } };
await agent.invoke({ messages: [{ role: "user", content: "Read /memories/style.txt" }] }, config2);
// 线程 2 可以读取线程 1 保存的文件
agent = create_deep_agent(
backend=FilesystemBackend(root_dir=".", virtual_mode=True), # 限制访问
interrupt_on={"write_file": True, "edit_file": True},
checkpointer=MemorySaver()
)
# Agent 可以读取/写入磁盘上的实际文件
使用 FilesystemBackend 进行本地开发,实现真实的磁盘访问和人机交互。
import { createDeepAgent, FilesystemBackend } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
const agent = await createDeepAgent({
backend: new FilesystemBackend({ rootDir: ".", virtualMode: true }),
interruptOn: { write_file: true, edit_file: true },
checkpointer: new MemorySaver()
});
安全提示:切勿在 Web 服务器中使用 FilesystemBackend - 请使用 StateBackend 或沙箱环境。
@tool
def get_user_preference(key: str, runtime: ToolRuntime) -> str:
"""从长期存储中获取用户偏好设置。"""
store = runtime.store
result = store.get(("user_prefs",), key)
return str(result.value) if result else "Not found"
@tool
def save_user_preference(key: str, value: str, runtime: ToolRuntime) -> str:
"""将用户偏好设置保存到长期存储中。"""
store = runtime.store
store.put(("user_prefs",), key, {"value": value})
return f"Saved {key}={value}"
store = InMemoryStore()
agent = create_agent(
model="gpt-4.1",
tools=[get_user_preference, save_user_preference],
store=store
)
StoreBackend 需要一个 store 实例。
# 错误示例
agent = create_deep_agent(backend=lambda rt: StoreBackend(rt))
# 正确示例
agent = create_deep_agent(backend=lambda rt: StoreBackend(rt), store=InMemoryStore())
// 正确示例
const agent = await createDeepAgent({
backend: (c) => new StoreBackend(c),
store: new InMemoryStore()
});
StateBackend 文件是线程作用域的 - 跨线程访问需使用相同的 thread_id 或使用 StoreBackend。
# 错误示例:thread-2 无法读取 thread-1 的文件
agent.invoke({"messages": [...]}, config={"configurable": {"thread_id": "thread-1"}}) # 写入
agent.invoke({"messages": [...]}, config={"configurable": {"thread_id": "thread-2"}}) # 文件未找到!
每周安装量
3.0K
代码仓库
GitHub 星标
423
首次出现
2026年3月3日
安全审计
安装于
codex2.5K
cursor2.5K
opencode2.5K
github-copilot2.5K
gemini-cli2.5K
kimi-cli2.4K
Short-term (StateBackend) : Persists within a single thread, lost when thread ends Long-term (StoreBackend) : Persists across threads and sessions Hybrid (CompositeBackend) : Route different paths to different backends
FilesystemMiddleware provides tools: ls, read_file, write_file, edit_file, glob, grep
| Use Case | Backend | Why |
|---|---|---|
| Temporary working files | StateBackend | Default, no setup |
| Local development CLI | FilesystemBackend | Direct disk access |
| Cross-session memory | StoreBackend | Persists across threads |
| Hybrid storage | CompositeBackend | Mix ephemeral + persistent |
agent = create_deep_agent() # Default: StateBackend result = agent.invoke({ "messages": [{"role": "user", "content": "Write notes to /draft.txt"}] }, config={"configurable": {"thread_id": "thread-1"}})
</python>
<typescript>
Default StateBackend stores files ephemerally within a thread.
```typescript
import { createDeepAgent } from "deepagents";
const agent = await createDeepAgent(); // Default: StateBackend
const result = await agent.invoke({
messages: [{ role: "user", content: "Write notes to /draft.txt" }]
}, { configurable: { thread_id: "thread-1" } });
// /draft.txt is lost when thread ends
store = InMemoryStore()
composite_backend = lambda rt: CompositeBackend( default=StateBackend(rt), routes={"/memories/": StoreBackend(rt)} )
agent = create_deep_agent(backend=composite_backend, store=store)
</python>
<typescript>
Configure CompositeBackend to route paths to different storage backends.
```typescript
import { createDeepAgent, CompositeBackend, StateBackend, StoreBackend } from "deepagents";
import { InMemoryStore } from "@langchain/langgraph";
const store = new InMemoryStore();
const agent = await createDeepAgent({
backend: (config) => new CompositeBackend(
new StateBackend(config),
{ "/memories/": new StoreBackend(config) }
),
store
});
// /draft.txt -> ephemeral (StateBackend)
// /memories/user-prefs.txt -> persistent (StoreBackend)
config2 = {"configurable": {"thread_id": "thread-2"}} agent.invoke({"messages": [{"role": "user", "content": "Read /memories/style.txt"}]}, config=config2)
</python>
<typescript>
Files in /memories/ persist across threads via StoreBackend routing.
```typescript
// Using CompositeBackend from previous example
const config1 = { configurable: { thread_id: "thread-1" } };
await agent.invoke({ messages: [{ role: "user", content: "Save to /memories/style.txt" }] }, config1);
const config2 = { configurable: { thread_id: "thread-2" } };
await agent.invoke({ messages: [{ role: "user", content: "Read /memories/style.txt" }] }, config2);
// Thread 2 can read file saved by Thread 1
agent = create_deep_agent( backend=FilesystemBackend(root_dir=".", virtual_mode=True), # Restrict access interrupt_on={"write_file": True, "edit_file": True}, checkpointer=MemorySaver() )
</python>
<typescript>
Use FilesystemBackend for local development with real disk access and human-in-the-loop.
```typescript
import { createDeepAgent, FilesystemBackend } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
const agent = await createDeepAgent({
backend: new FilesystemBackend({ rootDir: ".", virtualMode: true }),
interruptOn: { write_file: true, edit_file: true },
checkpointer: new MemorySaver()
});
Security: Never use FilesystemBackend in web servers - use StateBackend or sandbox instead.
@tool def get_user_preference(key: str, runtime: ToolRuntime) -> str: """Get a user preference from long-term storage.""" store = runtime.store result = store.get(("user_prefs",), key) return str(result.value) if result else "Not found"
@tool def save_user_preference(key: str, value: str, runtime: ToolRuntime) -> str: """Save a user preference to long-term storage.""" store = runtime.store store.put(("user_prefs",), key, {"value": value}) return f"Saved {key}={value}"
store = InMemoryStore()
agent = create_agent( model="gpt-4.1", tools=[get_user_preference, save_user_preference], store=store )
</python>
</ex-store-in-custom-tools>
<boundaries>
### What Agents CAN Configure
- Backend type and configuration
- Routing rules for CompositeBackend
- Root directory for FilesystemBackend
- Human-in-the-loop for file operations
### What Agents CANNOT Configure
- Tool names (ls, read_file, write_file, edit_file, glob, grep)
- Access files outside virtual_mode restrictions
- Cross-thread file access without proper backend setup
</boundaries>
<fix-storebackend-requires-store>
<python>
StoreBackend requires a store instance.
```python
# WRONG
agent = create_deep_agent(backend=lambda rt: StoreBackend(rt))
# CORRECT
agent = create_deep_agent(backend=lambda rt: StoreBackend(rt), store=InMemoryStore())
// CORRECT const agent = await createDeepAgent({ backend: (c) => new StoreBackend(c), store: new InMemoryStore() });
</typescript>
</fix-storebackend-requires-store>
<fix-statebackend-files-dont-persist>
<python>
StateBackend files are thread-scoped - use same thread_id or StoreBackend for cross-thread access.
```python
# WRONG: thread-2 can't read file from thread-1
agent.invoke({"messages": [...]}, config={"configurable": {"thread_id": "thread-1"}}) # Write
agent.invoke({"messages": [...]}, config={"configurable": {"thread_id": "thread-2"}}) # File not found!
Weekly Installs
3.0K
Repository
GitHub Stars
423
First Seen
Mar 3, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex2.5K
cursor2.5K
opencode2.5K
github-copilot2.5K
gemini-cli2.5K
kimi-cli2.4K
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装
AI智能体长期记忆系统 - 精英级架构,融合6种方法,永不丢失上下文
1,200 周安装
AI新闻播客制作技能:实时新闻转对话式播客脚本与音频生成
1,200 周安装
Word文档处理器:DOCX创建、编辑、分析与修订痕迹处理全指南 | 自动化办公解决方案
1,200 周安装
React Router 框架模式指南:全栈开发、文件路由、数据加载与渲染策略
1,200 周安装
Nano Banana AI 图像生成工具:使用 Gemini 3 Pro 生成与编辑高分辨率图像
1,200 周安装
SVG Logo Designer - AI 驱动的专业矢量标识设计工具,生成可缩放品牌标识
1,200 周安装