Deep Agents 通过 lsread_filewrite_fileedit_fileglobgrep 等工具向 agent 暴露 filesystem surface。这些工具通过可插拔 backend 运行。read_file 工具在所有 backends 中原生支持图片文件(.png.jpg.jpeg.gif.webp),并将它们作为 multimodal content blocks 返回。 Sandboxes 和 LocalShellBackend 也提供 execute 工具。 本页说明如何:
部署到 LangSmith Deployment 时,store 会自动 provision。使用 LangSmith tracing 调试文件路径、权限拒绝和跨 thread storage。按照可观测性快速入门完成设置。建议同时设置 LangSmith Engine,它会监控 traces、检测问题并提出修复建议。

快速开始

下面是一些预构建 filesystem backends,可快速用于 deep agent:
内置 backend描述
Defaultagent = create_deep_agent(model="google_genai:gemini-3.5-flash")
限定在 thread 范围内。Agent 的默认 filesystem backend 存储在 langgraph state 中。文件会在同一 thread 的多轮对话中持久存在(通过 checkpointer),但不会跨 threads 共享。
Local filesystem persistenceagent = 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 Hubagent = create_deep_agent(model="google_genai:gemini-3.5-flash", backend=ContextHubBackend("my-agent"))
将文件持久存储在 LangSmith Hub repo 中,无需 provision 单独的 LangGraph store。
Sandboxagent = create_deep_agent(model="google_genai:gemini-3.5-flash", backend=sandbox)
在隔离环境中执行代码。Sandboxes 提供 filesystem tools,以及用于运行 shell 命令的 execute 工具。可以选择 Modal、Daytona、Deno 或 local VFS。
Local shellagent = 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

from deepagents import create_deep_agent
from deepagents.backends import StateBackend

# By default we provide a StateBackend
agent = create_deep_agent(model="google_genai:gemini-3.5-flash")

# Under the hood, it looks like
agent2 = create_deep_agent(
    model="openai:gpt-5.4",
    backend=StateBackend(),
)
工作方式:
  • 通过 StateBackend 将文件存储在当前 thread 的 LangGraph agent state 中。
  • 通过 checkpoints 在同一 thread 的多个 agent turns 中持久存在。文件不会跨 threads 共享。
设计上应在 graph 内使用。在 graph run 外调用 backend methods(例如 state_backend.upload_files(...))不会生效,直到 graph 执行。
最适合:
  • 作为 agent 写入中间结果的 scratch pad。
  • 自动驱逐大型 tool outputs,随后 agent 可以分块读回。
注意,此 backend 由 supervisor agent 和 subagents 共享,subagent 写入的任何文件都会保留在 LangGraph agent state 中,即使该 subagent 执行完成也是如此。这些文件会继续对 supervisor agent 和其他 subagents 可用。

FilesystemBackend(local disk)

FilesystemBackend 会在可配置的 root directory 下读取和写入真实文件。
此 backend 会授予 agents 直接 filesystem 读写访问权限。 请谨慎使用,并且只在适当环境中使用。适合的用例:
  • 本地开发 CLIs(coding assistants、development tools)
  • CI/CD pipelines(请参阅下方安全注意事项)
不适合的用例:
  • Web servers 或 HTTP APIs,请改用 StateBackendStoreBackendsandbox backend
安全风险:
  • Agents 可以读取任何可访问文件,包括 secrets(API keys、credentials、.env files)
  • 如果与 network tools 结合,secrets 可能通过 SSRF attacks 外泄
  • 文件修改是永久且不可逆的
推荐防护:
  1. 启用 Human-in-the-Loop (HITL) middleware 以审查敏感操作。
  2. 从可访问 filesystem paths 中排除 secrets,尤其是在 CI/CD 中。
  3. 在需要 filesystem 交互的生产环境中使用 sandbox backend
  4. 使用 root_dir 时,始终启用 virtual_mode=True,以启用基于路径的访问限制(阻止 ..~ 和 root 外的 absolute paths)。 注意,默认值(virtual_mode=False)即使设置了 root_dir 也不提供安全性。
