ls、read_file、write_file、edit_file、glob 和 grep 等工具向 agent 暴露 filesystem surface。这些工具通过可插拔 backend 运行。read_file 工具在所有 backends 中原生支持图片文件(.png、.jpg、.jpeg、.gif、.webp),并将它们作为 multimodal content blocks 返回。
Sandboxes 和 LocalShellBackend 也提供 execute 工具。
本页说明如何:
- 选择 backend,
- 将不同路径 route 到不同 backends,
- 实现自己的虚拟文件系统,例如 S3 或 Postgres,
- 设置 filesystem 访问权限,
- 遵循 backend protocol,
快速开始
下面是一些预构建 filesystem backends,可快速用于 deep agent:| 内置 backend | 描述 |
|---|---|
| Default | agent = create_deep_agent(model="google_genai:gemini-3.5-flash") 限定在 thread 范围内。Agent 的默认 filesystem backend 存储在 langgraph state 中。文件会在同一 thread 的多轮对话中持久存在(通过 checkpointer),但不会跨 threads 共享。 |
| Local filesystem persistence | agent = create_deep_agent(model="google_genai:gemini-3.5-flash", backend=FilesystemBackend(root_dir="/Users/nh/Desktop/")) 这会让 deep agent 访问本地机器的 filesystem。你可以指定 agent 可以访问的根目录。注意,任何提供的 root_dir 都必须是绝对路径。通常应包裹在 CompositeBackend 中,以便将内部 agent 数据(offloaded tool results、conversation history)与项目文件分开。 |
| Durable store (LangGraph store) | agent = create_deep_agent(model="google_genai:gemini-3.5-flash", backend=StoreBackend()) 这会让 agent 访问_跨 threads 持久化_的长期存储。它适合存储适用于 agent 多次执行的较长期 memory 或 instructions。 |
| Context Hub | agent = create_deep_agent(model="google_genai:gemini-3.5-flash", backend=ContextHubBackend("my-agent")) 将文件持久存储在 LangSmith Hub repo 中,无需 provision 单独的 LangGraph store。 |
| Sandbox | agent = create_deep_agent(model="google_genai:gemini-3.5-flash", backend=sandbox) 在隔离环境中执行代码。Sandboxes 提供 filesystem tools,以及用于运行 shell 命令的 execute 工具。可以选择 Modal、Daytona、Deno 或 local VFS。 |
| Local shell | agent = create_deep_agent(model="google_genai:gemini-3.5-flash", backend=LocalShellBackend(root_dir=".", env={"PATH": "/usr/bin:/bin"})) 直接在 host 上提供 filesystem 和 shell execution。没有隔离,只能在受控开发环境中使用。请参阅下方安全注意事项。 |
| Composite | 默认限定在 thread 范围内,/memories/ 跨 threads 持久化。Composite backend 最灵活。你可以指定 filesystem 中不同 routes 指向不同 backends。可直接复制的示例见下方 Composite routing。 |
内置 backends
StateBackend
- 通过
StateBackend将文件存储在当前 thread 的 LangGraph agent state 中。 - 通过 checkpoints 在同一 thread 的多个 agent turns 中持久存在。文件不会跨 threads 共享。
- 作为 agent 写入中间结果的 scratch pad。
- 自动驱逐大型 tool outputs,随后 agent 可以分块读回。
FilesystemBackend(local disk)
FilesystemBackend 会在可配置的 root directory 下读取和写入真实文件。
- 在可配置的
root_dir下读取/写入真实文件。 - 可以选择设置
virtual_mode=True,在root_dir下 sandbox 并 normalize paths。 - 使用安全路径解析,尽可能防止不安全 symlink traversal,并可使用 ripgrep 进行快速
grep。
- 本机上的本地项目
- CI sandboxes
- Mounted persistent volumes
LocalShellBackend(local shell)
- 使用
execute工具扩展FilesystemBackend,用于在 host 上运行 shell commands。 - 命令直接在你的机器上通过
subprocess.run(shell=True)运行,没有 sandboxing。 - 支持
timeout(默认 120s)、max_output_bytes(默认 100,000)、env和inherit_env环境变量。 - Shell commands 使用
root_dir作为工作目录,但可以访问系统上的任何路径。
- 本地 coding assistants 和 development tools
- 你信任 agent 时,在开发期间快速迭代
StoreBackend(LangGraph store)
部署到 LangSmith Deployment 时,请省略
store 参数。平台会自动为 agent provision store。StoreBackend将文件存储在运行时提供的 LangGraphBaseStore中,启用跨 thread durable storage。
- 已经使用配置好的 LangGraph store 时,例如
BaseStore背后的 Redis、Postgres 或 cloud implementations。 - 通过 LangSmith Deployment 部署 agent 时,平台会自动为 agent provision store。
Namespace factories
Namespace factory 控制StoreBackend 在何处读写数据。它接收 LangGraph Runtime,并返回作为 store namespace 的字符串 tuple。使用 namespace factories 在 users、tenants 或 assistants 之间隔离数据。
构造 StoreBackend 时,将 namespace factory 传给 namespace 参数:
Runtime 提供:
rt.context,通过 LangGraph context schema 传入的用户提供上下文,例如user_idrt.server_info,在 LangGraph Server 上运行时的 server-specific metadata(assistant ID、graph ID、authenticated user)rt.execution_info,execution identity information(thread ID、run ID、checkpoint ID)
Runtime 参数可在 deepagents>=0.5.2 中使用。更早的 0.5.x releases 会传入 BackendContext,请参阅下方从 BackendContext 迁移。rt.server_info 和 rt.execution_info 需要 deepagents>=0.5.0。(user_id, thread_id) 用于每用户每对话隔离,或追加 "filesystem" 等 suffix,以便在同一 scope 使用多个 store namespaces 时消除歧义。
Namespace 组件只能包含字母数字字符、hyphens、underscores、dots、@、+、colons 和 tildes。通配符(*、?)会被拒绝,以防止 glob injection。
ContextHubBackend
ContextHubBackend 将文件存储在 LangSmith Hub repo 中。使用 owner/name 或 name 格式的 repo identifier 构造它。
使用
ContextHubBackend 前,请设置 LANGSMITH_API_KEY。- 首次使用时惰性 pull Hub repo tree,然后从 in-memory cache 提供 reads。
- 将 writes 和 edits 作为 Hub commits 持久化,并在成功 commit 后更新 cache。
- 使用 optimistic parent-commit writes(
parent_commit):每次 push 都以最新已知 commit hash 为目标。
- 如果 repo 不存在,第一次 pull 会被视为空;第一次成功 write 可以创建 repo。
- 如果另一个 writer 先推进了 repo,你的 stale parent-commit write 可能失败。冲突时请重新 pull 并重试。
upload_files()接受 UTF-8 文本。Non-UTF-8 files 会按路径以invalid_path拒绝。
- 不单独连接 LangGraph
BaseStore,同时使用 LangSmith-native durable filesystem persistence。 - 受益于 filesystem changes 的 Hub commit history 的 workflows。
CompositeBackend(router)
CompositeBackend基于 path prefix 将 file operations route 到不同 backends。- 在 listings 和 search results 中保留原始 path prefixes。
- 想同时为 agent 提供 thread-scoped 和 cross-thread storage 时,
CompositeBackend允许同时提供StateBackend和StoreBackend。 - 想把多个信息来源作为单个 filesystem 的一部分提供给 agent 时。
- 例如,你在一个 Store 的
/memories/下存储长期 memories,同时还有一个自定义 backend 在/docs/下提供文档访问。
- 例如,你在一个 Store 的
指定 backend
- 将 backend 实例传给
create_deep_agent(model=..., backend=...)。Filesystem middleware 会将它用于所有 tooling。 - Backend 必须实现
BackendProtocol,例如StateBackend()、FilesystemBackend(root_dir=".")、StoreBackend()、ContextHubBackend("my-agent")。 - 如果省略,默认值为
StateBackend()。
Route 到不同 backends
将 namespace 的不同部分 route 到不同 backends。常见用法是跨 threads 持久化/memories/*,并让其他所有内容限定在 thread 范围内。
/workspace/plan.md→StateBackend(thread-scoped)/memories/agent.md→/deepagents/myagent下的FilesystemBackendls、glob、grep会聚合结果,并显示原始 path prefixes。
- 更长 prefix 优先,例如 route
"/memories/projects/"可以覆盖"/memories/"。 - 对于 StoreBackend routing,请确保通过
create_deep_agent(model=..., store=...)提供 store,或由平台 provision store。 - Deep Agents 会将内部数据(offloaded tool results、conversation history)写入默认 backend。使用
StateBackend作为默认 backend,可以让这些 artifacts 保持临时状态,并避免写入磁盘或持久 store。完整示例请参阅 FilesystemBackend tip。
使用虚拟文件系统
构建自定义 backend,将远程或数据库 filesystem(例如 S3 或 Postgres)投射到 tools namespace 中。 设计指南:-
Paths 是 absolute(
/x/y.txt)。决定如何将它们映射到 storage keys/rows。 -
高效实现
ls和glob,可用时使用 server-side filtering,否则使用 local filter。 -
对于外部持久化(S3、Postgres 等),在 write/edit results 中返回
files_update=None(Python)或省略filesUpdate(JS)。只有 in-memory state backends 需要返回 files update dict。 -
使用
ls和glob作为 method names。 -
返回带有
error字段的结构化 result types,用于 missing files 或 invalid patterns(不要 raise)。
- Table
files(path text primary key, content text, created_at timestamptz, modified_at timestamptz) - 将 tool operations 映射到 SQL:
ls使用WHERE path LIKE $1 || '%'glob在 SQL 中过滤,或 fetch 后在 Python 中应用 globgrep可以按 extension 或 last modified time fetch candidate rows,然后扫描 lines
Permissions
使用 permissions 以声明方式控制 agent 可以读取或写入哪些 files 和 directories。Permissions 会应用于内置 filesystem tools,并在调用 backend 之前评估。添加 policy hooks
对于 path-based allow/deny rules 之外的自定义验证逻辑,例如 rate limiting、audit logging、content inspection,可以通过继承或包裹 backend 来强制执行企业规则。 在选定 prefixes 下阻止 writes/edits(subclass):从 backend factories 迁移
以前,StateBackend 和 StoreBackend 等 backends 需要接收 runtime object 的 factory function,因为它们需要 runtime context(state、store)才能运行。Backends 现在会通过 LangGraph 的 get_config()、get_store() 和 get_runtime() helpers 在内部解析此上下文,因此你可以直接传入 instances。
发生了什么变化
| Before(deprecated) | After |
|---|---|
backend=lambda rt: StateBackend(rt) | backend=StateBackend() |
backend=lambda rt: StoreBackend(rt) | backend=StoreBackend() |
backend=lambda rt: CompositeBackend(default=StateBackend(rt), ...) | backend=CompositeBackend(default=StateBackend(), ...) |
backend: (config) => new StateBackend(config) | backend: new StateBackend() |
backend: (config) => new StoreBackend(config) | backend: new StoreBackend() |
Deprecated APIs
| Deprecated | Replacement |
|---|---|
向 create_deep_agent 的 backend= 传入 callable | 直接传入 backend instance |
StateBackend(runtime) 上的 runtime constructor argument | StateBackend()(无需参数) |
StoreBackend(runtime) 上的 runtime constructor argument | StoreBackend() 或 StoreBackend(namespace=..., store=...) |
WriteResult 和 EditResult 上的 files_update 字段 | State writes 现在由 backend 内部处理 |
Middleware write/edit tools 中的 Command wrapping | Tools 返回 plain strings,不需要 Command(update=...) |
Factory pattern 运行时仍可工作,并会发出 deprecation warning。请在下一个 major version 前更新代码,改用 direct instances。
Migration example
从 BackendContext 迁移
在 deepagents>=0.5.2(Python)和 deepagents>=1.9.1(TypeScript)中,namespace factories 会直接接收 LangGraph Runtime,而不是 BackendContext wrapper。旧的 BackendContext 形式仍会通过 backwards-compatible .runtime 和 .state accessors 工作,但这些 accessors 会发出 deprecation warning,并将在 deepagents>=0.7 中移除。
发生了什么变化:
- Factory argument 现在是
Runtime,不是BackendContext。 - 移除
.runtimeaccessor,例如ctx.runtime.context.user_id变为rt.server_info.user.identity。 ctx.state没有直接替代项。Namespace info 应是 read-only,并在一次 run 的生命周期内保持稳定,而 state 是可变的且逐步变化。从 state 派生 namespace 可能导致数据进入不一致的 keys。如果你有需要读取 agent state 的用例,请打开 issue。
Protocol reference
Backends 必须实现BackendProtocol。
Required methods:
ls(path: str) -> LsResult- 返回 entries,至少包含
path。可用时包含is_dir、size、modified_at。按path排序以获得确定性输出。
- 返回 entries,至少包含
read(file_path: str, offset: int = 0, limit: int = 2000) -> ReadResult- 成功时返回 file data。缺失文件时,返回
ReadResult(error="Error: File '/x' not found")。
- 成功时返回 file data。缺失文件时,返回
grep(pattern: str, path: Optional[str] = None, glob: Optional[str] = None) -> GrepResult- 返回结构化 matches。出错时返回
GrepResult(error="...")(不要 raise)。
- 返回结构化 matches。出错时返回
glob(pattern: str, path: Optional[str] = None) -> GlobResult- 将 matched files 作为
FileInfoentries 返回(没有匹配时为空列表)。
- 将 matched files 作为
write(file_path: str, content: str) -> WriteResult- Create-only。冲突时返回
WriteResult(error=...)。成功时设置path,并对 state backends 设置files_update={...};external backends 应使用files_update=None。
- Create-only。冲突时返回
edit(file_path: str, old_string: str, new_string: str, replace_all: bool = False) -> EditResult- 除非
replace_all=True,否则强制old_string唯一。如果找不到,返回 error。成功时包含occurrences。
- 除非
LsResult(error, entries),成功时entries是list[FileInfo],失败时为None。ReadResult(error, file_data),成功时file_data是FileDatadict,失败时为None。GrepResult(error, matches),成功时matches是list[GrepMatch],失败时为None。GlobResult(error, matches),成功时matches是list[FileInfo],失败时为None。WriteResult(error, path, files_update)EditResult(error, path, files_update, occurrences)FileInfo字段:path(必需),可选is_dir、size、modified_at。GrepMatch字段:path、line、text。FileData字段:content(str)、encoding("utf-8"或"base64")、created_at、modified_at。
Connect these docs to Claude, VSCode, and more via MCP for real-time answers.

