Skip to main content

Documentation Index

Fetch the complete documentation index at: https://nvd-54.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

createDeepAgent 具有以下配置选项:
const agent = createDeepAgent({
  backend?: AnyBackendProtocol | (config: __type) => AnyBackendProtocol,
  checkpointer?: boolean | BaseCheckpointSaver<number>,
  contextSchema?: ContextSchema,
  interruptOn?: Record<string, boolean | __type>,
  memory?: string[],
  middleware?: TMiddleware,
  model?: string | BaseLanguageModel<any, BaseLanguageModelCallOptions>,
  name?: string,
  permissions?: FilesystemPermission[],
  responseFormat?: TResponse,
  skills?: string[],
  store?: BaseStore,
  streamTransformers?: TStreamTransformers,
  subagents?: TSubagents,
  systemPrompt?: string | SystemMessage<MessageStructure<MessageToolSet>>,
  tools?: TTools | StructuredTool<ToolInputSchemaBase, any, any, any, unknown>[]
});
完整参数列表请参阅 createDeepAgent API 参考文档。

模型

传入 provider:model 格式的 model 字符串,或一个已初始化的模型实例。所有提供商请参阅支持的模型,经过测试的推荐请参阅推荐模型
使用 provider:model 格式(例如 openai:gpt-5.4)可以在不同模型之间快速切换。
👉 Read the OpenAI chat model integration docs
npm install @langchain/openai deepagents
import { createDeepAgent } from "deepagents";

process.env.OPENAI_API_KEY = "your-api-key";

const agent = createDeepAgent({ model: "gpt-5.4" });
// this calls initChatModel for the specified model with default parameters
// to use specific model parameters, use initChatModel directly
Chat Model 会自动重试瞬时 API 故障(使用指数退避)。有关默认值、限制以及调整 max_retries / timeout 的代码示例,请参阅 LangChain 模型页面。

工具

除了用于规划、文件管理和子 Agent 生成的内置工具外,你还可以提供自定义工具:
import { tool } from "langchain";
import { TavilySearch } from "@langchain/tavily";
import { createDeepAgent } from "deepagents";
import { z } from "zod";

const internetSearch = tool(
  async ({
    query,
    maxResults = 5,
    topic = "general",
    includeRawContent = false,
  }: {
    query: string;
    maxResults?: number;
    topic?: "general" | "news" | "finance";
    includeRawContent?: boolean;
  }) => {
    const tavilySearch = new TavilySearch({
      maxResults,
      tavilyApiKey: process.env.TAVILY_API_KEY,
      includeRawContent,
      topic,
    });
    return await tavilySearch._call({ query });
  },
  {
    name: "internet_search",
    description: "Run a web search",
    schema: z.object({
      query: z.string().describe("The search query"),
      maxResults: z.number().optional().default(5),
      topic: z
        .enum(["general", "news", "finance"])
        .optional()
        .default("general"),
      includeRawContent: z.boolean().optional().default(false),
    }),
  },
);

const agent = createDeepAgent({
  model: "google-genai:gemini-3.1-pro-preview",
  tools: [internetSearch],
});

系统提示词

Deep Agents 自带内置系统提示词。Deep Agent 的价值来自于 SDK 在模型之上提供的编排层——规划、虚拟文件系统工具和子 Agent——而模型需要知道这些工具的存在以及何时使用它们。内置提示词教会 Agent 如何使用这些脚手架,这样你就不必在每个项目中重新推导;通过 profile 或你自己的 system_prompt= 来调整它,而不是逐字复制。 当 Middleware 添加特殊工具(如文件系统工具)时,会将它们追加到系统提示词中。 每个 Deep Agent 还应包含针对其特定用例的自定义系统提示词:
import { createDeepAgent } from "deepagents";

const researchInstructions =
  `You are an expert researcher. ` +
  `Your job is to conduct thorough research, and then ` +
  `write a polished report.`;

const agent = createDeepAgent({
  model: "google-genai:gemini-3.1-pro-preview",
  systemPrompt: researchInstructions,
});

提示词组装