from deepagents import create_deep_agent
from deepagents.backends import FilesystemBackend

agent = create_deep_agent(
    model="google_genai:gemini-3.5-flash",
    backend=FilesystemBackend(root_dir=".", virtual_mode=True),
)
工作方式:
  • 在可配置的 root_dir 下读取/写入真实文件。
  • 可以选择设置 virtual_mode=True,在 root_dir 下 sandbox 并 normalize paths。
  • 使用安全路径解析,尽可能防止不安全 symlink traversal,并可使用 ripgrep 进行快速 grep
最适合:
  • 本机上的本地项目
  • CI sandboxes
  • Mounted persistent volumes
大多数用例都应将 FilesystemBackend 包裹在 CompositeBackend 中。 Deep Agents 会自动向 backend 写入内部数据,包括 offloaded large tool results(位于 /large_tool_results/ 下)和 conversation history(位于 /conversation_history/ 下)。单独使用 FilesystemBackend 时,这些内部文件会写入 root_dir 下的真实磁盘,把 agent artifacts 与项目文件混在一起。使用 CompositeBackend 可以将项目目录 route 到 FilesystemBackend,同时让内部路径保留在临时 StateBackend storage 中:
from deepagents import create_deep_agent
from deepagents.backends import CompositeBackend, StateBackend, FilesystemBackend

agent = create_deep_agent(
    backend=CompositeBackend(
        default=StateBackend(),
        routes={
            "/workspace/": FilesystemBackend(root_dir="/path/to/project", virtual_mode=True),
        },
    )
)
这样,agent 在 /workspace/ 下的读写会进入真实磁盘,而 offloaded tool results 和其他内部数据会留在临时 state 中。更多 routing 模式请参阅Route to different backends

LocalShellBackend(local shell)

此 backend 会授予 agents 直接 filesystem 读写访问权限,并且在 host 上执行不受限制的 shell commands。 请极其谨慎使用,并且只在适当环境中使用。适合的用例:
  • 本地开发 CLIs(coding assistants、development tools)
  • 你信任 agent 代码的个人开发环境
  • 具有正确 secret management 的 CI/CD pipelines
不适合的用例:
  • 生产环境,例如 web servers、APIs、multi-tenant systems
  • 处理不受信任的用户输入或执行不受信任代码
安全风险:
  • Agents 可以用你的用户权限执行任意 shell commands
  • Agents 可以读取任何可访问文件,包括 secrets(API keys、credentials、.env files)
  • Secrets 可能被暴露
  • 文件修改和命令执行是永久且不可逆的
  • 命令直接在 host system 上运行
  • 命令可能消耗无限 CPU、memory 和 disk
推荐防护:
  1. 启用 Human-in-the-Loop (HITL) middleware,在执行前审查并批准操作。强烈推荐这样做。
  2. 只在专用开发环境中运行。不要在共享或生产系统上使用。
  3. 对于需要 shell execution 的生产环境,请使用 sandbox backend
注意: 启用 shell access 时,virtual_mode=True 不提供安全性,因为命令可以访问系统上的任何路径。
from deepagents import create_deep_agent
from deepagents.backends import LocalShellBackend

agent = create_deep_agent(
    model="google_genai:gemini-3.5-flash",
    backend=LocalShellBackend(root_dir=".", virtual_mode=True, env={"PATH": "/usr/bin:/bin"}),
)
工作方式:
  • 使用 execute 工具扩展 FilesystemBackend,用于在 host 上运行 shell commands。
  • 命令直接在你的机器上通过 subprocess.run(shell=True) 运行,没有 sandboxing。
  • 支持 timeout(默认 120s)、max_output_bytes(默认 100,000)、envinherit_env 环境变量。
  • Shell commands 使用 root_dir 作为工作目录,但可以访问系统上的任何路径。
