createDeepAgent 具有以下配置选项:
const agent = createDeepAgent({
model?: BaseLanguageModel | string,
tools?: TTools | StructuredTool[],
systemPrompt?: string | SystemMessage,
middleware?: TMiddleware,
subagents?: TSubagents,
responseFormat?: TResponse,
backend?: AnyBackendProtocol | ((config) => AnyBackendProtocol),
interruptOn?: Record<string, boolean | InterruptOnConfig>,
memory?: string[],
skills?: string[],
...
});
createDeepAgent API 参考。
模型
以provider:model 格式传递 model 字符串,或传递已初始化的模型实例。默认为 anthropic:claude-sonnet-4-6。请参阅支持的模型了解所有提供商,以及推荐模型了解经过测试的推荐。
使用
provider:model 格式(例如 openai:gpt-5)可以快速在模型之间切换。- OpenAI
- Anthropic
- Azure
- Google Gemini
- Bedrock Converse
- Other
👉 阅读 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" });
// 这将使用默认参数为指定模型调用 initChatModel
// 要使用特定模型参数,请直接使用 initChatModel
👉 阅读 Anthropic 聊天模型集成文档
npm install @langchain/anthropic deepagents
import { createDeepAgent } from "deepagents";
process.env.ANTHROPIC_API_KEY = "your-api-key";
const agent = createDeepAgent({ model: "anthropic:claude-sonnet-4-6" });
// 这将使用默认参数为指定模型调用 initChatModel
// 要使用特定模型参数,请直接使用 initChatModel
👉 阅读 Azure 聊天模型集成文档
npm install @langchain/azure deepagents
import { createDeepAgent } from "deepagents";
process.env.AZURE_OPENAI_API_KEY = "your-api-key";
process.env.AZURE_OPENAI_ENDPOINT = "your-endpoint";
process.env.OPENAI_API_VERSION = "your-api-version";
const agent = createDeepAgent({ model: "azure_openai:gpt-5.4" });
// 这将使用默认参数为指定模型调用 initChatModel
// 要使用特定模型参数,请直接使用 initChatModel
👉 阅读 Google GenAI 聊天模型集成文档
npm install @langchain/google-genai deepagents
import { createDeepAgent } from "deepagents";
process.env.GOOGLE_API_KEY = "your-api-key";
const agent = createDeepAgent({ model: "google-genai:gemini-3.1-pro-preview" });
// 这将使用默认参数为指定模型调用 initChatModel
// 要使用特定模型参数,请直接使用 initChatModel
👉 阅读 AWS Bedrock 聊天模型集成文档
npm install @langchain/aws deepagents
import { createDeepAgent } from "deepagents";
// 按照此处步骤配置您的凭据:
// https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
const agent = createDeepAgent({ model: "bedrock:anthropic.claude-sonnet-4-6" });
// 这将使用默认参数为指定模型调用 initChatModel
// 要使用特定模型参数,请直接使用 initChatModel
传递任何支持的模型字符串,或已初始化的模型实例:
import { initChatModel } from "langchain";
import { createDeepAgent } from "deepagents";
const model = await initChatModel("provider:model-name");
const agent = createDeepAgent({ model });
连接弹性
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, // 对于不可靠网络增加重试次数(默认:6)
timeout: 120_000, // 对于慢速连接增加超时时间
}),
});
对于在不可靠网络上运行的长时间代理任务,考虑将
max_retries 增加到 10-15,并与检查点配对,以便在失败时保留进度。工具
除了用于规划、文件管理和子代理生成的内置工具外,您还可以提供自定义工具: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: "运行网络搜索",
schema: z.object({
query: z.string().describe("搜索查询"),
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],
});
系统提示
深度代理附带内置系统提示。默认系统提示包含使用内置规划工具、文件系统工具和子代理的详细说明。 当中间件添加特殊工具(如文件系统工具)时,它们会附加到系统提示中。 每个深度代理还应包含一个针对其特定用例的自定义系统提示:import { createDeepAgent } from "deepagents";
const researchInstructions = `您是一位专家研究员。` +
`您的工作是进行彻底研究,然后` +
`撰写一份精炼的报告。`;
const agent = createDeepAgent({
systemPrompt: researchInstructions,
});
中间件
默认情况下,深度代理可以访问以下中间件:TodoListMiddleware:跟踪和管理待办事项列表,以组织代理任务和工作FilesystemMiddleware:处理文件系统操作,如读取、写入和导航目录SubAgentMiddleware:生成和协调子代理,以将任务委托给专门的代理SummarizationMiddleware:压缩消息历史记录,以在对话变长时保持在上下文限制内AnthropicPromptCachingMiddleware:使用 Anthropic 模型时自动减少冗余令牌处理PatchToolCallsMiddleware:当工具调用在接收结果之前被中断或取消时,自动修复消息历史记录
MemoryMiddleware:当提供memory参数时,跨会话持久化和检索对话上下文SkillsMiddleware:当提供skills参数时启用自定义技能HumanInTheLoopMiddleware:当提供interruptOn参数时,在指定点暂停以等待人工批准或输入
预构建中间件
LangChain 公开了额外的预构建中间件,允许您添加各种功能,例如重试、回退或 PII 检测。有关更多信息,请参阅预构建中间件。deepagents 包还公开了 createSummarizationMiddleware 用于相同的工作流程。有关详细信息,请参阅摘要。
特定于提供商的中间件
有关针对特定 LLM 提供商优化的特定于提供商的中间件,请参阅官方集成和社区集成。自定义中间件
您可以提供额外的中间件来扩展功能、添加工具或实现自定义钩子: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: "获取城市的天气。",
schema: z.object({
city: z.string(),
}),
}
);
let callCount = 0;
const logToolCallsMiddleware = createMiddleware({
name: "LogToolCallsMiddleware",
wrapToolCall: async (request, handler) => {
// 拦截并记录每个工具调用 - 演示横切关注点
callCount += 1;
const toolName = request.toolCall.name;
console.log(`[Middleware] Tool call #${callCount}: ${toolName}`);
console.log(
`[Middleware] Arguments: ${JSON.stringify(request.toolCall.args)}`
);
// 执行工具调用
const result = await handler(request);
// 记录结果
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,
});
初始化后不要修改属性如果需要在钩子调用之间跟踪值(例如计数器或累积数据),请使用图状态。
图状态按设计作用于线程,因此在并发下更新是安全的。这样做:不要这样做:原地修改,例如在
const customMiddleware = createMiddleware({
name: "CustomMiddleware",
beforeAgent: async (state) => {
return { x: (state.x ?? 0) + 1 }; // 改为更新图状态
},
});
let x = 1;
const customMiddleware = createMiddleware({
name: "CustomMiddleware",
beforeAgent: async () => {
x += 1; // 修改会导致竞态条件
},
});
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.2", // Optional override, defaults to main agent model
};
const subagents = [researchSubagent];
const agent = createDeepAgent({
model: "claude-sonnet-4-6",
subagents,
});
后端
深度代理工具可以利用虚拟文件系统来存储、访问和编辑文件。默认情况下,深度代理使用StateBackend。
如果您使用技能或记忆,则必须在创建代理之前将预期的技能或记忆文件添加到后端。
- StateBackend
- FilesystemBackend
- LocalShellBackend
- StoreBackend
- CompositeBackend
存储在
langgraph 状态中的临时文件系统后端。此文件系统仅持久化单个线程。import { createDeepAgent, StateBackend } from "deepagents";
// 默认情况下,我们提供一个 StateBackend
const agent = createDeepAgent();
// 在底层,它看起来像这样
const agent2 = createDeepAgent({
backend: new StateBackend(),
});
本地机器的文件系统。
此后端授予代理直接的文件系统读/写访问权限。
请谨慎使用,并仅在适当的环境中使用。
有关更多信息,请参阅
FilesystemBackend。import { createDeepAgent, FilesystemBackend } from "deepagents";
const agent = createDeepAgent({
backend: new FilesystemBackend({ rootDir: ".", virtualMode: true }),
});
在主机上直接执行 shell 的文件系统。提供文件系统工具以及用于运行命令的
execute 工具。此后端授予代理直接的文件系统读/写访问权限以及在主机上不受限制的 shell 执行权限。
请极其谨慎地使用,并仅在适当的环境中使用。
有关更多信息,请参阅
LocalShellBackend。import { createDeepAgent, LocalShellBackend } from "deepagents";
const backend = new LocalShellBackend({ workingDirectory: "." });
const agent = createDeepAgent({ backend });
提供长期存储的文件系统,跨线程持久化。
import { createDeepAgent, StoreBackend } from "deepagents";
import { InMemoryStore } from "@langchain/langgraph";
const store = new InMemoryStore(); // 适用于本地开发;部署到 LangSmith 时省略
const agent = createDeepAgent({
backend: new StoreBackend({
namespace: (ctx) => [ctx.runtime.context.userId],
}),
store
});
当部署到 LangSmith Deployment 时,请省略
store 参数。平台会自动为您的代理配置存储。namespace 参数控制数据隔离。对于多用户部署,请始终设置命名空间工厂以按用户或租户隔离数据。一个灵活的后端,您可以在文件系统中指定不同的路由以指向不同的后端。
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,
});
沙盒
沙盒是专门的后端,在隔离环境中运行代理代码,具有自己的文件系统和用于 shell 命令的execute 工具。
当您希望深度代理写入文件、安装依赖项并运行命令而不更改本地机器上的任何内容时,请使用沙盒后端。
您可以通过在创建深度代理时将沙盒后端传递给 backend 来配置沙盒:
import { createDeepAgent } from "deepagents";
import { ChatAnthropic } from "@langchain/anthropic";
import { DenoSandbox } from "@langchain/deno";
// 创建并初始化沙箱
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
read_file: false, // No interrupts needed
send_email: { allowedDecisions: ["approve", "reject"] }, // No editing
},
checkpointer, // Required!
});
技能
您可以使用技能为您的深度代理提供新的功能和专业知识。 虽然工具倾向于涵盖较低级别的功能(如本机文件系统操作或规划),但技能可以包含有关如何完成任务、参考信息和其他资产(如模板)的详细说明。 这些文件仅在代理确定该技能对当前提示有用时才由代理加载。 这种渐进式披露减少了代理在启动时必须考虑的令牌和上下文数量。 有关技能示例,请参阅深度代理示例技能。 要将技能添加到您的深度代理,请将它们作为参数传递给create_deep_agent:
- StateBackend
- StoreBackend
- FilesystemBackend
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,
);
import { createDeepAgent, StoreBackend, type FileData } from "deepagents";
import {
InMemoryStore,
MemorySaver,
} from "@langchain/langgraph";
const checkpointer = new MemorySaver();
const store = new InMemoryStore();
function createFileData(content: string): FileData {
const now = new Date().toISOString();
return {
content: content.split("\n"),
created_at: now,
modified_at: now,
};
}
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();
const fileData = createFileData(skillContent);
await store.put(["filesystem"], "/skills/langgraph-docs/SKILL.md", fileData);
const agent = await createDeepAgent({
backend: new StoreBackend(),
store: store,
checkpointer,
// IMPORTANT: deepagents skill source paths are virtual (POSIX) paths relative to the backend root.
skills: ["/skills/"],
});
const config = {
recursionLimit: 50,
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.",
},
],
},
config,
);
import { createDeepAgent, FilesystemBackend } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
const checkpointer = new MemorySaver();
const backend = new FilesystemBackend({ rootDir: process.cwd() });
const agent = await createDeepAgent({
backend,
skills: ["./examples/skills/"],
interruptOn: {
read_file: true,
write_file: true,
delete_file: true,
},
checkpointer, // Required!
});
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.",
},
],
},
config,
);
记忆
使用AGENTS.md 文件 为您的深度代理提供额外的上下文。
您可以在创建深度代理时将一个或多个文件路径传递给 memory 参数:
- StateBackend
- StoreBackend
- Filesystem
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: "请告诉我您的记忆文件中有什么内容。",
},
],
// 为默认 StateBackend 的内部状态文件系统播种(虚拟路径必须以 "/" 开头)。
files: { "/AGENTS.md": createFileData(agentsMd) },
},
{ configurable: { thread_id: "12345" } }
);
import { createDeepAgent, StoreBackend, type FileData } from "deepagents";
import {
InMemoryStore,
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);
function createFileData(content: string): FileData {
const now = new Date().toISOString();
return {
content,
mimeType: "text/plain",
created_at: now,
modified_at: now,
};
}
const store = new InMemoryStore();
const fileData = createFileData(agentsMd);
await store.put(["filesystem"], "/AGENTS.md", fileData);
const checkpointer = new MemorySaver();
const agent = await createDeepAgent({
backend: new StoreBackend(),
store: store,
checkpointer: checkpointer,
memory: ["/AGENTS.md"],
});
const result = await agent.invoke(
{
messages: [
{
role: "user",
content: "请告诉我您的记忆文件中有什么内容。",
},
],
},
{ configurable: { thread_id: "12345" } }
);
import { createDeepAgent, FilesystemBackend } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
// 检查点器是人机回环所必需的
const checkpointer = new MemorySaver();
const agent = await createDeepAgent({
backend: new FilesystemBackend({ rootDir: "/Users/user/{project}" }),
memory: ["./AGENTS.md", "./.deepagents/AGENTS.md"],
interruptOn: {
read_file: true,
write_file: true,
delete_file: true,
},
checkpointer, // 必需!
});
结构化输出
深度代理支持结构化输出。 您可以通过将所需结构化输出模式作为responseFormat 参数传递给 createDeepAgent() 调用来设置它。
当模型生成结构化数据时,它会被捕获、验证,并在代理状态的 ‘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: "运行网络搜索",
schema: z.object({
query: z.string().describe("搜索查询"),
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("此天气报告的位置"),
temperature: z.number().describe("当前温度(摄氏度)"),
condition: z
.string()
.describe("当前天气状况(例如,晴朗、多云、下雨)"),
humidity: z.number().describe("湿度百分比"),
windSpeed: z.number().describe("风速(公里/小时)"),
forecast: z.string().describe("未来 24 小时的简要预报"),
});
const agent = await createDeepAgent({
responseFormat: weatherReportSchema,
tools: [internetSearch],
});
const result = await agent.invoke({
messages: [
{
role: "user",
content: "旧金山的天气怎么样?",
},
],
});
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.'
// }
连接这些文档 到 Claude、VSCode 等,通过 MCP 获取实时答案。