Deep Agents 从最多四个命名部分构建系统提示词,以便调用者提供的指令、SDK 内置的 Agent 指导以及任何模型特定的 profile 覆盖可以以可预测的优先级共存。如果没有这种分层,为 Claude 调优的 profile 后缀(例如)可能会根据调用顺序覆盖或被你的 system_prompt= 参数覆盖;命名槽位使排序明确且稳定。 在实践中,大多数调用者只会遇到两个槽位:USER(你的 system_prompt=)和 BASE(SDK 默认值)。选择带有内置 profile 的模型——目前是 Anthropic 或 OpenAI——会添加一个 SUFFIX。完整的四部分组装主要在你编写自定义 HarnessProfile 或调试 profile 文本出现位置时才相关。 四个命名部分(每个都可能不存在):
名称来源说明
USERcreate_deep_agentsystem_prompt= 参数strSystemMessage;未设置时省略。
BASESDK 默认值 (BASE_AGENT_PROMPT)始终存在,除非被 profile 的 CUSTOM 替换。
CUSTOMHarnessProfile.base_system_prompt当匹配的 profile 设置此项时,直接替换 BASE
SUFFIXHarnessProfile.system_prompt_suffix当匹配的 profile 设置此项时,追加在最后。
顺序始终是 USER -> (BASECUSTOM) -> SUFFIX,用空行(\n\n)连接。由此产生两个不变量:
  1. USER 始终在最前面。 调用者的文本先于任何 SDK 或 profile 内容,因此无论选择哪个模型,角色/指令都会优先。
  2. SUFFIX 始终在最后。 Profile 后缀紧靠对话历史,这是模型调优指导最可靠的放置位置。
组装形态(✓ = 字段已设置,- = 字段未设置):
system_prompt=profile base_system_prompt (CUSTOM)profile system_prompt_suffix (SUFFIX)最终组装的系统提示词
None--BASE
None-BASE + SUFFIX
None-CUSTOM
NoneCUSTOM + SUFFIX
str--USER + BASE
str-USER + BASE + SUFFIX
str-USER + CUSTOM
strUSER + CUSTOM + SUFFIX
实际示例——内置 profile(Anthropic、OpenAI)仅提供 system_prompt_suffix,因此典型调用位于 str + - + 行:
agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    system_prompt="You are a customer-support agent for ACME Corp.",
)
# Final = USER + BASE + SUFFIX
#       = "You are a customer-support agent for ACME Corp."
#         + "\n\n"
#         + BASE_AGENT_PROMPT
#         + "\n\n"
#         + <Claude-specific guidance>
传入 SystemMessage(而非字符串)会触发不同的拼接路径:右侧组装(BASECUSTOM 加上任何 SUFFIX)作为额外的文本内容块追加到消息已有的 content_blocks 上。相同的逻辑排序仍然适用(调用者的块在前),调用者块上的任何 cache_control 标记都会保留——这对放置显式 Anthropic Prompt 缓存断点很有用。
相同的覆盖规则适用于声明式子 Agent——每个子 Agent 针对自己的模型重新运行 profile 解析,然后将解析后的 profile 的 base_system_prompt / system_prompt_suffix 应用到其编写的 system_prompt。子 Agent 的 system_prompt 扮演 BASE 角色;CUSTOMSUFFIX 来自匹配子 Agent 模型的 profile(可能与主 Agent 的 profile 不同)。
spec["system_prompt"]profile base_system_prompt (CUSTOM)profile system_prompt_suffix (SUFFIX)最终子 Agent 系统提示词
authored--authored
authored-authored + SUFFIX
authored-CUSTOM
authoredCUSTOM + SUFFIX
子 Agent 没有 USER 段——规范中编写的 system_prompt 是最接近的类似物,保留在 BASE 槽位中。仅提供 system_prompt_suffix 的 profile(内置 Anthropic / OpenAI profile 的常见情况)只是追加到子 Agent 作者编写的内容之后;设置了 base_system_prompt 的 profile 将完全替换编写的提示词,因此请谨慎使用该字段。
自动添加的通用子 Agent 遵循相同的覆盖规则,但多了一层:GP 基础提示词解析为 general_purpose_subagent.system_prompt(如果已设置)-> HarnessProfile.base_system_prompt(如果已设置)-> SDK GP 默认值。Profile 后缀无论如何都会叠加在上面。这两个覆盖字段都可以携带基础提示词替换,但它们不可互换。general_purpose_subagent.system_prompt 是 GP 特定配置;base_system_prompt 是主要针对主 Agent 的全局覆盖。当两者都设置时,GP 特定意图对 GP 子 Agent 优先,这样同时调整两个字段的用户不会看到其 GP 覆盖被静默丢弃:
register_harness_profile(
    "anthropic",
    HarnessProfile(
        base_system_prompt="You are ACME's support orchestrator.",  # main agent
        general_purpose_subagent=GeneralPurposeSubagentProfile(
            system_prompt="You are a research subagent. Cite sources.",  # GP subagent
        ),
        system_prompt_suffix="Always think step by step.",
    ),
)
层级最终系统提示词
主 Agent"You are ACME's support orchestrator." + SUFFIX
GP 子 Agent"You are a research subagent. Cite sources." + SUFFIX
如果 general_purpose_subagent.system_prompt 未设置,GP 子 Agent 会回退到 base_system_prompt(如果已设置),最终回退到 SDK GP 默认值。

