跳到主要内容

文档索引

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

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

Deep Agents 通过 lsread_filewrite_fileedit_fileglobgrep 等工具向智能体暴露文件系统界面。这些工具通过可插拔的后端运行。read_file 工具在所有后端中原生支持图像文件(.png.jpg.jpeg.gif.webp),并将它们作为多模态内容块返回。 read_file 工具在所有后端中原生支持二进制文件(图像、PDF、音频、视频),返回带有类型化 contentmimeTypeReadResult 沙箱和 LocalShellBackend 还提供了一个 execute 工具。本页解释了如何:

快速入门

以下是几个可以快速与您的 Deep Agent 配合使用的预置文件系统后端
内置后端描述
默认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/"))
这使 Deep Agent 能够访问本地机器的文件系统。您可以指定智能体有权访问的根目录。请注意,提供的任何 root_dir 必须是绝对路径。
持久存储(LangGraph store)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 执行。没有隔离——仅在受控的开发环境中使用。请参阅下文的安全注意事项
组合型 (Composite)默认临时,/memories/ 持久化。Composite 后端具有最大的灵活性。您可以指定文件系统中的不同路由指向不同的后端。请参阅下文的 Composite 路由以获取可直接粘贴的代码示例。

内置后端

StateBackend (临时)

import { createDeepAgent, StateBackend } from "deepagents";

// By default we provide a StateBackend
const agent = createDeepAgent();

