跳到主要内容

文档索引

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

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

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,
  responseFormat?: TResponse,
  skills?: string[],
  store?: BaseStore,
  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)以快速切换模型。
👉 阅读OpenAI 聊天模型集成文档
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

连接弹性

LangChain 聊天模型会自动以指数退避方式重试失败的 API 请求。默认情况下,对于网络错误、速率限制 (429) 和服务器错误 (5xx),模型最多重试 6 次。客户端错误(如 401(未授权)或 404)不会重试。 您可以在创建模型时调整 maxRetries 参数,以便根据您的环境微调此行为:
import { ChatAnthropic } from "@langchain/anthropic";
import { createDeepAgent } from "deepagents";

const agent = createDeepAgent({
    model: new ChatAnthropic({
        model: "claude-sonnet-4-6",
        maxRetries: 10, // Increase for unreliable networks (default: 6)
        timeout: 120_000, // Increase timeout for slow connections
    }),
});
对于不可靠网络上的长时间运行的智能体任务,请考虑将 max_retries 增加到 10–15,并将其与 checkpointer 结合使用,以便在故障发生时保留进度。

工具

除了用于规划、文件管理和子智能体生成的内置工具外,您还可以提供自定义工具
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({
  tools: [internetSearch],
});

系统提示

Deep Agents 附带内置系统提示词。Deep Agent 的价值源于 SDK 在模型之上提供的编排层——规划、虚拟文件系统工具和子智能体——模型需要知道这些工具的存在以及何时使用它们。内置提示词教会智能体如何使用这些脚手架,这样你就不必为每个项目重新推导它;请通过配置文件 (profile) 或你自己的 system_prompt= 来微调它,而不是逐字复制。 当中间件添加特殊工具(如文件系统工具)时,它会将它们附加到系统提示词中。 每个 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({
  systemPrompt: researchInstructions,
});

提示词组装

Deep Agents 从最多四个命名部分构建系统提示词,以便调用者提供的指令、SDK 的内置智能体指南以及任何特定于模型的配置文件覆盖可以具有可预测的优先级共存。如果没有这种分层,为 Claude 调整的配置文件后缀(例如)可能会根据调用顺序覆盖你的 system_prompt= 参数或被其覆盖;命名的插槽使排序变得显式且稳定。 在实践中,大多数调用者只会遇到两个插槽:USER(你的 system_prompt=)和 BASE(SDK 默认值)。选择具有内置配置文件的模型(目前是 Anthropic 或 OpenAI)会添加一个 SUFFIX。完整的四部分组装主要在您编写自定义 HarnessProfile 或调试配置文件的文本出现在何处时才相关。 四个命名部分(每个部分都可能缺失):
名称来源备注
USERcreate_deep_agentsystem_prompt= 参数strSystemMessage;未设置时省略。
BASESDK 默认值 (BASE_AGENT_PROMPT)始终存在,除非被配置文件的 CUSTOM 替换。
CUSTOMHarnessProfile.base_system_prompt当匹配的配置文件设置它时,直接替换 BASE
SUFFIXHarnessProfile.system_prompt_suffix当匹配的配置文件设置它时,最后附加。
顺序始终是 USER -> (BASECUSTOM) -> SUFFIX,由空行 (\n\n) 连接。遵循以下两个不变性:
  1. USER 始终在最前面。 调用者的文本位于任何 SDK 或配置文件内容之前,因此无论选择哪个模型,角色/指令都具有优先级。
  2. SUFFIX 始终在最后。 配置文件后缀最接近对话历史记录,这是模型微调指南最可靠落地的地方。