Middleware

Deep Agents 支持任何 Middleware,包括下方列出的内置 Middleware、LangChain 预构建 Middleware、特定提供商 Middleware 以及你自行编写的自定义 Middleware。将 Middleware 传入 create_deep_agentmiddleware 参数。 默认情况下,Deep Agents 可以访问以下 Middleware: 如果你使用了记忆、技能或人机协作,还会包含以下 Middleware:
  • MemoryMiddleware:当提供 memory 参数时,跨会话持久化和检索对话上下文
  • SkillsMiddleware:当提供 skills 参数时,启用自定义技能
  • HumanInTheLoopMiddleware:当提供 interruptOn 参数时,在指定节点暂停以等待人工审批或输入

预构建 Middleware

LangChain 提供了额外的预构建 Middleware,让你可以添加各种功能,如重试、回退或 PII 检测。更多信息请参阅预构建 Middleware deepagents 包还暴露了 createSummarizationMiddleware 用于同样的工作流。更多详情请参阅摘要

特定提供商 Middleware

有关针对特定 LLM 提供商优化的 Middleware,请参阅官方集成社区集成

自定义 Middleware

你可以提供额外的 Middleware 来扩展功能、添加工具或实现自定义钩子:
import { tool, createMiddleware } from "langchain";
import { createDeepAgent } from "deepagents";
import * as z from "zod";

const getWeather = tool(
  ({ city }: { city: string }) => {
    return `The weather in ${city} is sunny.`;
  },
  {
    name: "get_weather",
    description: "Get the weather in a city.",
    schema: z.object({
      city: z.string(),
    }),
  },
);

let callCount = 0;

const logToolCallsMiddleware = createMiddleware({
  name: "LogToolCallsMiddleware",
  wrapToolCall: async (request, handler) => {
    // 拦截并记录每次 Tool 调用 - 演示横切关注点
    callCount += 1;
    const toolName = request.toolCall.name;

    console.log(`[Middleware] Tool 调用 #${callCount}: ${toolName}`);
    console.log(
      `[Middleware] 参数: ${JSON.stringify(request.toolCall.args)}`,
    );

    // 执行 Tool 调用
    const result = await handler(request);

    // 记录结果
    console.log(`[Middleware] Tool 调用 #${callCount} 完成`);

    return result;
  },
});

const agent = await createDeepAgent({
  model: "google-genai:gemini-3.1-pro-preview",
  tools: [getWeather] as any,
  middleware: [logToolCallsMiddleware] as any,
});
不要在初始化后修改属性如果你需要在钩子调用之间跟踪值(例如计数器或累积数据),请使用 Graph State。 Graph State 按设计限定在线程范围内,因此在并发下更新是安全的。应该这样做:
const customMiddleware = createMiddleware({
  name: "CustomMiddleware",
  beforeAgent: async (state) => {
    return { x: (state.x ?? 0) + 1 }; // 改为更新 Graph State
  },
});
不要这样做:
let x = 1;

