跳到主要内容

文档索引

在以下地址获取完整的文档索引:https://docs.langchain.org.cn/llms.txt

在进一步探索之前,请使用此文件发现所有可用页面。

深度智能体通过 lsread_filewrite_fileedit_fileglobgrep 等工具向智能体公开文件系统接口。这些工具通过可插拔的后端进行操作。read_file 工具原生支持所有后端上的图像文件(.png.jpg.jpeg.gif.webp),并将它们作为多模态内容块返回。 沙盒和 LocalShellBackend 也提供 execute 工具。本页解释了如何:

快速入门

以下是一些您可以快速与深度智能体一起使用的预构建文件系统后端
内置后端描述
默认agent = create_deep_agent(model="google_genai:gemini-3.1-pro-preview")
状态瞬时。智能体的默认文件系统后端存储在 langgraph 状态中。请注意,此文件系统仅对单个线程持久化。
本地文件系统持久化agent = create_deep_agent(model="google_genai:gemini-3.1-pro-preview", backend=FilesystemBackend(root_dir="/Users/nh/Desktop/"))
这使得深度智能体能够访问您本地机器的文件系统。您可以指定智能体有权访问的根目录。请注意,任何提供的 root_dir 都必须是绝对路径。
持久存储(LangGraph 存储)agent = create_deep_agent(model="google_genai:gemini-3.1-pro-preview", backend=StoreBackend())
这使智能体能够访问跨线程持久化的长期存储。这非常适合存储长期记忆或适用于智能体多次执行的指令。
沙箱agent = create_deep_agent(model="google_genai:gemini-3.1-pro-preview", backend=sandbox)
在隔离环境中执行代码。沙盒提供文件系统工具以及用于运行 Shell 命令的 execute 工具。可选择 Modal、Daytona、Deno 或本地 VFS。
本地 Shellagent = create_deep_agent(model="google_genai:gemini-3.1-pro-preview", backend=LocalShellBackend(root_dir=".", env={"PATH": "/usr/bin:/bin"}))
文件系统和 Shell 执行直接在主机上。无隔离——仅在受控的开发环境中使用。请参阅下面的 安全注意事项
复合默认瞬时,/memories/ 持久化。复合后端具有最大的灵活性。您可以在文件系统中指定不同的路由指向不同的后端。请参阅下面的复合路由以获取可直接使用的示例。

内置后端

StateBackend(瞬时)

# By default we provide a StateBackend
agent = create_deep_agent(model="google_genai:gemini-3.1-pro-preview")

# Under the hood, it looks like
from deepagents.backends import StateBackend

agent = create_deep_agent(
    model="google_genai:gemini-3.1-pro-preview",
    backend=StateBackend()
)
工作原理
  • 通过 StateBackend 将文件存储在当前线程的 LangGraph 智能体状态中。
  • 通过检查点在同一线程的多个智能体轮次中持久化。
最适合
  • 智能体用于写入中间结果的临时便笺簿。
  • 自动逐出大型工具输出,然后智能体可以逐块读回。
请注意,此后端由主管智能体和子智能体共享,子智能体写入的任何文件即使在该子智能体执行完成后仍将保留在 LangGraph 智能体状态中。这些文件将继续对主管智能体和其他子智能体可用。

FilesystemBackend(本地磁盘)

FilesystemBackend 在可配置的根目录下读取和写入实际文件。
此后端授予智能体直接的文件系统读/写访问权限。请谨慎使用,并且仅在适当的环境中使用。适当的用例:
  • 本地开发 CLI(编码助手、开发工具)
  • CI/CD 流水线(请参阅下面的安全注意事项)
不适当的用例
  • Web 服务器或 HTTP API - 改用 StateBackendStoreBackend沙盒后端
安全风险
  • 智能体可以读取任何可访问的文件,包括秘密信息(API 密钥、凭证、.env 文件)
  • 结合网络工具,秘密信息可能通过 SSRF 攻击泄露
  • 文件修改是永久且不可逆的
