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)可以在不同模型之间快速切换。- OpenAI
- Anthropic
- Azure
- Google Gemini
- Bedrock Converse
- Other
👉 Read the OpenAI chat model integration docs
npm install @langchain/openai deepagents
pnpm install @langchain/openai deepagents
yarn add @langchain/openai deepagents
bun add @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
import { initChatModel } from "langchain";
import { createDeepAgent } from "deepagents";
process.env.OPENAI_API_KEY = "your-api-key";
const model = await initChatModel("gpt-5.4");
const agent = createDeepAgent({
model,
temperature: 0,
});
import { ChatOpenAI } from "@langchain/openai";
import { createDeepAgent } from "deepagents";
const agent = createDeepAgent({
model: new ChatOpenAI({
model: "gpt-5.4",
apiKey: "your-api-key",
temperature: 0,
}),
});
👉 Read the Anthropic chat model integration docs
npm install @langchain/anthropic deepagents
pnpm install @langchain/anthropic deepagents
yarn add @langchain/anthropic deepagents
bun add @langchain/anthropic deepagents
import { createDeepAgent } from "deepagents";
process.env.ANTHROPIC_API_KEY = "your-api-key";
const agent = createDeepAgent({ model: "anthropic:claude-sonnet-4-6" });
// this calls initChatModel for the specified model with default parameters
// to use specific model parameters, use initChatModel directly
import { initChatModel } from "langchain";
import { createDeepAgent } from "deepagents";
process.env.ANTHROPIC_API_KEY = "your-api-key";
const model = await initChatModel("claude-sonnet-4-6");
const agent = createDeepAgent({
model,
temperature: 0,
});
import { ChatAnthropic } from "@langchain/anthropic";
import { createDeepAgent } from "deepagents";
const agent = createDeepAgent({
model: new ChatAnthropic({
model: "claude-sonnet-4-6",
apiKey: "your-api-key",
temperature: 0,
}),
});
👉 Read the Azure chat model integration docs
npm install @langchain/azure deepagents
pnpm install @langchain/azure deepagents
yarn add @langchain/azure deepagents
bun add @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" });
// this calls initChatModel for the specified model with default parameters
// to use specific model parameters, use initChatModel directly
import { initChatModel } from "langchain";
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 model = await initChatModel("azure_openai:gpt-5.4");
const agent = createDeepAgent({
model,
temperature: 0,
});
import { AzureChatOpenAI } from "@langchain/openai";
import { createDeepAgent } from "deepagents";
const agent = createDeepAgent({
model: new AzureChatOpenAI({
model: "gpt-5.4",
azureOpenAIApiKey: "your-api-key",
azureOpenAIApiEndpoint: "your-endpoint",
azureOpenAIApiVersion: "your-api-version",
temperature: 0,
}),
});
👉 Read the Google GenAI chat model integration docs
npm install @langchain/google-genai deepagents
pnpm install @langchain/google-genai deepagents
yarn add @langchain/google-genai deepagents
bun add @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" });
// this calls initChatModel for the specified model with default parameters
// to use specific model parameters, use initChatModel directly
import { initChatModel } from "langchain";
import { createDeepAgent } from "deepagents";
process.env.GOOGLE_API_KEY = "your-api-key";
const model = await initChatModel("google-genai:gemini-3.1-pro-preview");
const agent = createDeepAgent({
model,
temperature: 0,
});
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
import { createDeepAgent } from "deepagents";
const agent = createDeepAgent({
model: new ChatGoogleGenerativeAI({
model: "gemini-3.1-pro-preview",
apiKey: "your-api-key",
temperature: 0,
}),
});
👉 Read the AWS Bedrock chat model integration docs
npm install @langchain/aws deepagents
pnpm install @langchain/aws deepagents
yarn add @langchain/aws deepagents
bun add @langchain/aws deepagents
import { createDeepAgent } from "deepagents";
// Follow the steps here to configure your credentials:
// https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
const agent = createDeepAgent({ model: "bedrock:anthropic.claude-sonnet-4-6" });
// this calls initChatModel for the specified model with default parameters
// to use specific model parameters, use initChatModel directly
import { initChatModel } from "langchain";
import { createDeepAgent } from "deepagents";
// Follow the steps here to configure your credentials:
// https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
const model = await initChatModel("bedrock:anthropic.claude-sonnet-4-6");
const agent = createDeepAgent({
model,
temperature: 0,
});
import { ChatBedrockConverse } from "@langchain/aws";
import { createDeepAgent } from "deepagents";
// Follow the steps here to configure your credentials:
// https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html
const agent = createDeepAgent({
model: new ChatBedrockConverse({
model: "anthropic.claude-sonnet-4-6",
region: "us-east-2",
temperature: 0,
}),
});
Pass any supported model string, or an initialized model instance:
import { initChatModel } from "langchain";
import { createDeepAgent } from "deepagents";
const model = await initChatModel("provider:model-name");
const agent = createDeepAgent({ model });
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],
});
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: "openai:gpt-5.4",
tools: [internetSearch],
});
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: "anthropic:claude-sonnet-4-6",
tools: [internetSearch],
});
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: "openrouter:anthropic/claude-sonnet-4-6",
tools: [internetSearch],
});
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: "fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
tools: [internetSearch],
});
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: "baseten:zai-org/GLM-5",
tools: [internetSearch],
});
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: "ollama:devstral-2",
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,
});
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: "openai:gpt-5.4",
systemPrompt: researchInstructions,
});
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: "anthropic:claude-sonnet-4-6",
systemPrompt: researchInstructions,
});
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: "openrouter:anthropic/claude-sonnet-4-6",
systemPrompt: researchInstructions,
});
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: "fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
systemPrompt: researchInstructions,
});
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: "baseten:zai-org/GLM-5",
systemPrompt: researchInstructions,
});
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: "ollama:devstral-2",
systemPrompt: researchInstructions,
});
提示词组装
Deep Agents 从最多四个命名部分构建系统提示词,以便调用者提供的指令、SDK 内置的 Agent 指导以及任何模型特定的 profile 覆盖可以以可预测的优先级共存。如果没有这种分层,为 Claude 调优的 profile 后缀(例如)可能会根据调用顺序覆盖或被你的system_prompt= 参数覆盖;命名槽位使排序明确且稳定。
在实践中,大多数调用者只会遇到两个槽位:USER(你的 system_prompt=)和 BASE(SDK 默认值)。选择带有内置 profile 的模型——目前是 Anthropic 或 OpenAI——会添加一个 SUFFIX。完整的四部分组装主要在你编写自定义 HarnessProfile 或调试 profile 文本出现位置时才相关。
四个命名部分(每个都可能不存在):
| 名称 | 来源 | 说明 |
|---|---|---|
USER | create_deep_agent 的 system_prompt= 参数 | str 或 SystemMessage;未设置时省略。 |
BASE | SDK 默认值 (BASE_AGENT_PROMPT) | 始终存在,除非被 profile 的 CUSTOM 替换。 |
CUSTOM | HarnessProfile.base_system_prompt | 当匹配的 profile 设置此项时,直接替换 BASE。 |
SUFFIX | HarnessProfile.system_prompt_suffix | 当匹配的 profile 设置此项时,追加在最后。 |
USER -> (BASE 或 CUSTOM) -> SUFFIX,用空行(\n\n)连接。由此产生两个不变量:
USER始终在最前面。 调用者的文本先于任何 SDK 或 profile 内容,因此无论选择哪个模型,角色/指令都会优先。SUFFIX始终在最后。 Profile 后缀紧靠对话历史,这是模型调优指导最可靠的放置位置。
system_prompt= | profile base_system_prompt (CUSTOM) | profile system_prompt_suffix (SUFFIX) | 最终组装的系统提示词 |
|---|---|---|---|
None | - | - | BASE |
None | - | ✓ | BASE + SUFFIX |
None | ✓ | - | CUSTOM |
None | ✓ | ✓ | CUSTOM + SUFFIX |
str | - | - | USER + BASE |
str | - | ✓ | USER + BASE + SUFFIX |
str | ✓ | - | USER + CUSTOM |
str | ✓ | ✓ | USER + CUSTOM + SUFFIX |
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 Prompt 缓存断点很有用。子 Agent 提示词
子 Agent 提示词
相同的覆盖规则适用于声明式子 Agent——每个子 Agent 针对自己的模型重新运行 profile 解析,然后将解析后的 profile 的
子 Agent 没有
base_system_prompt / system_prompt_suffix 应用到其编写的 system_prompt。子 Agent 的 system_prompt 扮演 BASE 角色;CUSTOM 和 SUFFIX 来自匹配子 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 |
| authored | ✓ | ✓ | CUSTOM + SUFFIX |
USER 段——规范中编写的 system_prompt 是最接近的类似物,保留在 BASE 槽位中。仅提供 system_prompt_suffix 的 profile(内置 Anthropic / OpenAI profile 的常见情况)只是追加到子 Agent 作者编写的内容之后;设置了 base_system_prompt 的 profile 将完全替换编写的提示词,因此请谨慎使用该字段。通用子 Agent 提示词
通用子 Agent 提示词
自动添加的通用子 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_agent 的 middleware 参数。
默认情况下,Deep Agents 可以访问以下 Middleware:
TodoListMiddleware:跟踪和管理待办列表,用于组织 Agent 的任务和工作FilesystemMiddleware:处理文件系统操作,如读取、写入和导航目录SubAgentMiddleware:生成和协调子 Agent,用于将任务委托给专门的 AgentSummarizationMiddleware:当对话变长时,压缩消息历史以保持在上下文限制内AnthropicPromptCachingMiddleware:使用 Anthropic 模型时自动减少冗余 Token 处理PatchToolCallsMiddleware:当工具调用被中断或在收到结果前取消时,自动修复消息历史
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,
});
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: "openai:gpt-5.4",
tools: [getWeather] as any,
middleware: [logToolCallsMiddleware] as any,
});
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: "anthropic:claude-sonnet-4-6",
tools: [getWeather] as any,
middleware: [logToolCallsMiddleware] as any,
});
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: "openrouter:anthropic/claude-sonnet-4-6",
tools: [getWeather] as any,
middleware: [logToolCallsMiddleware] as any,
});
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: "fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
tools: [getWeather] as any,
middleware: [logToolCallsMiddleware] as any,
});
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: "baseten:zai-org/GLM-5",
tools: [getWeather] as any,
middleware: [logToolCallsMiddleware] as any,
});
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: "ollama:devstral-2",
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()],
});
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const agent = createDeepAgent({
model: "openai:gpt-5.4",
middleware: [createCodeInterpreterMiddleware()],
});
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const agent = createDeepAgent({
model: "anthropic:claude-sonnet-4-6",
middleware: [createCodeInterpreterMiddleware()],
});
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const agent = createDeepAgent({
model: "openrouter:anthropic/claude-sonnet-4-6",
middleware: [createCodeInterpreterMiddleware()],
});
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const agent = createDeepAgent({
model: "fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
middleware: [createCodeInterpreterMiddleware()],
});
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const agent = createDeepAgent({
model: "baseten:zai-org/GLM-5",
middleware: [createCodeInterpreterMiddleware()],
});
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const agent = createDeepAgent({
model: "ollama:devstral-2",
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,
});
后端
Deep Agent 的工具可以利用虚拟文件系统来存储、访问和编辑文件。默认情况下,Deep Agent 使用StateBackend。
如果你使用技能或记忆,必须在创建 Agent 之前将预期的技能或记忆文件添加到后端。
- StateBackend
- FilesystemBackend
- LocalShellBackend
- StoreBackend
- ContextHubBackend
- CompositeBackend
线程范围的文件系统后端,存储在
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(),
});
本地机器的文件系统。
此后端授予 Agent 直接的文件系统读/写访问权限。
请谨慎使用,仅在适当的环境中使用。
更多信息请参阅
FilesystemBackend。import { createDeepAgent, FilesystemBackend } from "deepagents";
const agent = createDeepAgent({
backend: new FilesystemBackend({ rootDir: ".", virtualMode: true }),
});
带有直接在主机上执行 shell 的文件系统。提供文件系统工具以及用于运行命令的
execute 工具。此后端授予 Agent 直接的文件系统读/写访问权限以及在你主机上不受限制的 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(); // Good for local dev; omit for LangSmith Deployment
const agent = createDeepAgent({
backend: new StoreBackend({
namespace: (ctx) => [ctx.runtime.context.userId],
}),
store
});
When deploying to LangSmith Deployment, omit the
store parameter. The platform automatically provisions a store for your agent.namespace 参数控制数据隔离。对于多用户部署,请始终设置 namespace factory 以按用户或租户隔离数据。LangSmith Hub 仓库中的持久文件系统存储。更多详情请参阅
ContextHubBackend。灵活的后端,你可以指定文件系统中的不同路由指向不同的后端。
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,
});
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();
}
人机协作
某些工具操作可能是敏感的,需要在执行前获得人工审批。 你可以为每个工具配置审批: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!
});
技能
你可以使用技能为你的 Deep Agent 提供新的能力和专业知识。 工具通常涵盖较低级别的功能,如原生文件系统操作或规划,而技能可以包含关于如何完成任务的详细说明、参考信息以及其他资源(如模板)。 这些文件仅在 Agent 确定该技能对当前 Prompt 有用时才会被加载。 这种渐进式披露减少了 Agent 在启动时需要考虑的 Token 和上下文数量。 有关示例技能,请参阅 Deep Agents 示例技能。 要将技能添加到你的 Deep Agent,请将它们作为参数传入create_deep_agent:
- StateBackend
- StoreBackend
- FilesystemBackend
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,
);
import { createDeepAgent, StoreBackend, type FileData } from "deepagents";
import {
InMemoryStore,
MemorySaver,
} from "@langchain/langgraph";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const checkpointer = new MemorySaver();
const store = new InMemoryStore();
const backend = new StoreBackend();
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({
model: "openai:gpt-5.4",
backend,
store: store,
checkpointer,
// IMPORTANT: deepagents skill source paths are virtual (POSIX) paths relative to the backend root.
skills: ["/skills/"],
middleware: [createCodeInterpreterMiddleware({ skillsBackend: backend })],
});
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";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
const checkpointer = new MemorySaver();
const backend = new FilesystemBackend({ rootDir: process.cwd() });
const agent = await createDeepAgent({
model: "openai:gpt-5.4",
backend,
skills: ["./examples/skills/"],
interruptOn: {
read_file: true,
write_file: true,
delete_file: true,
},
checkpointer, // Required!
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.",
},
],
},
config,
);
记忆
使用AGENTS.md 文件为你的 Deep Agent 提供额外上下文。
你可以在创建 Deep Agent 时将一个或多个文件路径传入 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({
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" } },
);
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: "openai:gpt-5.4",
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" } },
);
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: "anthropic:claude-sonnet-4-6",
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" } },
);
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: "openrouter:anthropic/claude-sonnet-4-6",
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" } },
);
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: "fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
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" } },
);
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: "baseten:zai-org/GLM-5",
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" } },
);
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: "ollama:devstral-2",
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" } },
);
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({
model: "google-genai:gemini-3.1-pro-preview",
backend: new StoreBackend(),
store: store,
checkpointer: checkpointer,
memory: ["/AGENTS.md"],
});
const result = await agent.invoke(
{
messages: [
{
role: "user",
content: "Please tell me what's in your memory files.",
},
],
},
{ 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({
model: "openai:gpt-5.4",
backend: new StoreBackend(),
store: store,
checkpointer: checkpointer,
memory: ["/AGENTS.md"],
});
const result = await agent.invoke(
{
messages: [
{
role: "user",
content: "Please tell me what's in your memory files.",
},
],
},
{ 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({
model: "anthropic:claude-sonnet-4-6",
backend: new StoreBackend(),
store: store,
checkpointer: checkpointer,
memory: ["/AGENTS.md"],
});
const result = await agent.invoke(
{
messages: [
{
role: "user",
content: "Please tell me what's in your memory files.",
},
],
},
{ 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({
model: "openrouter:anthropic/claude-sonnet-4-6",
backend: new StoreBackend(),
store: store,
checkpointer: checkpointer,
memory: ["/AGENTS.md"],
});
const result = await agent.invoke(
{
messages: [
{
role: "user",
content: "Please tell me what's in your memory files.",
},
],
},
{ 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({
model: "fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
backend: new StoreBackend(),
store: store,
checkpointer: checkpointer,
memory: ["/AGENTS.md"],
});
const result = await agent.invoke(
{
messages: [
{
role: "user",
content: "Please tell me what's in your memory files.",
},
],
},
{ 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({
model: "baseten:zai-org/GLM-5",
backend: new StoreBackend(),
store: store,
checkpointer: checkpointer,
memory: ["/AGENTS.md"],
});
const result = await agent.invoke(
{
messages: [
{
role: "user",
content: "Please tell me what's in your memory files.",
},
],
},
{ 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({
model: "ollama:devstral-2",
backend: new StoreBackend(),
store: store,
checkpointer: checkpointer,
memory: ["/AGENTS.md"],
});
const result = await agent.invoke(
{
messages: [
{
role: "user",
content: "Please tell me what's in your memory files.",
},
],
},
{ configurable: { thread_id: "12345" } },
);
import { createDeepAgent, FilesystemBackend } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
// 人机协作(human-in-the-loop)必须配置 Checkpointer
const checkpointer = new MemorySaver();
const agent = await createDeepAgent({
model: "google-genai:gemini-3.1-pro-preview",
backend: new FilesystemBackend({ rootDir: "/Users/user/{project}" }),
memory: ["./AGENTS.md", "./.deepagents/AGENTS.md"],
interruptOn: {
read_file: true,
write_file: true,
delete_file: true,
},
checkpointer, // 必需!
});
import { createDeepAgent, FilesystemBackend } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
// 人机协作(human-in-the-loop)必须配置 Checkpointer
const checkpointer = new MemorySaver();
const agent = await createDeepAgent({
model: "openai:gpt-5.4",
backend: new FilesystemBackend({ rootDir: "/Users/user/{project}" }),
memory: ["./AGENTS.md", "./.deepagents/AGENTS.md"],
interruptOn: {
read_file: true,
write_file: true,
delete_file: true,
},
checkpointer, // 必需!
});
import { createDeepAgent, FilesystemBackend } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
// 人机协作(human-in-the-loop)必须配置 Checkpointer
const checkpointer = new MemorySaver();
const agent = await createDeepAgent({
model: "anthropic:claude-sonnet-4-6",
backend: new FilesystemBackend({ rootDir: "/Users/user/{project}" }),
memory: ["./AGENTS.md", "./.deepagents/AGENTS.md"],
interruptOn: {
read_file: true,
write_file: true,
delete_file: true,
},
checkpointer, // 必需!
});
import { createDeepAgent, FilesystemBackend } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
// 人机协作(human-in-the-loop)必须配置 Checkpointer
const checkpointer = new MemorySaver();
const agent = await createDeepAgent({
model: "openrouter:anthropic/claude-sonnet-4-6",
backend: new FilesystemBackend({ rootDir: "/Users/user/{project}" }),
memory: ["./AGENTS.md", "./.deepagents/AGENTS.md"],
interruptOn: {
read_file: true,
write_file: true,
delete_file: true,
},
checkpointer, // 必需!
});
import { createDeepAgent, FilesystemBackend } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
// 人机协作(human-in-the-loop)必须配置 Checkpointer
const checkpointer = new MemorySaver();
const agent = await createDeepAgent({
model: "fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
backend: new FilesystemBackend({ rootDir: "/Users/user/{project}" }),
memory: ["./AGENTS.md", "./.deepagents/AGENTS.md"],
interruptOn: {
read_file: true,
write_file: true,
delete_file: true,
},
checkpointer, // 必需!
});
import { createDeepAgent, FilesystemBackend } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
// 人机协作(human-in-the-loop)必须配置 Checkpointer
const checkpointer = new MemorySaver();
const agent = await createDeepAgent({
model: "baseten:zai-org/GLM-5",
backend: new FilesystemBackend({ rootDir: "/Users/user/{project}" }),
memory: ["./AGENTS.md", "./.deepagents/AGENTS.md"],
interruptOn: {
read_file: true,
write_file: true,
delete_file: true,
},
checkpointer, // 必需!
});
import { createDeepAgent, FilesystemBackend } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
// 人机协作(human-in-the-loop)必须配置 Checkpointer
const checkpointer = new MemorySaver();
const agent = await createDeepAgent({
model: "ollama:devstral-2",
backend: new FilesystemBackend({ rootDir: "/Users/user/{project}" }),
memory: ["./AGENTS.md", "./.deepagents/AGENTS.md"],
interruptOn: {
read_file: true,
write_file: true,
delete_file: true,
},
checkpointer, // 必需!
});
结构化输出
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.'
// }
将这些文档连接到 Claude、VSCode 等工具,通过 MCP 获取实时答案。