const customMiddlewareBad = createMiddleware({
  name: "CustomMiddleware",
  beforeAgent: async () => {
    x += 1; // 修改外部变量会导致竞态条件
  },
});
就地修改,例如在 beforeAgent 中修改 state.x、在 beforeAgent 中修改共享变量或在钩子中更改其他共享值,可能导致微妙的错误和竞态条件,因为许多操作是并发运行的(子 Agent、并行工具和不同线程上的并行调用)。有关使用自定义属性扩展 State 的完整详情,请参阅自定义 Middleware - 自定义 State Schema。 如果你必须在自定义 Middleware 中使用修改操作,请考虑当子 Agent、并行工具或并发 Agent 调用同时运行时会发生什么。

解释器

使用解释器添加一个在作用域限定的 QuickJS 运行时中执行 JavaScript 的 eval 工具。当 Agent 需要以编程方式组合工具、批量处理工作、在代码中处理错误或在没有完整 shell 环境的情况下转换结构化数据时,解释器非常有用。
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "google-genai:gemini-3.1-pro-preview",
  middleware: [createCodeInterpreterMiddleware()],
});
有关设置、编程式工具调用、解释器技能和限制,请参阅解释器

子 Agent

为了隔离详细工作并避免上下文膨胀,请使用子 Agent:
import { tool } from "langchain";
import { TavilySearch } from "@langchain/tavily";
import { createDeepAgent, type SubAgent } from "deepagents";
import { z } from "zod";

const internetSearch = tool(
  async ({
    query,
    maxResults = 5,
    topic = "general",
    includeRawContent = false,
  }: {
    query: string;
    maxResults?: number;
    topic?: "general" | "news" | "finance";
    includeRawContent?: boolean;
  }) => {
    const tavilySearch = new TavilySearch({
      maxResults,
      tavilyApiKey: process.env.TAVILY_API_KEY,
      includeRawContent,
      topic,
    });
    return await tavilySearch._call({ query });
  },
  {
    name: "internet_search",
    description: "Run a web search",
    schema: z.object({
      query: z.string().describe("The search query"),
      maxResults: z.number().optional().default(5),
      topic: z
        .enum(["general", "news", "finance"])
        .optional()
        .default("general"),
      includeRawContent: z.boolean().optional().default(false),
    }),
  },
);

const researchSubagent: SubAgent = {
  name: "research-agent",
  description: "Used to research more in depth questions",
  systemPrompt: "You are a great researcher",
  tools: [internetSearch],
  model: "openai:gpt-5.4",  // Optional override, defaults to main agent model
};
const subagents = [researchSubagent];

const agent = createDeepAgent({
  model: "claude-sonnet-4-6",
  subagents,
});
更多信息请参阅子 Agent

后端

Deep Agent 的工具可以利用虚拟文件系统来存储、访问和编辑文件。默认情况下,Deep Agent 使用 StateBackend 如果你使用技能记忆,必须在创建 Agent 之前将预期的技能或记忆文件添加到后端。
线程范围的文件系统后端,存储在 langgraph State 中。文件在线程内的各轮对话中持久化(通过你的 checkpointer),不会跨线程共享。
import { createDeepAgent, StateBackend } from "deepagents";

// 默认情况下 we provide a StateBackend
const agent = createDeepAgent();

// Under the hood, it looks like
const agent2 = createDeepAgent({
  backend: new StateBackend(),
});
更多信息请参阅后端

Sandbox

Sandbox 是专门的后端,在隔离环境中运行 Agent 代码,拥有自己的文件系统和用于 shell 命令的 execute 工具。 当你希望 Deep Agent 编写文件、安装依赖和运行命令而不更改本地机器上的任何内容时,请使用 Sandbox 后端。 你可以通过在创建 Deep Agent 时将 Sandbox 后端传入 backend 来配置 Sandbox:
import { createDeepAgent } from "deepagents";
import { ChatAnthropic } from "@langchain/anthropic";
import { DenoSandbox } from "@langchain/deno";