推荐的安全措施
  1. 启用 人工介入 (HITL) 中间件 来审查敏感操作。
  2. 从可访问的文件系统路径中排除秘密信息(尤其是在 CI/CD 中)。
  3. 对于需要文件系统交互的生产环境,请使用 沙盒后端
  4. 始终virtual_mode=Trueroot_dir 一起使用,以启用基于路径的访问限制(阻止 ..~ 以及根目录之外的绝对路径)。请注意,即使设置了 root_dir,默认值(virtual_mode=False)也无法提供安全性。
from deepagents.backends import FilesystemBackend

agent = create_deep_agent(
    model="google_genai:gemini-3.1-pro-preview",
    backend=FilesystemBackend(root_dir=".", virtual_mode=True)
)
工作原理
  • 在可配置的 root_dir 下读/写实际文件。
  • 您可以选择设置 virtual_mode=True 以在 root_dir 下沙盒化和规范化路径。
  • 使用安全的路径解析,尽可能防止不安全的符号链接遍历,可以使用 ripgrep 进行快速 grep
最适合
  • 您机器上的本地项目
  • CI 沙盒
  • 挂载的持久卷

LocalShellBackend(本地 Shell)

此后端授予智能体直接的文件系统读/写访问权限以及在主机上无限制的 Shell 执行权限。请务必极其谨慎使用,并且仅在适当的环境中使用。适当的用例:
  • 本地开发 CLI(编码助手、开发工具)
  • 您信任智能体代码的个人开发环境
  • 具有适当秘密管理的 CI/CD 流水线
不适当的用例
  • 生产环境(例如 Web 服务器、API、多租户系统)
  • 处理不受信任的用户输入或执行不受信任的代码
安全风险
  • 智能体可以使用您用户的权限执行任意 Shell 命令
  • 智能体可以读取任何可访问的文件,包括秘密信息(API 密钥、凭证、.env 文件)
  • 秘密信息可能被泄露
  • 文件修改和命令执行是永久且不可逆的
  • 命令直接在您的主机系统上运行
  • 命令可以消耗无限的 CPU、内存、磁盘
推荐的安全措施
  1. 启用 人工介入 (HITL) 中间件 以在执行前审查和批准操作。这是强烈推荐的。
  2. 仅在专用开发环境中运行。切勿在共享或生产系统上使用。
  3. 对于需要 Shell 执行的生产环境,请使用 沙盒后端
注意:当启用了 Shell 访问时,virtual_mode=True 不提供任何安全性,因为命令可以访问系统上的任何路径。
from deepagents.backends import LocalShellBackend

agent = create_deep_agent(
    model="google_genai:gemini-3.1-pro-preview",
    backend=LocalShellBackend(root_dir=".", env={"PATH": "/usr/bin:/bin"})
)
工作原理
  • 使用 execute 工具扩展 FilesystemBackend,用于在主机上运行 Shell 命令。
  • 命令使用 subprocess.run(shell=True) 直接在您的机器上运行,没有沙盒。
  • 支持 timeout(默认 120 秒)、max_output_bytes(默认 100,000)、envinherit_env 用于环境变量。
  • Shell 命令使用 root_dir 作为工作目录,但可以访问系统上的任何路径。
最适合
  • 本地编码助手和开发工具
  • 在您信任智能体时,在开发过程中快速迭代

StoreBackend (LangGraph 存储)

from langgraph.store.memory import InMemoryStore
from deepagents.backends import StoreBackend

agent = create_deep_agent(
    model="google_genai:gemini-3.1-pro-preview",
    backend=StoreBackend(
        namespace=lambda ctx: (ctx.runtime.context.user_id,),
    ),
    store=InMemoryStore()  # Good for local dev; omit for LangSmith Deployment
)
部署到 LangSmith Deployment 时,请省略 store 参数。平台会自动为您的智能体配置存储。
namespace 参数控制数据隔离。对于多用户部署,始终设置一个 命名空间工厂,以按用户或租户隔离数据。
工作原理
  • StoreBackend 将文件存储在运行时提供的 LangGraph BaseStore 中,从而实现跨线程持久存储。
