ls、read_file、write_file、edit_file、glob 和 grep 等工具向 agent 暴露 filesystem surface。这些工具通过可插拔 backend 运行。read_file 工具在所有 backends 中原生支持图片文件(.png、.jpg、.jpeg、.gif、.webp),并将它们作为 multimodal content blocks 返回。
read_file 工具在所有 backends 中原生支持 binary files(图片、PDF、音频、视频),并返回带有 typed content 和 mimeType 的 ReadResult。
Sandboxes 和 LocalShellBackend 也提供 execute 工具。
本页说明如何:
- 选择 backend,
- 将不同路径 route 到不同 backends,
- 实现自己的虚拟文件系统,例如 S3 或 Postgres,
- 设置 filesystem 访问权限,
- 添加 policy hooks,
- 处理 binary 和 multimodal files,
- 遵循 backend protocol,
- 以及将现有 backends 更新到 v2。
快速开始
下面是一些预构建 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_id -
rt.serverInfo,在 LangGraph Server 上运行时的 server-specific metadata(assistant ID、graph ID、authenticated user) -
rt.executionInfo,execution identity information(thread ID、run ID、checkpoint ID)
Runtime 参数可在 deepagents>=1.9.1 中使用。更早的 1.9.x releases 会传入 BackendContext,请参阅下方从 BackendContext 迁移。rt.serverInfo 和 rt.executionInfo 需要 deepagents>=1.9.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 实例传给
createDeepAgent({ backend: ... })。Filesystem middleware 会将它用于所有 tooling。 - Backend 必须实现
AnyBackendProtocol(BackendProtocolV1或BackendProtocolV2),例如new StateBackend()、new FilesystemBackend({ rootDir: "." })、new StoreBackend()。 - 如果省略,默认值为
new StateBackend()。
1.9.0 之前只支持
BackendProtocol,现在称为 BackendProtocolV1。V1 backends 会在运行时通过 adaptBackendProtocol() 自动适配到 V2。继续使用现有 V1 backends 不需要修改代码。要更新到 v2,请参阅将现有 backends 更新到 v2。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。 -
所有 query methods(
ls、read、readRaw、grep、glob)都必须返回带有可选error字段的结构化 Result objects,例如LsResult、ReadResult。 -
在
read()中支持 binary files,返回带有适当mimeType的Uint8Arraycontent。
- Table
files(path text primary key, content text, mime_type text, created_at timestamptz, modified_at timestamptz) - 将 tool operations 映射到 SQL:
ls使用WHERE path LIKE $1 || '%'→ 返回LsResultglob在 SQL 中过滤,或 fetch 后本地应用 glob → 返回GlobResultgrep可以按 extension 或 last modified time fetch candidate rows,然后扫描 lines(跳过mime_type为 binary 的 rows)→ 返回GrepResult
Permissions
使用 permissions 以声明方式控制 agent 可以读取或写入哪些 files 和 directories。Permissions 会应用于内置 filesystem tools,并在调用 backend 之前评估。 完整选项,包括 rule ordering、subagent permissions 和 composite backend interactions,请参阅 permissions guide。添加 policy hooks
对于 path-based allow/deny rules 之外的自定义验证逻辑,例如 rate limiting、audit logging、content inspection,可以通过继承或包裹 backend 来强制执行企业规则。 在选定 prefixes 下阻止 writes/edits(subclass):Multimodal 和 binary files
Multi-modal file support(PDFs、audio、video)需要
deepagents>=1.9.0。read() 遇到 binary file(由文件扩展名推断 MIME type)时,会返回带有 Uint8Array content 和相应 mimeType 的 ReadResult。Text files 返回 string content。
支持的 MIME types
| 类别 | 扩展名 | MIME types |
|---|---|---|
| Images | .png, .jpg/.jpeg, .gif, .webp, .svg, .heic, .heif | image/png, image/jpeg, image/gif, image/webp, image/svg+xml, image/heic, image/heif |
| Audio | .mp3, .wav, .aiff, .aac, .ogg, .flac | audio/mpeg, audio/wav, audio/aiff, audio/aac, audio/ogg, audio/flac |
| Video | .mp4, .webm, .mpeg/.mpg, .mov, .avi, .flv, .wmv, .3gpp | video/mp4, video/webm, video/mpeg, video/quicktime, video/x-msvideo, video/x-flv, video/x-ms-wmv, video/3gpp |
| Documents | .pdf, .ppt, .pptx | application/pdf, application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation |
| Text | .txt, .html, .json, .js, .ts, .py 等 | text/plain, text/html, application/json 等 |
读取 binary files
FileData format
FileData 是用于在 state 和 store backends 中存储文件内容的类型。
fileFormat: "v1" 传给 backend constructor,例如 new StoreBackend({ fileFormat: "v1" })。
从 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 |
|---|---|
BackendFactory type | 直接传入 backend instance |
BackendRuntime interface | Backends 在内部解析 context |
StateBackend(runtime, options?) constructor overload | new StateBackend(options?) |
StoreBackend(stateAndStore, options?) constructor overload | new StoreBackend(options?) |
WriteResult 和 EditResult 上的 filesUpdate 字段 | State writes 现在由 backend 内部处理 |
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 实现BackendProtocolV2。所有 query methods 都返回带有 { error?: string, ...data } 的结构化 Result objects。
Required methods
-
ls(path: string) → LsResult- 列出指定 directory 中的 files 和 directories(non-recursive)。Directories 的 path 末尾带
/,并且is_dir=true。可用时包含is_dir、size、modified_at。
- 列出指定 directory 中的 files 和 directories(non-recursive)。Directories 的 path 末尾带
-
read(filePath: string, offset?: number, limit?: number) → ReadResult- 读取 file content。对于 text files,content 按 line offset/limit 分页(默认 offset 0、limit 500)。对于 binary files,会返回完整 raw
Uint8Arraycontent,并设置mimeType字段。缺失文件时,返回{ error: "File '/x' not found" }。
- 读取 file content。对于 text files,content 按 line offset/limit 分页(默认 offset 0、limit 500)。对于 binary files,会返回完整 raw
-
readRaw(filePath: string) → ReadRawResult- 以 raw
FileData读取 file content。返回包含 timestamps 的完整 file data。
- 以 raw
-
grep(pattern: string, path?: string | null, glob?: string | null) → GrepResult- 在 file contents 中搜索 literal text pattern。Binary files(由 MIME type 判定)会被跳过。失败时返回
{ error: "..." }。
- 在 file contents 中搜索 literal text pattern。Binary files(由 MIME type 判定)会被跳过。失败时返回
-
glob(pattern: string, path?: string) → GlobResult- 将匹配 glob pattern 的 files 作为
FileInfoentries 返回。
- 将匹配 glob pattern 的 files 作为
-
write(filePath: string, content: string) → WriteResult- Create-only semantics。冲突时返回
{ error: "..." }。成功时设置path,并对 state backends 设置filesUpdate={...};external backends 应使用filesUpdate=null。
- Create-only semantics。冲突时返回
-
edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean) → EditResult- 除非
replaceAll=true,否则强制oldString唯一。如果找不到,返回 error。成功时包含occurrences。
- 除非
Optional methods
uploadFiles(files: Array<[string, Uint8Array]>) → FileUploadResponse[],上传多个文件(用于 sandbox backends)。downloadFiles(paths: string[]) → FileDownloadResponse[],下载多个文件(用于 sandbox backends)。
Result types
| Type | Success fields | Error field |
|---|---|---|
ReadResult | content?: string | Uint8Array, mimeType?: string | error |
ReadRawResult | data?: FileData | error |
LsResult | files?: FileInfo[] | error |
GlobResult | files?: FileInfo[] | error |
GrepResult | matches?: GrepMatch[] | error |
WriteResult | path?: string | error |
EditResult | path?: string, occurrences?: number | error |
Supporting types
FileInfo,path(必需),可选is_dir、size、modified_at。GrepMatch,path、line(1-indexed)、text。FileData,包含 timestamps 的 file content。请参阅 FileData format。
Sandbox extension
SandboxBackendProtocolV2 使用以下内容扩展 BackendProtocolV2:
execute(command: string) → ExecuteResponse,在 sandbox 中运行 shell command。readonly id: string,sandbox instance 的唯一标识符。
将现有 backends 更新到 V2
迁移指南
迁移指南
Method renames
| V1 method | V2 method | Return type change |
|---|---|---|
lsInfo(path) | ls(path) | FileInfo[] → LsResult |
read(filePath, offset, limit) | read(filePath, offset, limit) | string → ReadResult |
readRaw(filePath) | readRaw(filePath) | FileData → ReadRawResult |
grepRaw(pattern, path, glob) | grep(pattern, path, glob) | GrepMatch[] | string → GrepResult |
globInfo(pattern, path) | glob(pattern, path) | FileInfo[] → GlobResult |
write(...) | write(...) | Unchanged (WriteResult) |
edit(...) | edit(...) | Unchanged (EditResult) |
Type renames
| V1 type | V2 type |
|---|---|
BackendProtocol | BackendProtocolV2 |
SandboxBackendProtocol | SandboxBackendProtocolV2 |
Adaptation utilities
如果你有需要与 V2-only code 一起使用的现有 V1 backends,请使用 adaptation functions:Framework 会自动适配传给
createDeepAgent() 的 V1 backends。只有在直接调用 protocol methods 时,才需要手动 adaptation。Connect these docs to Claude, VSCode, and more via MCP for real-time answers.