// Create and initialize the sandbox
const sandbox = await DenoSandbox.create({
  memoryMb: 1024,
  lifetime: "10m",
});

try {
  const agent = createDeepAgent({
    model: new ChatAnthropic({ model: "claude-opus-4-6" }),
    systemPrompt: "You are a JavaScript coding assistant with sandbox access.",
    backend: sandbox,
  });

  const result = await agent.invoke({
    messages: [
      {
        role: "user",
        content:
          "Create a simple HTTP server using Deno.serve and test it with curl",
      },
    ],
  });
} finally {
  await sandbox.close();
}
更多信息请参阅 Sandbox

人机协作

某些工具操作可能是敏感的,需要在执行前获得人工审批。 你可以为每个工具配置审批:
import { tool } from "langchain";
import { createDeepAgent } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
import { z } from "zod";

const deleteFile = tool(
  async ({ path }: { path: string }) => {
    return `Deleted ${path}`;
  },
  {
    name: "delete_file",
    description: "Delete a file from the filesystem.",
    schema: z.object({
      path: z.string(),
    }),
  },
);

const readFile = tool(
  async ({ path }: { path: string }) => {
    return `Contents of ${path}`;
  },
  {
    name: "read_file",
    description: "Read a file from the filesystem.",
    schema: z.object({
      path: z.string(),
    }),
  },
);

const sendEmail = tool(
  async ({ to, subject, body }: { to: string; subject: string; body: string }) => {
    return `Sent email to ${to}`;
  },
  {
    name: "send_email",
    description: "Send an email.",
    schema: z.object({
      to: z.string(),
      subject: z.string(),
      body: z.string(),
    }),
  },
);

// Checkpointer is REQUIRED for human-in-the-loop
const checkpointer = new MemorySaver();

const agent = createDeepAgent({
  model: "google_genai:gemini-3.1-pro-preview",
  tools: [deleteFile, readFile, sendEmail],
  interruptOn: {
    delete_file: true,  // Default: approve, edit, reject, respond
    read_file: false,   // No interrupts needed
    send_email: { allowedDecisions: ["approve", "reject"] },  // No editing
  },
  checkpointer,  // Required!
});
你可以为 Agent 和子 Agent 配置在工具调用时以及在工具调用内部的 Interrupt。 更多信息请参阅人机协作

技能

你可以使用技能为你的 Deep Agent 提供新的能力和专业知识。 工具通常涵盖较低级别的功能,如原生文件系统操作或规划,而技能可以包含关于如何完成任务的详细说明、参考信息以及其他资源(如模板)。 这些文件仅在 Agent 确定该技能对当前 Prompt 有用时才会被加载。 这种渐进式披露减少了 Agent 在启动时需要考虑的 Token 和上下文数量。 有关示例技能,请参阅 Deep Agents 示例技能 要将技能添加到你的 Deep Agent,请将它们作为参数传入 create_deep_agent
import { createDeepAgent, StateBackend, type FileData } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const checkpointer = new MemorySaver();
const backend = new StateBackend();

function createFileData(content: string): FileData {
  const now = new Date().toISOString();
  return {
    content: content.split("\n"),
    created_at: now,
    modified_at: now,
  };
}

const skillsFiles: Record<string, FileData> = {};

const skillUrl =
  "https://raw.githubusercontent.com/langchain-ai/deepagentsjs/refs/heads/main/examples/skills/langgraph-docs/SKILL.md";
const response = await fetch(skillUrl);
const skillContent = await response.text();

skillsFiles["/skills/langgraph-docs/SKILL.md"] = createFileData(skillContent);

const agent = await createDeepAgent({
  model: "openai:gpt-5.4",
  backend,
  checkpointer,
  // IMPORTANT: deepagents skill source paths are virtual (POSIX) paths relative to the backend root.
  skills: ["/skills/"],
  middleware: [createCodeInterpreterMiddleware({ skillsBackend: backend })],
});

const config = {
  configurable: {
    thread_id: `thread-${Date.now()}`,
  },
};