最适合
  • 当您已经运行了一个配置好的 LangGraph 存储(例如,Redis、Postgres 或 BaseStore 后面的云实现)时。
  • 当您通过 LangSmith Deployment 部署您的智能体时(将自动为您的智能体配置一个存储)。

命名空间工厂

命名空间工厂控制 StoreBackend 读取和写入数据的位置。它接收一个 LangGraph Runtime,并返回一个用作存储命名空间的字符串元组。使用命名空间工厂来隔离用户、租户或助手之间的数据。 在构造 StoreBackend 时,将命名空间工厂传递给 namespace 参数:
NamespaceFactory = Callable[[Runtime], tuple[str, ...]]
Runtime 提供
  • rt.context — 通过 LangGraph 的 上下文模式 传递的用户提供的上下文(例如,user_id
  • rt.server_info — 在 LangGraph 服务器上运行时与服务器相关的元数据(智能体 ID、图 ID、已认证用户)
  • rt.execution_info — 执行身份信息(线程 ID、运行 ID、检查点 ID)
Runtime 参数在 deepagents>=0.5.2 中可用。早期的 0.5.x 版本传递的是 BackendContext 而不是 Runtime——请参阅下面的 BackendContext 迁移rt.server_infort.execution_info 需要 deepagents>=0.5.0
常见命名空间模式
from deepagents.backends import StoreBackend

# Per-user: each user gets their own isolated storage
backend = StoreBackend(
    namespace=lambda rt: (rt.server_info.user.identity,),
)

# Per-assistant: all users of the same assistant share storage
backend = StoreBackend(
    namespace=lambda rt: (
        rt.server_info.assistant_id,
    ),
)

# Per-thread: storage scoped to a single conversation
backend = StoreBackend(
    namespace=lambda rt: (
        rt.execution_info.thread_id,
    ),
)
您可以组合多个组件来创建更具体的范围——例如,(user_id, thread_id) 用于每个用户、每个对话的隔离,或者在同一范围使用多个存储命名空间时添加诸如 "filesystem" 的后缀以消除歧义。 命名空间组件必须只包含字母数字字符、连字符、下划线、点、@+、冒号和波浪号。通配符(*?)被拒绝以防止 glob 注入。
namespace 参数在 v0.5.0 中将是必需的。对于新代码,请始终显式设置它。
如果没有提供命名空间工厂,旧版默认会使用 LangGraph 配置元数据中的 assistant_id。这意味着同一 智能体 的所有用户共享相同的存储。对于多用户 生产环境,请务必提供命名空间工厂。

CompositeBackend(路由器)

from deepagents import create_deep_agent
from deepagents.backends import CompositeBackend, StateBackend, StoreBackend
from langgraph.store.memory import InMemoryStore

agent = create_deep_agent(
    model="google_genai:gemini-3.1-pro-preview",
    backend=CompositeBackend(
        default=StateBackend(),
        routes={
            "/memories/": StoreBackend(),
        }
    ),
    store=InMemoryStore()  # Store passed to create_deep_agent, not backend
)
工作原理
  • CompositeBackend 根据路径前缀将文件操作路由到不同的后端。
  • 在列表和搜索结果中保留原始路径前缀。
最适合
  • 当您希望为智能体提供瞬时和跨线程存储时,CompositeBackend 允许您同时提供 StateBackendStoreBackend
  • 当您有多个信息源,并且希望将其作为单个文件系统的一部分提供给智能体时。
    • 例如,您在一个存储中将长期记忆存储在 /memories/ 下,并且您还有一个自定义后端,其文档可在 /docs/ 访问。

指定后端

  • 将后端实例传递给 create_deep_agent(model=..., backend=...)。文件系统中间件将其用于所有工具。
  • 后端必须实现 BackendProtocol(例如,StateBackend()FilesystemBackend(root_dir=".")StoreBackend())。
  • 如果省略,默认值为 StateBackend()

路由到不同后端

将命名空间的一部分路由到不同的后端。通常用于持久化 /memories/* 并使其他所有内容保持瞬时。
from deepagents import create_deep_agent
from deepagents.backends import CompositeBackend, StateBackend, FilesystemBackend

agent = create_deep_agent(
    model="google_genai:gemini-3.1-pro-preview",
    backend=CompositeBackend(
        default=StateBackend(),
        routes={
            "/memories/": FilesystemBackend(root_dir="/deepagents/myagent", virtual_mode=True),
        },
    )
)
行为
  • /workspace/plan.mdStateBackend(瞬时)
  • /memories/agent.md/deepagents/myagent 下的 FilesystemBackend
  • lsglobgrep 聚合结果并显示原始路径前缀。
备注
  • 较长的前缀优先(例如,路由 "/memories/projects/" 可以覆盖 "/memories/")。
  • 对于 StoreBackend 路由,请确保通过 create_deep_agent(model=..., store=...) 提供存储,或由平台进行配置。

使用虚拟文件系统

构建自定义后端,将远程或数据库文件系统(例如 S3 或 Postgres)投影到工具命名空间中。 设计指南:
  • 路径是绝对的(/x/y.txt)。决定如何将它们映射到您的存储键/行。
  • 高效实现 lsglob(如果可用则进行服务器端过滤,否则进行本地过滤)。
  • 对于外部持久化(S3、Postgres 等),在写入/编辑结果中返回 files_update=None (Python) 或省略 filesUpdate (JS) — 只有内存状态后端才需要返回文件更新字典。
  • 使用 lsglob 作为方法名。
  • 返回带有 error 字段的结构化结果类型,用于文件丢失或无效模式(不要抛出异常)。
S3 风格大纲
from deepagents.backends.protocol import (
    BackendProtocol, WriteResult, EditResult, LsResult, ReadResult, GrepResult, GlobResult,
)

class S3Backend(BackendProtocol):
    def __init__(self, bucket: str, prefix: str = ""):
        self.bucket = bucket
        self.prefix = prefix.rstrip("/")

    def _key(self, path: str) -> str:
        return f"{self.prefix}{path}"

    def ls(self, path: str) -> LsResult:
        # List objects under _key(path); build FileInfo entries (path, size, modified_at)
        ...

    def read(self, file_path: str, offset: int = 0, limit: int = 2000) -> ReadResult:
        # Fetch object; return ReadResult(file_data=...) or ReadResult(error=...)
        ...

    def grep(self, pattern: str, path: str | None = None, glob: str | None = None) -> GrepResult:
        # Optionally filter server‑side; else list and scan content
        ...

    def glob(self, pattern: str, path: str = "/") -> GlobResult:
        # Apply glob relative to path across keys
        ...

    def write(self, file_path: str, content: str) -> WriteResult:
        # Enforce create‑only semantics; return WriteResult(path=file_path, files_update=None)
        ...

    def edit(self, file_path: str, old_string: str, new_string: str, replace_all: bool = False) -> EditResult:
        # Read → replace (respect uniqueness vs replace_all) → write → return occurrences
        ...
Postgres 风格大纲
  • Table files(path text primary key, content text, created_at timestamptz, modified_at timestamptz)
  • 将工具操作映射到 SQL
    • ls 使用 WHERE path LIKE $1 || '%'
    • 在 SQL 中进行 glob 过滤或获取后在 Python 中应用 glob
    • grep 可以按扩展名或最后修改时间获取候选行,然后扫描行

权限

使用 权限 以声明方式控制智能体可以读取或写入哪些文件和目录。权限适用于内置文件系统工具,并在调用后端之前进行评估。
from deepagents import create_deep_agent, FilesystemPermission

agent = create_deep_agent(
    model="google_genai:gemini-3.1-pro-preview",
    backend=CompositeBackend(
        default=StateBackend(),
        routes={
            "/memories/": StoreBackend(
                namespace=lambda rt: (rt.server_info.user.identity,),
            ),
            "/policies/": StoreBackend(
                namespace=lambda rt: (rt.context.org_id,),
            ),
        },
    ),
    permissions=[
        FilesystemPermission(
            operations=["write"],
            paths=["/policies/**"],
            mode="deny",
        ),
    ],
)
有关包括规则排序、子智能体权限和复合后端交互在内的完整选项集,请参阅 权限指南

添加策略钩子

对于超出基于路径的允许/拒绝规则(速率限制、审计日志、内容检查)的自定义验证逻辑,请通过子类化或包装后端来强制执行企业规则。 阻止在选定前缀下的写入/编辑(子类):
from deepagents.backends.filesystem import FilesystemBackend
from deepagents.backends.protocol import WriteResult, EditResult

class GuardedBackend(FilesystemBackend):
    def __init__(self, *, deny_prefixes: list[str], **kwargs):
        super().__init__(**kwargs)
        self.deny_prefixes = [p if p.endswith("/") else p + "/" for p in deny_prefixes]

    def write(self, file_path: str, content: str) -> WriteResult:
        if any(file_path.startswith(p) for p in self.deny_prefixes):
            return WriteResult(error=f"Writes are not allowed under {file_path}")
        return super().write(file_path, content)

    def edit(self, file_path: str, old_string: str, new_string: str, replace_all: bool = False) -> EditResult:
        if any(file_path.startswith(p) for p in self.deny_prefixes):
            return EditResult(error=f"Edits are not allowed under {file_path}")
        return super().edit(file_path, old_string, new_string, replace_all)
通用包装器(适用于任何后端)
from deepagents.backends.protocol import (
    BackendProtocol, WriteResult, EditResult, LsResult, ReadResult, GrepResult, GlobResult,
)

class PolicyWrapper(BackendProtocol):
    def __init__(self, inner: BackendProtocol, deny_prefixes: list[str] | None = None):
        self.inner = inner
        self.deny_prefixes = [p if p.endswith("/") else p + "/" for p in (deny_prefixes or [])]

    def _deny(self, path: str) -> bool:
        return any(path.startswith(p) for p in self.deny_prefixes)

    def ls(self, path: str) -> LsResult:
        return self.inner.ls(path)

    def read(self, file_path: str, offset: int = 0, limit: int = 2000) -> ReadResult:
        return self.inner.read(file_path, offset=offset, limit=limit)
    def grep(self, pattern: str, path: str | None = None, glob: str | None = None) -> GrepResult:
        return self.inner.grep(pattern, path, glob)
    def glob(self, pattern: str, path: str = "/") -> GlobResult:
        return self.inner.glob(pattern, path)
    def write(self, file_path: str, content: str) -> WriteResult:
        if self._deny(file_path):
            return WriteResult(error=f"Writes are not allowed under {file_path}")
        return self.inner.write(file_path, content)
    def edit(self, file_path: str, old_string: str, new_string: str, replace_all: bool = False) -> EditResult:
        if self._deny(file_path):
            return EditResult(error=f"Edits are not allowed under {file_path}")
        return self.inner.edit(file_path, old_string, new_string, replace_all)

从后端工厂迁移

deepagents 0.5.0 起,后端工厂模式已弃用。请直接传递预构建的后端实例,而不是工厂函数。
此前,像 StateBackendStoreBackend 这样的后端需要一个接收运行时对象的工厂函数,因为它们需要运行时上下文(状态、存储)才能操作。现在,后端通过 LangGraph 的 get_config()get_store()get_runtime() 辅助函数在内部解析此上下文,因此您可以直接传递实例。

发生了什么变化

之前(已弃用)之后
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()

已弃用的 API

已弃用替代方案
create_deep_agent 中将可调用对象传递给 backend=直接传递后端实例
StateBackend(runtime) 上的 runtime 构造函数参数StateBackend()(无需参数)
StoreBackend(runtime) 上的 runtime 构造函数参数StoreBackend()StoreBackend(namespace=..., store=...)
WriteResultEditResult 上的 files_update 字段状态写入现在由后端内部处理
中间件写入/编辑工具中的 Command 包装工具返回纯字符串;无需 Command(update=...)
工厂模式在运行时仍然有效并会发出弃用警告。请在下一个主要版本之前更新您的代码以使用直接实例。

迁移示例

# Before (deprecated)
from deepagents import create_deep_agent
from deepagents.backends import CompositeBackend, StateBackend, StoreBackend

agent = create_deep_agent(
    model="google_genai:gemini-3.1-pro-preview",
    backend=lambda rt: CompositeBackend(
        default=StateBackend(rt),
        routes={"/memories/": StoreBackend(rt, namespace=lambda rt: (rt.server_info.user.identity,))},
    ),
)

# After
agent = create_deep_agent(
    model="google_genai:gemini-3.1-pro-preview",
    backend=CompositeBackend(
        default=StateBackend(),
        routes={"/memories/": StoreBackend(namespace=lambda rt: (rt.server_info.user.identity,))},
    ),
)

BackendContext 迁移

deepagents>=0.5.2 (Python) 和 deepagents>=1.9.1 (TypeScript) 中,命名空间工厂直接接收 LangGraph Runtime,而不是 BackendContext 包装器。旧的 BackendContext 形式仍然通过向后兼容的 .runtime.state 访问器工作,但这些访问器会发出弃用警告,并将在 deepagents>=0.7 中移除。 变化内容:
  • 工厂参数现在是 Runtime,而不是 BackendContext
  • 删除 .runtime 访问器 — 例如,ctx.runtime.context.user_id 变为 rt.server_info.user.identity
  • 没有直接替代 ctx.state 的方案。命名空间信息应该是只读的,并且在运行生命周期内保持稳定,而状态是可变的,并且会逐步变化——从中派生命名空间可能会导致数据最终存储在不一致的键下。如果您有需要读取智能体状态的用例,请提出问题
# Before (deprecated, removed in v0.7)
StoreBackend(
    namespace=lambda ctx: (ctx.runtime.context.user_id,),
)

# After
StoreBackend(
    namespace=lambda rt: (rt.server_info.user.identity,),
)

协议参考

后端必须实现 BackendProtocol 所需方法:
  • ls(path: str) -> LsResult
    • 返回至少包含 path 的条目。如果可用,请包含 is_dirsizemodified_at。按 path 排序以获得确定性输出。
  • read(file_path: str, offset: int = 0, limit: int = 2000) -> ReadResult
    • 成功时返回文件数据。如果文件丢失,返回 ReadResult(error="Error: File '/x' not found")
  • grep(pattern: str, path: Optional[str] = None, glob: Optional[str] = None) -> GrepResult
    • 返回结构化匹配项。出错时,返回 GrepResult(error="...")(不要抛出异常)。
  • glob(pattern: str, path: str = "/") -> GlobResult
    • 将匹配的文件作为 FileInfo 条目返回(如果没有则为空列表)。
  • write(file_path: str, content: str) -> WriteResult
    • 仅创建。如果发生冲突,返回 WriteResult(error=...)。成功时,设置 path,对于状态后端,设置 files_update={...};外部后端应使用 files_update=None
  • edit(file_path: str, old_string: str, new_string: str, replace_all: bool = False) -> EditResult
    • 除非 replace_all=True,否则强制 old_string 的唯一性。如果未找到,则返回错误。成功时包含 occurrences
支持类型
  • LsResult(error, entries) — 成功时 entrieslist[FileInfo],失败时为 None
  • ReadResult(error, file_data) — 成功时 file_dataFileData 字典,失败时为 None
  • GrepResult(error, matches) — 成功时 matcheslist[GrepMatch],失败时为 None
  • GlobResult(error, matches) — 成功时 matcheslist[FileInfo],失败时为 None
  • WriteResult(error, path, files_update)
  • EditResult(error, path, files_update, occurrences)
  • FileInfo 包含字段:path(必需),可选 is_dirsizemodified_at
  • GrepMatch 包含字段:pathlinetext
  • FileData 包含字段:content (str)、encoding"utf-8""base64")、created_atmodified_at。 ::

© . This site is unofficial and not affiliated with LangChain, Inc.