最适合:
  • 本地 coding assistants 和 development tools
  • 你信任 agent 时,在开发期间快速迭代

StoreBackend(LangGraph store)

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

agent = create_deep_agent(
    model="google_genai:gemini-3.5-flash",
    backend=StoreBackend(
        namespace=lambda rt: (rt.server_info.user.identity,),
    ),
    store=InMemoryStore(),  # Good for local dev; omit for LangSmith Deployment
)
部署到 LangSmith Deployment 时,请省略 store 参数。平台会自动为 agent provision store。
namespace 参数控制数据隔离。对于多用户部署,请始终设置 namespace factory,按用户或 tenant 隔离数据。
工作方式:
  • StoreBackend 将文件存储在运行时提供的 LangGraph BaseStore 中,启用跨 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 参数:
NamespaceFactory = Callable[[Runtime], tuple[str, ...]]
Runtime 提供:
  • rt.context,通过 LangGraph context schema 传入的用户提供上下文,例如 user_id
  • rt.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_infort.execution_info 需要 deepagents>=0.5.0
常见 namespace 模式:
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,
    ),
)
你可以组合多个组件来创建更具体的 scopes,例如 (user_id, thread_id) 用于每用户每对话隔离,或追加 "filesystem" 等 suffix,以便在同一 scope 使用多个 store namespaces 时消除歧义。 Namespace 组件只能包含字母数字字符、hyphens、underscores、dots、@+、colons 和 tildes。通配符(*?)会被拒绝,以防止 glob injection。
namespace 参数将在 v0.5.0 中必需。新代码请始终显式设置它。
没有提供 namespace factory 时,legacy default 会使用 LangGraph config metadata 中的 assistant_id。这意味着同一 assistant 的所有用户共享同一 storage。对于多用户生产部署,请始终提供 namespace factory。

ContextHubBackend

from deepagents import create_deep_agent
from deepagents.backends import ContextHubBackend

agent = create_deep_agent(
    model="google_genai:gemini-3.5-flash",
    backend=ContextHubBackend("my-agent"),
)
ContextHubBackend 将文件存储在 LangSmith Hub repo 中。使用 owner/namename 格式的 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)

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.5-flash",
    backend=CompositeBackend(
        default=StateBackend(),
        routes={
            "/memories/": StoreBackend(namespace=lambda _rt: ("memories",)),
        },
    ),
    store=InMemoryStore(),  # Store passed to create_deep_agent, not backend
)
工作方式:
  • CompositeBackend 基于 path prefix 将 file operations route 到不同 backends。
  • 在 listings 和 search results 中保留原始 path prefixes。
最适合:
  • 想同时为 agent 提供 thread-scoped 和 cross-thread storage 时,CompositeBackend 允许同时提供 StateBackendStoreBackend
  • 想把多个信息来源作为单个 filesystem 的一部分提供给 agent 时。
    • 例如,你在一个 Store 的 /memories/ 下存储长期 memories,同时还有一个自定义 backend 在 /docs/ 下提供文档访问。

指定 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 范围内。
from deepagents import create_deep_agent
from deepagents.backends import CompositeBackend, StateBackend, FilesystemBackend

agent = create_deep_agent(
    model="google_genai:gemini-3.5-flash",
    backend=CompositeBackend(
        default=StateBackend(),
        routes={
            "/memories/": FilesystemBackend(root_dir="/deepagents/myagent", virtual_mode=True),
        },
    )
)
行为:
  • /workspace/plan.mdStateBackend(thread-scoped)
  • /memories/agent.md/deepagents/myagent 下的 FilesystemBackend
  • lsglobgrep 会聚合结果,并显示原始 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。
  • 高效实现 lsglob,可用时使用 server-side filtering,否则使用 local filter。
  • 对于外部持久化(S3、Postgres 等),在 write/edit results 中返回 files_update=None(Python)或省略 filesUpdate(JS)。只有 in-memory state backends 需要返回 files update dict。
  • 使用 lsglob 作为 method names。
  • 返回带有 error 字段的结构化 result types,用于 missing files 或 invalid patterns(不要 raise)。