组装形式(✓ = 字段已设置,- = 字段未设置)
system_prompt=配置文件 base_system_prompt (CUSTOM)配置文件 system_prompt_suffix (SUFFIX)最终组装的系统提示词
--BASE
-BASE + SUFFIX
-CUSTOM
CUSTOM + SUFFIX
str--USER + BASE
str-USER + BASE + SUFFIX
str-USER + CUSTOM
strUSER + CUSTOM + SUFFIX
示例 —— 内置配置文件(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(而非字符串)会触发不同的连接路径:右侧组装(BASE-或-CUSTOM 加上任何 SUFFIX)作为额外的文本内容块附加到消息现有的 content_blocks 中。应用相同的逻辑顺序(调用者块在前),并且调用者块上的任何 cache_control 标记都会被保留 —— 这对于放置显式的 Anthropic 提示词缓存断点很有用。
同样的叠加规则也适用于声明性子智能体 —— 每个子智能体根据 其自己的模型 重新运行配置文件解析,然后将其解析出的配置文件的 base_system_prompt / system_prompt_suffix 应用于其编写的 system_prompt。子智能体的 system_prompt 扮演 BASE 角色;CUSTOMSUFFIX 来自与子智能体模型匹配的配置文件(可能与主智能体的配置文件不同)。
spec["system_prompt"]配置文件 base_system_prompt (CUSTOM)配置文件 system_prompt_suffix (SUFFIX)最终子智能体系统提示词
编写的--编写的
编写的-编写的 + SUFFIX
编写的-CUSTOM
编写的CUSTOM + SUFFIX
子智能体没有 USER 部分 —— 规范中编写的 system_prompt 是最接近的类比,并保留在 BASE 插槽中。仅包含 system_prompt_suffix 的配置文件(内置 Anthropic / OpenAI 配置文件的常见情况)只会附加到子智能体作者编写的任何内容之后;设置 base_system_prompt 的配置文件将彻底 替换 编写的提示词,因此请谨慎使用该字段。
自动添加的通用子智能体 (GP) 遵循相同的叠加规则,但多了一层:GP 基础提示词解析顺序为 general_purpose_subagent.system_prompt(如果已设置) -> HarnessProfile.base_system_prompt(如果已设置) -> SDK GP 默认值。无论哪种方式,配置文件后缀都会叠加在上面。这两个覆盖字段都可以承载基础提示词替换,但它们不可互换。general_purpose_subagent.system_prompt 是特定于 GP 的配置;base_system_prompt 是一个全局覆盖,主要针对主智能体。当两者都设置时,特定于 GP 的意图在 GP 子智能体中胜出,因此调整这两个字段的用户永远不会看到他们的 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.",
    ),
)
堆栈最终系统提示词
主智能体“你是个 ACME 的支持编排者。” + SUFFIX
GP 子智能体“你是个研究子智能体。请引用来源。” + SUFFIX
如果未设置 general_purpose_subagent.system_prompt,GP 子智能体将回退到 base_system_prompt(如果已设置),最后回退到 SDK GP 默认值。

中间件

默认情况下,Deep Agents 可以访问以下中间件 如果您正在使用记忆、技能或人类在环 (human-in-the-loop),还包含以下中间件
  • MemoryMiddleware: 提供 memory 参数时,在会话之间持久化和检索对话上下文
  • SkillsMiddleware: 提供 skills 参数时启用自定义技能
  • HumanInTheLoopMiddleware: 在提供 interruptOn 参数时,在指定点暂停以等待人工批准或输入

预构建中间件

LangChain 提供了额外的预构建中间件,允许您添加各种功能,如重试、回退或 PII 检测。有关更多信息,请参阅预构建中间件 deepagents 包还为相同的工作流程提供了 createSummarizationMiddleware。有关更多详细信息,请参阅摘要

特定提供商中间件

有关针对特定 LLM 提供商优化的提供商专用中间件,请参阅官方集成社区集成

自定义中间件

您可以提供额外的中间件来扩展功能、添加工具或实现自定义钩子 (hook)
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) => {
    // Intercept and log every tool call - demonstrates cross-cutting concern
    callCount += 1;
    const toolName = request.toolCall.name;

    console.log(`[Middleware] Tool call #${callCount}: ${toolName}`);
    console.log(
      `[Middleware] Arguments: ${JSON.stringify(request.toolCall.args)}`
    );

    // Execute the tool call
    const result = await handler(request);

    // Log the result
    console.log(`[Middleware] Tool call #${callCount} completed`);

    return result;
  },
});

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