const result = await agent.invoke(
  {
    messages: [
      {
        role: "user",
        content: "what is langraph? Use the langgraph-docs skill if available.",
      },
    ],
    files: skillsFiles,
  },
  config,
);

记忆

使用 AGENTS.md 文件为你的 Deep Agent 提供额外上下文。 你可以在创建 Deep Agent 时将一个或多个文件路径传入 memory 参数:
import { createDeepAgent, type FileData } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";

const AGENTS_MD_URL =
  "https://raw.githubusercontent.com/langchain-ai/deepagents/refs/heads/main/examples/text-to-sql-agent/AGENTS.md";

async function fetchText(url: string): Promise<string> {
  const res = await fetch(url);
  if (!res.ok) {
    throw new Error(`Failed to fetch ${url}: ${res.status} ${res.statusText}`);
  }
  return await res.text();
}

const agentsMd = await fetchText(AGENTS_MD_URL);
const checkpointer = new MemorySaver();

function createFileData(content: string): FileData {
  const now = new Date().toISOString();
  return {
    content,
    mimeType: "text/plain",
    created_at: now,
    modified_at: now,
  };
}

const agent = await createDeepAgent({
  model: "google-genai:gemini-3.1-pro-preview",
  memory: ["/AGENTS.md"],
  checkpointer: checkpointer,
});

const result = await agent.invoke(
  {
    messages: [
      {
        role: "user",
        content: "Please tell me what's in your memory files.",
      },
    ],
    // 为默认 StateBackend 的状态内文件系统预填充数据(虚拟路径必须以 "/" 开头)。
    files: { "/AGENTS.md": createFileData(agentsMd) },
  },
  { configurable: { thread_id: "12345" } },
);

结构化输出

Deep Agents 支持结构化输出 你可以通过将期望的结构化输出 Schema 作为 responseFormat 参数传入 createDeepAgent() 调用来设置。 当模型生成结构化数据时,数据会被捕获、验证并返回到 Agent State 的 ‘structuredResponse’ 键中。
import { tool } from "langchain";
import { TavilySearch } from "@langchain/tavily";
import { createDeepAgent } from "deepagents";
import { z } from "zod";

const internetSearch = tool(
  async ({
    query,
    maxResults = 5,
    topic = "general",
    includeRawContent = false,
  }: {
    query: string;
    maxResults?: number;
    topic?: "general" | "news" | "finance";
    includeRawContent?: boolean;
  }) => {
    const tavilySearch = new TavilySearch({
      maxResults,
      tavilyApiKey: process.env.TAVILY_API_KEY,
      includeRawContent,
      topic,
    });
    return await tavilySearch._call({ query });
  },
  {
    name: "internet_search",
    description: "Run a web search",
    schema: z.object({
      query: z.string().describe("The search query"),
      maxResults: z.number().optional().default(5),
      topic: z
        .enum(["general", "news", "finance"])
        .optional()
        .default("general"),
      includeRawContent: z.boolean().optional().default(false),
    }),
  },
);

const weatherReportSchema = z.object({
  location: z.string().describe("The location for this weather report"),
  temperature: z.number().describe("Current temperature in Celsius"),
  condition: z
    .string()
    .describe("Current weather condition (e.g., sunny, cloudy, rainy)"),
  humidity: z.number().describe("Humidity percentage"),
  windSpeed: z.number().describe("Wind speed in km/h"),
  forecast: z.string().describe("Brief forecast for the next 24 hours"),
});

const agent = await createDeepAgent({
  responseFormat: weatherReportSchema,
  tools: [internetSearch],
});

const result = await agent.invoke({
  messages: [
    {
      role: "user",
      content: "What's the weather like in San Francisco?",
    },
  ],
});

console.log(result.structuredResponse);
// {
//   location: 'San Francisco, California',
//   temperature: 18.3,
//   condition: 'Sunny',
//   humidity: 48,
//   windSpeed: 7.6,
//   forecast: 'Clear skies with temperatures remaining mild. High of 18°C (64°F) during the day, dropping to around 11°C (52°F) at night.'
// }
更多信息和示例请参阅响应格式