S3-style outline:
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 | None = None) -> 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-style outline:
  • 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 中应用 glob
    • grep 可以按 extension 或 last modified time fetch candidate rows,然后扫描 lines

Permissions

使用 permissions 以声明方式控制 agent 可以读取或写入哪些 files 和 directories。Permissions 会应用于内置 filesystem tools,并在调用 backend 之前评估。
from deepagents import create_deep_agent, FilesystemPermission

agent = create_deep_agent(
    model="google_genai:gemini-3.5-flash",
    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",
        ),
    ],
)
完整选项,包括 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):
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)
Generic wrapper(适用于任何 backend):
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 | None = None) -> 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)

从 backend factories 迁移

Backend factory pattern 自 deepagents 0.5.0 起已弃用。请直接传入预构造 backend instances,而不是 factory functions。
以前,StateBackendStoreBackend 等 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

DeprecatedReplacement
create_deep_agentbackend= 传入 callable直接传入 backend instance
StateBackend(runtime) 上的 runtime constructor argumentStateBackend()(无需参数)
StoreBackend(runtime) 上的 runtime constructor argumentStoreBackend()StoreBackend(namespace=..., store=...)
WriteResultEditResult 上的 files_update 字段State writes 现在由 backend 内部处理
Middleware write/edit tools 中的 Command wrappingTools 返回 plain strings,不需要 Command(update=...)
Factory pattern 运行时仍可工作,并会发出 deprecation warning。请在下一个 major version 前更新代码,改用 direct instances。

Migration example

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

agent = create_deep_agent(
    model="google_genai:gemini-3.5-flash",
    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.5-flash",
    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)中,namespace factories 会直接接收 LangGraph Runtime,而不是 BackendContext wrapper。旧的 BackendContext 形式仍会通过 backwards-compatible .runtime.state accessors 工作,但这些 accessors 会发出 deprecation warning,并将在 deepagents>=0.7 中移除。 发生了什么变化:
  • Factory argument 现在是 Runtime,不是 BackendContext
  • 移除 .runtime accessor,例如 ctx.runtime.context.user_id 变为 rt.server_info.user.identity
  • ctx.state 没有直接替代项。Namespace info 应是 read-only,并在一次 run 的生命周期内保持稳定,而 state 是可变的且逐步变化。从 state 派生 namespace 可能导致数据进入不一致的 keys。如果你有需要读取 agent state 的用例,请打开 issue
# 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,),
)

Protocol reference

Backends 必须实现 BackendProtocol Required methods:
  • ls(path: str) -> LsResult
    • 返回 entries,至少包含 path。可用时包含 is_dirsizemodified_at。按 path 排序以获得确定性输出。
  • read(file_path: str, offset: int = 0, limit: int = 2000) -> ReadResult
    • 成功时返回 file data。缺失文件时,返回 ReadResult(error="Error: File '/x' not found")
  • grep(pattern: str, path: Optional[str] = None, glob: Optional[str] = None) -> GrepResult
    • 返回结构化 matches。出错时返回 GrepResult(error="...")(不要 raise)。
  • glob(pattern: str, path: Optional[str] = None) -> GlobResult
    • 将 matched files 作为 FileInfo entries 返回(没有匹配时为空列表)。
  • write(file_path: str, content: str) -> WriteResult
    • Create-only。冲突时返回 WriteResult(error=...)。成功时设置 path,并对 state backends 设置 files_update={...};external backends 应使用 files_update=None
  • edit(file_path: str, old_string: str, new_string: str, replace_all: bool = False) -> EditResult
    • 除非 replace_all=True,否则强制 old_string 唯一。如果找不到,返回 error。成功时包含 occurrences
Supporting types:
  • LsResult(error, entries),成功时 entrieslist[FileInfo],失败时为 None
  • ReadResult(error, file_data),成功时 file_dataFileData dict,失败时为 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