// Under the hood, it looks like
const agent2 = createDeepAgent({
  backend: new 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 配合使用,以启用基于路径的访问限制(阻止 ..~ 和根目录之外的绝对路径)。请注意,默认情况下(virtual_mode=False),即使设置了 root_dir 也不提供安全性。
import { createDeepAgent, FilesystemBackend } from "deepagents";

const agent = createDeepAgent({
  backend: new FilesystemBackend({ rootDir: ".", virtualMode: 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 不提供任何安全性,因为命令可以访问系统上的任何路径。
import { createDeepAgent, LocalShellBackend } from "deepagents";

const backend = new LocalShellBackend({ workingDirectory: "." });
const agent = createDeepAgent({ backend });
工作原理
  • 扩展了 FilesystemBackend,增加了用于在宿主机上运行 shell 命令的 execute 工具。
  • 命令直接在您的机器上使用 subprocess.run(shell=True) 运行,没有沙箱保护。
  • 支持 timeout(默认 120s)、max_output_bytes(默认 100,000)、envinherit_env 环境变量。
  • Shell 命令使用 root_dir 作为工作目录,但可以访问系统上的任何路径。
最适合
  • 本地编码助手和开发工具
  • 在您信任智能体的开发阶段进行快速迭代

StoreBackend (LangGraph 存储)

import { createDeepAgent, StoreBackend } from "deepagents";
import { InMemoryStore } from "@langchain/langgraph";

const store = new InMemoryStore();  // Good for local dev; omit for LangSmith Deployment
const agent = createDeepAgent({
  backend: new StoreBackend({
    namespace: (ctx) => [ctx.runtime.context.userId],
  }),
  store
});
部署到 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 的上下文模式 (context schema)传递的用户提供上下文(例如 user_id
  • rt.serverInfo — 在 LangGraph Server 上运行时服务器特定的元数据(助手 ID、图 ID、已通过身份验证的用户)
  • rt.executionInfo — 执行身份信息(线程 ID、运行 ID、检查点 ID)
Runtime 参数在 deepagents>=1.9.1 中可用。早期的 1.9.x 版本传递的是 BackendContext — 见下文的BackendContext 迁移rt.serverInfort.executionInfo 要求 deepagents>=1.9.0
通用命名空间模式
import { StoreBackend } from "deepagents";

// Per-user: each user gets their own isolated storage
const backend = new StoreBackend({
  namespace: (rt) => [rt.serverInfo.user.identity],
});

// Per-assistant: all users of the same assistant share storage
const backend = new StoreBackend({
  namespace: (rt) => [rt.serverInfo.assistantId],
});

// Per-thread: storage scoped to a single conversation
const backend = new StoreBackend({
  namespace: (rt) => [rt.executionInfo.threadId],
});
您可以组合多个组件来创建更具体的范围 — 例如,(user_id, thread_id) 用于按用户按对话隔离,或者附加像 "filesystem" 这样的后缀,以便在同一范围使用多个存储命名空间时消除歧义。 命名空间组件必须仅包含字母数字字符、连字符、下划线、点、@+、冒号和波浪号。拒绝通配符(*?)以防止 glob 注入。
namespace 参数在 v1.9.0 中将是必需的。对于新代码,请始终显式设置它。
未提供命名空间工厂时,旧版默认值使用 LangGraph 配置元数据中的 assistant_id。这意味着同一助手的所有用户共享相同的存储。对于多用户投入生产的情况,请务必提供命名空间工厂。

CompositeBackend (路由器)

import { createDeepAgent, CompositeBackend, StateBackend, StoreBackend } from "deepagents";
import { InMemoryStore } from "@langchain/langgraph";

const store = new InMemoryStore();
const agent = createDeepAgent({
  backend: new CompositeBackend(
    new StateBackend(),
    {
      "/memories/": new StoreBackend(),
    }
  ),
  store,
});
工作原理
  • CompositeBackend 根据路径前缀将文件操作路由到不同的后端。
  • 在列表和搜索结果中保留原始路径前缀。
最适合
  • 当您想同时给智能体提供临时和跨线程存储时,CompositeBackend 允许您同时提供 StateBackendStoreBackend
  • 当您有多个信息源想作为单个文件系统的一部分提供给智能体时。
    • 例如:您在其中一个 Store 的 /memories/ 下存储了长期记忆,同时您还有一个自定义后端,其文档可在 /docs/ 访问。

指定后端

  • 将后端实例传递给 createDeepAgent({ backend: ... })。文件系统中间件将其用于所有工具调用。
  • 后端必须实现 AnyBackendProtocol (BackendProtocolV1BackendProtocolV2) — 例如 new StateBackend(), new FilesystemBackend({ rootDir: "." }), new StoreBackend()
  • 如果省略,默认值为 new StateBackend()
在 1.9.0 版本之前,仅支持 BackendProtocol(现为 BackendProtocolV1)。V1 后端在运行时通过 adaptBackendProtocol() 自动适配为 V2。继续使用现有的 V1 后端无需更改代码。要更新到 v2,请参阅将现有后端更新到 v2

路由到不同的后端

将命名空间的部分路由到不同的后端。通常用于持久化 /memories/* 并保持其他所有内容为临时。
import { createDeepAgent, CompositeBackend, FilesystemBackend, StateBackend } from "deepagents";

const agent = createDeepAgent({
  backend: new CompositeBackend(
    new StateBackend(),
    {
      "/memories/": new FilesystemBackend({ rootDir: "/deepagents/myagent", virtualMode: true }),
    },
  ),
});
行为
  • /workspace/plan.mdStateBackend (临时)
  • /memories/agent.mdFilesystemBackend (位于 /deepagents/myagent 之下)
  • ls, glob, grep 聚合结果并显示原始路径前缀。
备注
  • 较长的前缀优先(例如,路由 "/memories/projects/" 可以覆盖 "/memories/")。
  • 对于 StoreBackend 路由,请确保通过 create_deep_agent(model=..., store=...) 提供了 store 或由平台配置了 store。

使用虚拟文件系统

构建自定义后端以将远程或数据库文件系统(例如 S3 或 Postgres)投影到工具命名空间中。 设计指南:
  • 路径是绝对路径(/x/y.txt)。决定如何将它们映射到您的存储键/行。
  • 高效地实现 lsglob(如果可用,使用服务器端过滤,否则使用本地过滤)。
  • 对于外部持久化(S3、Postgres 等),在写入/编辑结果中返回 files_update=None (Python) 或省略 filesUpdate (JS) — 只有内存状态后端需要返回文件更新字典。
  • 使用 lsglob 作为方法名。
  • 所有查询方法(ls, read, readRaw, grep, glob)必须返回结构化的 Result 对象(例如 LsResult, ReadResult),并带有一个可选的 error 字段。
  • 通过返回带有适当 mimeTypeUint8Array 内容,在 read() 中支持二进制文件。
S3 风格大纲
import {
  type BackendProtocolV2,
  type LsResult,
  type ReadResult,
  type ReadRawResult,
  type GrepResult,
  type GlobResult,
  type WriteResult,
  type EditResult,
} from "deepagents";

class S3Backend implements BackendProtocolV2 {
  constructor(private bucket: string, private prefix: string = "") {
    this.prefix = prefix.replace(/\/$/, "");
  }

  private key(path: string): string {
    return `${this.prefix}${path}`;
  }

  async ls(path: string): Promise<LsResult> {
    // List objects under key(path); return { files: [...] }
    ...
  }

  async read(filePath: string, offset?: number, limit?: number): Promise<ReadResult> {
    // Fetch object; return { content, mimeType }
    // For binary files, return Uint8Array content
    ...
  }

  async readRaw(filePath: string): Promise<ReadRawResult> {
    // Return { data: FileData }
    ...
  }

  async grep(pattern: string, path?: string | null, glob?: string | null): Promise<GrepResult> {
    // Search text files; skip binary; return { matches: [...] }
    ...
  }

  async glob(pattern: string, path = "/"): Promise<GlobResult> {
    // Apply glob relative to path; return { files: [...] }
    ...
  }

  async write(filePath: string, content: string): Promise<WriteResult> {
    // Enforce create-only semantics; return { path: filePath, filesUpdate: null }
    ...
  }

  async edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): Promise<EditResult> {
    // Read → replace → write → return { path, occurrences }
    ...
  }
}
Postgres 风格大纲
  • files(path text primary key, content text, mime_type text, created_at timestamptz, modified_at timestamptz)
  • 将工具操作映射到 SQL
    • ls 使用 WHERE path LIKE $1 || '%' → 返回 LsResult
    • 在 SQL 中进行 glob 过滤或获取后再在本地应用 glob → 返回 GlobResult
    • grep 可以通过扩展名或最后修改时间获取候选行,然后扫描行(跳过 mime_type 为二进制的行) → 返回 GrepResult

权限

使用权限来声明式地控制智能体可以读取或写入哪些文件和目录。权限适用于内置的文件系统工具,并在调用后端之前进行评估。 有关包括规则排序、子智能体权限和组合后端交互在内的全套选项,请参阅权限指南

添加策略钩子

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

class GuardedBackend extends FilesystemBackend {
  private denyPrefixes: string[];

  constructor({ denyPrefixes, ...options }: { denyPrefixes: string[]; rootDir?: string }) {
    super(options);
    this.denyPrefixes = denyPrefixes.map(p => p.endsWith("/") ? p : p + "/");
  }

  async write(filePath: string, content: string): Promise<WriteResult> {
    if (this.denyPrefixes.some(p => filePath.startsWith(p))) {
      return { error: `Writes are not allowed under ${filePath}` };
    }
    return super.write(filePath, content);
  }

  async edit(filePath: string, oldString: string, newString: string, replaceAll = false): Promise<EditResult> {
    if (this.denyPrefixes.some(p => filePath.startsWith(p))) {
      return { error: `Edits are not allowed under ${filePath}` };
    }
    return super.edit(filePath, oldString, newString, replaceAll);
  }
}
通用包装器(适用于任何后端)
import {
  type BackendProtocolV2,
  type LsResult,
  type ReadResult,
  type ReadRawResult,
  type GrepResult,
  type GlobResult,
  type WriteResult,
  type EditResult,
} from "deepagents";

class PolicyWrapper implements BackendProtocolV2 {
  private denyPrefixes: string[];

  constructor(private inner: BackendProtocolV2, denyPrefixes: string[] = []) {
    this.denyPrefixes = denyPrefixes.map(p => p.endsWith("/") ? p : p + "/");
  }

  private isDenied(path: string): boolean {
    return this.denyPrefixes.some(p => path.startsWith(p));
  }

  ls(path: string): Promise<LsResult> { return this.inner.ls(path); }
  read(filePath: string, offset?: number, limit?: number): Promise<ReadResult> { return this.inner.read(filePath, offset, limit); }
  readRaw(filePath: string): Promise<ReadRawResult> { return this.inner.readRaw(filePath); }
  grep(pattern: string, path?: string | null, glob?: string | null): Promise<GrepResult> { return this.inner.grep(pattern, path, glob); }
  glob(pattern: string, path?: string): Promise<GlobResult> { return this.inner.glob(pattern, path); }

  async write(filePath: string, content: string): Promise<WriteResult> {
    if (this.isDenied(filePath)) return { error: `Writes are not allowed under ${filePath}` };
    return this.inner.write(filePath, content);
  }

  async edit(filePath: string, oldString: string, newString: string, replaceAll = false): Promise<EditResult> {
    if (this.isDenied(filePath)) return { error: `Edits are not allowed under ${filePath}` };
    return this.inner.edit(filePath, oldString, newString, replaceAll);
  }
}

多模态和二进制文件

多模态文件支持(PDF、音频、视频)需要 deepagents>=1.9.0
V2 后端原生支持二进制文件。当 read() 遇到二进制文件(由文件扩展名的 MIME 类型决定)时,它返回带有 Uint8Array 内容和相应 mimeTypeReadResult。文本文件返回 string 内容。

支持的 MIME 类型

类别扩展名MIME 类型
图像.png, .jpg/.jpeg, .gif, .webp, .svg, .heic, .heifimage/png, image/jpeg, image/gif, image/webp, image/svg+xml, image/heic, image/heif
音频.mp3, .wav, .aiff, .aac, .ogg, .flacaudio/mpeg, audio/wav, audio/aiff, audio/aac, audio/ogg, audio/flac
视频.mp4, .webm, .mpeg/.mpg, .mov, .avi, .flv, .wmv, .3gppvideo/mp4, video/webm, video/mpeg, video/quicktime, video/x-msvideo, video/x-flv, video/x-ms-wmv, video/3gpp
文档.pdf, .ppt, .pptxapplication/pdf, application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation
文本.txt, .html, .json, .js, .ts, .pytext/plain, text/html, application/json

读取二进制文件

const result = await backend.read("/workspace/screenshot.png");

if (result.error) {
  console.error(result.error);
} else if (result.content instanceof Uint8Array) {
  // Binary file — content is Uint8Array, mimeType is set
  console.log(`Binary file: ${result.mimeType}`); // "image/png"
} else {
  // Text file — content is string
  console.log(`Text file: ${result.mimeType}`); // "text/plain"
}

FileData 格式

FileData 是用于在状态和存储后端中存储文件内容的类型。
type FileData =
  // Current format (v2)
  | {
      content: string | Uint8Array; // string for text, Uint8Array for binary
      mimeType: string;             // e.g. "text/plain", "image/png"
      created_at: string;           // ISO 8601 timestamp
      modified_at: string;          // ISO 8601 timestamp
    }
  // Legacy format (v1)
  | {
      content: string[];            // array of lines
      created_at: string;           // ISO 8601 timestamp
      modified_at: string;          // ISO 8601 timestamp
    };
后端在从状态或存储中读取时可能会遇到任何一种格式。框架会透明地处理两者。新的写入默认采用 v2 格式。在旧版读取器需要旧版格式的滚动部署期间,将 fileFormat: "v1" 传递给后端构造函数(例如 new StoreBackend({ fileFormat: "v1" }))。

从后端工厂迁移

后端工厂模式自 deepagents 1.9.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

已弃用替换方案
BackendFactory 类型直接传递后端实例
BackendRuntime 接口后端内部解析上下文
StateBackend(runtime, options?) 构造函数重载new StateBackend(options?)
StoreBackend(stateAndStore, options?) 构造函数重载new StoreBackend(options?)
WriteResultEditResult 上的 filesUpdate 字段状态写入现在由后端内部处理
工厂模式在运行时仍然有效,并会发出弃用警告。请在下一个大版本发布前更新代码以直接使用实例。

迁移示例

// Before (deprecated)
import { createDeepAgent, CompositeBackend, StateBackend, StoreBackend } from "deepagents";

const agent = createDeepAgent({
  backend: (config) => new CompositeBackend(
    new StateBackend(config),
    { "/memories/": new StoreBackend(config, {
      namespace: (rt) => [rt.serverInfo.user.identity],
    }) },
  ),
});

// After
const agent = createDeepAgent({
  backend: new CompositeBackend(
    new StateBackend(),
    { "/memories/": new StoreBackend({
      namespace: (rt) => [rt.serverInfo.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 没有直接替代品。命名空间信息在运行期间应该是只读且稳定的,而状态是可变的并随步骤变化——基于状态派生命名空间存在数据落入不一致键的风险。如果您有需要读取智能体状态的用例,请提交 issue
// Before (deprecated, removed in v0.7)
new StoreBackend({
  namespace: (ctx) => [ctx.runtime.context.userId],
});

// After
new StoreBackend({
  namespace: (rt) => [rt.serverInfo.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)
  • 包含以下字段的 FileInfopath (必需),可选字段 is_dir, size, modified_at
  • 包含以下字段的 GrepMatchpath, line, text
  • 包含以下字段的 FileDatacontent (str), encoding ("utf-8""base64"), created_at, modified_at。 ::
后端实现 BackendProtocolV2。所有查询方法都返回带有 { error?: string, ...data } 的结构化 Result 对象。

必需方法

  • ls(path: string) → LsResult
    • 列出指定目录中的文件和子目录(非递归)。目录的路径带有尾随 /is_dir=true。在可用时包含 is_dirsizemodified_at
  • read(filePath: string, offset?: number, limit?: number) → ReadResult
    • 读取文件内容。对于文本文件,内容按行偏移量/限制进行分页(默认偏移量 0,限制 500)。对于二进制文件,返回完整的原始 Uint8Array 内容并设置 mimeType 字段。如果文件缺失,返回 { error: "File '/x' not found" }
  • readRaw(filePath: string) → ReadRawResult
    • 以原始 FileData 形式读取文件内容。返回完整的文件数据,包括时间戳。
  • grep(pattern: string, path?: string | null, glob?: string | null) → GrepResult
    • 在文件内容中搜索字面文本模式。跳过二进制文件(由 MIME 类型决定)。失败时返回 { error: "..." }
  • glob(pattern: string, path?: string) → GlobResult
    • FileInfo 条目形式返回匹配 glob 模式的文件。
  • write(filePath: string, content: string) → WriteResult
    • 仅限创建语义。冲突时返回 { error: "..." }。成功时,设置 path,对于状态后端设置 filesUpdate={...};外部后端应使用 filesUpdate=null
  • edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean) → EditResult
    • 除非 replaceAll=true,否则强制 oldString 的唯一性。如果未找到,则返回错误。成功时包含 occurrences

可选方法

  • uploadFiles(files: Array<[string, Uint8Array]>) → FileUploadResponse[] — 上传多个文件(适用于沙箱后端)。
  • downloadFiles(paths: string[]) → FileDownloadResponse[] — 下载多个文件(适用于沙箱后端)。

结果类型

类型成功字段错误字段
ReadResultcontent?: string | Uint8Array, mimeType?: string错误
ReadRawResultdata?: FileData错误
LsResultfiles?: FileInfo[]错误
GlobResultfiles?: FileInfo[]错误
GrepResultmatches?: GrepMatch[]错误
WriteResultpath?: string错误
EditResultpath?: string, occurrences?: number错误

辅助类型

  • FileInfopath (必需),可选字段 is_dir, size, modified_at
  • GrepMatchpath, line (从 1 开始计), text
  • FileData — 带有时间戳的文件内容。见 FileData 格式

沙箱扩展

SandboxBackendProtocolV2 扩展了 BackendProtocolV2,具有
  • execute(command: string) → ExecuteResponse — 在沙箱中运行 shell 命令。
  • readonly id: string — 沙箱实例的唯一标识符。

将现有后端更新到 V2

方法重命名

V1 方法V2 方法返回类型更改
lsInfo(path)ls(path)FileInfo[]LsResult
read(filePath, offset, limit)read(filePath, offset, limit)stringReadResult
readRaw(filePath)readRaw(filePath)FileDataReadRawResult
grepRaw(pattern, path, glob)grep(pattern, path, glob)GrepMatch[] | stringGrepResult
globInfo(pattern, path)glob(pattern, path)FileInfo[]GlobResult
write(...)write(...)未更改 (WriteResult)
edit(...)edit(...)未更改 (EditResult)

类型重命名

V1 类型V2 类型
BackendProtocolBackendProtocolV2
SandboxBackendProtocolSandboxBackendProtocolV2

适配实用工具

如果您有现有的 V1 后端需要在仅限 V2 的代码中使用,请使用适配函数
import { adaptBackendProtocol, adaptSandboxProtocol } from "deepagents";

// Adapt a V1 backend to V2
const v2Backend = adaptBackendProtocol(v1Backend);

// Adapt a V1 sandbox to V2
const v2Sandbox = adaptSandboxProtocol(v1Sandbox);
框架会自动适配传递给 createDeepAgent() 的 V1 后端。只有在直接调用协议方法时才需要手动适配。

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