const customMiddleware = createMiddleware({
  name: "CustomMiddleware",
  beforeAgent: async () => {
    x += 1; // Mutation causes race conditions
  },
});
就地变动(例如在 beforeAgent 中修改 state.x、在 beforeAgent 中变动共享变量或在钩子中更改其他共享值)可能会导致微妙的错误和竞态条件,因为许多操作是并发运行的(子智能体、并行工具以及不同线程上的并行调用)。有关使用自定义属性扩展状态的完整详细信息,请参阅自定义中间件 - 自定义状态模式。如果您必须在自定义中间件中使用变动,请考虑当子智能体、并行工具或并发智能体调用同时运行时会发生什么。

子代理

为了隔离详细工作并避免上下文膨胀,请使用子智能体
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,
});
有关更多信息,请参阅子智能体

后端

Deep Agent 的工具可以利用虚拟文件系统来存储、访问和编辑文件。默认情况下,Deep Agents 使用 StateBackend 如果您正在使用技能记忆,在创建智能体之前,必须将预期的技能或记忆文件添加到后端。
存储在 langgraph 状态中的临时文件系统后端。此文件系统仅 针对单个线程 持久化。
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(),
});
有关更多信息,请参阅后端

沙盒

沙箱是专门的后端,它们在具有自己文件系统和用于 shell 命令的 execute 工具的隔离环境中运行智能体代码。当您希望您的 Deep Agent 编写文件、安装依赖项并运行命令而不更改本地机器上的任何内容时,请使用沙箱后端。 您可以在创建 Deep Agent 时通过将沙箱后端传递给 backend 来配置沙箱:
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();
}
有关更多信息,请参阅沙箱

人工干预

某些工具操作可能很敏感,执行前需要人工批准。您可以为每个工具配置批准机制
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!
});
您可以为智能体和子智能体配置在工具调用时以及从工具调用内部中断。有关更多信息,请参阅人类在环 (Human-in-the-loop)

技能

您可以使用技能为您的 Deep Agent 提供新的能力和专业知识。虽然工具往往涵盖底层功能,如原生文件系统操作或规划,但技能可以包含关于如何完成任务的详细指令、参考信息和其他资产(如模板)。这些文件仅在智能体确定该技能对当前提示词有用时才会被加载。这种渐进式披露减少了智能体在启动时必须考虑的令牌数量和上下文。 有关示例技能,请参阅 Deep Agents 示例技能 要向您的 Deep Agent 添加技能,请在调用 create_deep_agent 时将它们作为参数传递:
import { createDeepAgent, type FileData } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";

const checkpointer = new MemorySaver();

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({
  checkpointer,
  // IMPORTANT: deepagents skill source paths are virtual (POSIX) paths relative to the backend root.
  skills: ["/skills/"],
});

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({
  memory: ["/AGENTS.md"],
  checkpointer: checkpointer,
});

const result = await agent.invoke(
  {
    messages: [
      {
        role: "user",
        content: "Please tell me what's in your memory files.",
      },
    ],
    // Seed the default StateBackend's in-state filesystem (virtual paths must start with "/").
    files: { "/AGENTS.md": createFileData(agentsMd) },
  },
  { configurable: { thread_id: "12345" } }
);

配置文件

Harness 配置文件 (harness profile) 封装了针对每个提供商或每个模型的调整(系统提示词后缀、工具描述覆盖、排除的工具或中间件、额外的中间件以及通用子智能体编辑),因此当选择匹配的模型时,create_deep_agent 会自动应用它们。
from deepagents import HarnessProfile, register_harness_profile

# Append a system-prompt suffix whenever gpt-5.4 is selected.
register_harness_profile(
    "openai:gpt-5.4",
    HarnessProfile(system_prompt_suffix="Respond in under 100 words."),
)
有关注册键、合并语义和插件打包,请参阅配置文件 (Profiles)。一个范围更窄的伴随 API,提供商配置文件 (provider profiles),封装了提供商的模型构建参数。

结构化输出

Deep Agents 支持结构化输出 您可以通过在调用 createDeepAgent() 时将所需的结构化输出模式作为 responseFormat 参数传递来设置它。当模型生成结构化数据时,它会被捕获、验证并返回在智能体状态的 ‘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.'
// }
有关更多信息和示例,请参阅响应格式 (response format)
© . This site is unofficial and not affiliated with LangChain, Inc.