deep-agents-memory
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese<overview>
Deep Agents use pluggable backends for file operations and memory:
</backend-selection>
<ex-default-state-backend>
<python>
Default StateBackend stores files ephemerally within a thread.
```python
from deepagents import create_deep_agent
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: , , , , ,
</overview>
<backend-selection>
lsread_filewrite_fileedit_fileglobgrep| 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"}})
<overview>
Deep Agents使用可插拔后端来实现文件操作和内存管理:
</backend-selection>
<ex-default-state-backend>
<python>
默认StateBackend将文件临时存储在单线程内。
```python
from deepagents import create_deep_agent
短期存储(StateBackend):在单线程内持久化,线程结束后数据丢失
长期存储(StoreBackend):可跨线程和会话持久化
混合存储(CompositeBackend):将不同路径的请求路由到不同后端
FilesystemMiddleware提供以下工具:、、、、、
</overview>
<backend-selection>
lsread_filewrite_fileedit_fileglobgrep| 用例 | 后端 | 原因 |
|---|---|---|
| 临时工作文件 | StateBackend | 默认配置,无需额外设置 |
| 本地开发CLI | FilesystemBackend | 直接磁盘访问 |
| 跨会话内存 | StoreBackend | 可跨线程持久化 |
| 混合存储 | CompositeBackend | 混合临时+持久化存储 |
agent = create_deep_agent() # Default: StateBackend
result = agent.invoke({
"messages": [{"role": "user", "content": "Write notes to /draft.txt"}]
}, config={"configurable": {"thread_id": "thread-1"}})
/draft.txt is lost when thread ends
/draft.txt is lost when thread ends
</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 endsstore = InMemoryStore()
composite_backend = lambda rt: CompositeBackend(
default=StateBackend(rt),
routes={"/memories/": StoreBackend(rt)}
)
agent = create_deep_agent(backend=composite_backend, store=store)
</python>
<typescript>
默认StateBackend将文件临时存储在单线程内。
```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 endsstore = InMemoryStore()
composite_backend = lambda rt: CompositeBackend(
default=StateBackend(rt),
routes={"/memories/": StoreBackend(rt)}
)
agent = create_deep_agent(backend=composite_backend, store=store)
/draft.txt -> ephemeral (StateBackend)
/draft.txt -> ephemeral (StateBackend)
/memories/user-prefs.txt -> persistent (StoreBackend)
/memories/user-prefs.txt -> persistent (StoreBackend)
</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)</python>
<typescript>
配置CompositeBackend将不同路径请求路由到不同存储后端。
```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)Using CompositeBackend from previous example
Using CompositeBackend from previous example
config1 = {"configurable": {"thread_id": "thread-1"}}
agent.invoke({"messages": [{"role": "user", "content": "Save to /memories/style.txt"}]}, config=config1)
config2 = {"configurable": {"thread_id": "thread-2"}}
agent.invoke({"messages": [{"role": "user", "content": "Read /memories/style.txt"}]}, config=config2)
config1 = {"configurable": {"thread_id": "thread-1"}}
agent.invoke({"messages": [{"role": "user", "content": "Save to /memories/style.txt"}]}, config=config1)
config2 = {"configurable": {"thread_id": "thread-2"}}
agent.invoke({"messages": [{"role": "user", "content": "Read /memories/style.txt"}]}, config=config2)
Thread 2 can read file saved by Thread 1
Thread 2 can read file saved by Thread 1
</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 1agent = create_deep_agent(
backend=FilesystemBackend(root_dir=".", virtual_mode=True), # Restrict access
interrupt_on={"write_file": True, "edit_file": True},
checkpointer=MemorySaver()
)
</python>
<typescript>
/memories/路径下的文件通过StoreBackend路由实现跨线程持久化。
```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 1agent = create_deep_agent(
backend=FilesystemBackend(root_dir=".", virtual_mode=True), # Restrict access
interrupt_on={"write_file": True, "edit_file": True},
checkpointer=MemorySaver()
)
Agent can read/write actual files on disk
Agent can read/write actual files on disk
</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.
</ex-filesystem-backend-local-dev>
<ex-store-in-custom-tools>
<python>
Access the store directly in custom tools for long-term memory operations.
```python
from langchain.tools import tool, ToolRuntime
from langchain.agents import create_agent
from langgraph.store.memory import InMemoryStore
@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></python>
<typescript>
本地开发时使用FilesystemBackend实现真实磁盘访问和人在回路能力。
```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()
});安全提示:切勿在Web服务器中使用FilesystemBackend,请改用StateBackend或沙箱。
</ex-filesystem-backend-local-dev>
<ex-store-in-custom-tools>
<python>
在自定义工具中直接访问store实现长期内存操作。
```python
from langchain.tools import tool, ToolRuntime
from langchain.agents import create_agent
from langgraph.store.memory import InMemoryStore
@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
- 后端类型及配置
- CompositeBackend的路由规则
- FilesystemBackend的根目录
- 文件操作的人在回路配置
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>
- 工具名称(ls、read_file、write_file、edit_file、glob、grep)
- 访问超出virtual_mode限制的文件
- 未完成正确后端配置的情况下跨线程访问文件 </boundaries>
WRONG
WRONG
agent = create_deep_agent(backend=lambda rt: StoreBackend(rt))
agent = create_deep_agent(backend=lambda rt: StoreBackend(rt))
CORRECT
CORRECT
agent = create_deep_agent(backend=lambda rt: StoreBackend(rt), store=InMemoryStore())
</python>
<typescript>
StoreBackend requires a store instance.
```typescript
// WRONG
const agent = await createDeepAgent({ backend: (c) => new StoreBackend(c) });
// CORRECT
const agent = await createDeepAgent({ backend: (c) => new StoreBackend(c), store: new InMemoryStore() });agent = create_deep_agent(backend=lambda rt: StoreBackend(rt), store=InMemoryStore())
</python>
<typescript>
StoreBackend需要传入store实例。
```typescript
// WRONG
const agent = await createDeepAgent({ backend: (c) => new StoreBackend(c) });
// CORRECT
const agent = await createDeepAgent({ backend: (c) => new StoreBackend(c), store: new InMemoryStore() });WRONG: thread-2 can't read file from thread-1
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!
</python>
<typescript>
StateBackend files are thread-scoped - use same thread_id or StoreBackend for cross-thread access.
```typescript
// WRONG: thread-2 can't read file from thread-1
await agent.invoke({ messages: [...] }, { configurable: { thread_id: "thread-1" } }); // Write
await agent.invoke({ messages: [...] }, { configurable: { thread_id: "thread-2" } }); // File not found!agent.invoke({"messages": [...]}, config={"configurable": {"thread_id": "thread-1"}}) # Write
agent.invoke({"messages": [...]}, config={"configurable": {"thread_id": "thread-2"}}) # File not found!
</python>
<typescript>
StateBackend文件是线程作用域的——跨线程访问请使用相同的thread_id或切换到StoreBackend。
```typescript
// WRONG: thread-2 can't read file from thread-1
await agent.invoke({ messages: [...] }, { configurable: { thread_id: "thread-1" } }); // Write
await agent.invoke({ messages: [...] }, { configurable: { thread_id: "thread-2" } }); // File not found!With routes={"/memories/": StoreBackend(rt)}:
With routes={"/memories/": StoreBackend(rt)}:
agent.invoke(...) # /prefs.txt -> ephemeral (no match)
agent.invoke(...) # /memories/prefs.txt -> persistent (matches route)
</python>
<typescript>
Path must match CompositeBackend route prefix for persistence.
```typescript
// With routes: { "/memories/": StoreBackend }:
await agent.invoke(...); // /prefs.txt -> ephemeral (no match)
await agent.invoke(...); // /memories/prefs.txt -> persistent (matches route)agent.invoke(...) # /prefs.txt -> ephemeral (no match)
agent.invoke(...) # /memories/prefs.txt -> persistent (matches route)
</python>
<typescript>
路径必须匹配CompositeBackend路由前缀才能实现持久化。
```typescript
// With routes: { "/memories/": StoreBackend }:
await agent.invoke(...); // /prefs.txt -> ephemeral (no match)
await agent.invoke(...); // /memories/prefs.txt -> persistent (matches route)WRONG # CORRECT
WRONG # CORRECT
store = InMemoryStore() store = PostgresStore(connection_string="postgresql://...")
</python>
<typescript>
Use PostgresStore for production (InMemoryStore lost on restart).
```typescript
// WRONG // CORRECT
const store = new InMemoryStore(); const store = new PostgresStore({ connectionString: "..." });store = InMemoryStore() store = PostgresStore(connection_string="postgresql://...")
</python>
<typescript>
生产环境请使用PostgresStore(InMemoryStore会在服务重启后丢失数据)。
```typescript
// WRONG // CORRECT
const store = new InMemoryStore(); const store = new PostgresStore({ connectionString: "..." });/mem/file.txt -> StoreBackend, /mem/temp/file.txt -> StateBackend (longer match)
/mem/file.txt -> StoreBackend, /mem/temp/file.txt -> StateBackend (longer match)
</python>
</fix-longest-prefix-match></python>
</fix-longest-prefix-match>