围绕目标构建 harness。create_deep_agent 提供 production-ready foundation:将它连接到你的 data、塑造其 behavior,并添加 use case 所需 capabilities。 createDeepAgent 默认随 pre-assembled harness 提供:filesystem、summarization、subagents 和 prompt caching。下方 parameters 可让你定义 agent persona、连接 data 和 tools,并用 additional middleware 扩展 stack。
import { createDeepAgent } from "deepagents";

const agent = await createDeepAgent({
  model: "anthropic:claude-sonnet-4-6",
  systemPrompt: "You are a helpful assistant.",
  tools: [search, fetchUrl],
  memory: ["./AGENTS.md"],
  skills: ["./skills/"],
});
Parameter作用
model要使用的 model
systemPromptAgent 的 custom instructions
toolsAgent 可调用的 domain tools
memoryStartup 时加载的 AGENTS.md files
skills用于 on-demand knowledge 的 skills directory
backendFilesystem backend(默认 StateBackend)
permissionsFilesystem 的 path-level access control
subagents用于 delegated tasks 的 custom subagents
middleware要添加到 stack 的 extra middleware
interruptOn在 tool calls 前暂停以等待 human approval
responseFormatStructured output schema
完整 parameter list 请参阅 createDeepAgent API reference。若要从头组合 fully custom harness,请参阅 Configure the harness
添加 tools、subagents 和 backends 时,请使用 LangSmith trace 各部分如何协同工作。按照 observability quickstart 完成设置,并参阅 Going to production 了解如何部署到 LangSmith。建议你同时设置 LangSmith Engine,它会监控 traces、检测 issues,并提出 fixes。

Model

传入 provider:model 格式的 model string,或 initialized model instance。所有 providers 请参阅 supported models,经过测试的 recommendations 请参阅 suggested models
使用 provider:model 格式(例如 openai:gpt-5.4)可在 models 之间快速切换。
👉 Read the OpenAI chat model integration docs
npm install @langchain/openai deepagents
import { createDeepAgent } from "deepagents";

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

const agent = createDeepAgent({ model: "gpt-5.4" });
// this calls initChatModel for the specified model with default parameters
// to use specific model parameters, use initChatModel directly
Chat models 会自动 retry transient API failures(使用 exponential backoff)。关于调优 max_retries / timeout 的 defaults、limits 和 code samples,请参阅 LangChain Models 页面。

Tools

除用于 planning、file management 和 subagent spawning 的 built-in tools 外,你还可以提供 custom tools:
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.5-flash",
  tools: [internetSearch],
});

MCP tools

Deep Agents 完全支持 Model Context Protocol (MCP) tools。你可以从任何 MCP server 加载 tools,例如 databases、APIs、file systems 等,并将它们直接传给 create_deep_agent
安装 @langchain/mcp-adapters 以连接 MCP servers:
npm install @langchain/mcp-adapters
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
import { createDeepAgent } from "deepagents";

const client = new MultiServerMCPClient({
    my_server: {
        transport: "http",
        url: "http://localhost:8000/mcp",
    },
});

const tools = await client.getTools();

const agent = await createDeepAgent({
    model: "openai:gpt-5.4",
    tools,
});

const result = await agent.invoke({
    messages: [{ role: "user", content: "Use the MCP server to help me." }],
});
有关 stdio servers、OAuth authentication、tool filtering 和 stateful sessions 的详细配置选项,请参阅完整 MCP guide

System prompt

Deep Agents 附带 built-in system prompt。Deep agent 的价值来自 SDK 在 model 之上提供的 orchestration layer,包括 planning、virtual-filesystem tools 和 subagents,而 model 需要知道这些能力存在以及何时使用它们。Built-in prompt 会教 agent 如何使用这套 scaffolding,因此你无需为每个 project 重新推导;请通过 profile 或你自己的 system_prompt= 调整它,而不是逐字复制。 当 middleware 添加 filesystem tools 等 special tools 时,它会将相关内容追加到 system prompt。 每个 deep agent 也应包含面向其 specific use case 的 custom system prompt:
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.5-flash",
  systemPrompt: researchInstructions,
});

Prompt assembly

Deep Agents 会从最多四个 named parts 构建 system prompt,让 caller-supplied instructions、SDK built-in agent guidance,以及任何 model-specific profile overrides 能以可预测 precedence 共存。如果没有这种 layering,针对 Claude 调优的 profile suffix 可能会根据 call order 覆盖你的 system_prompt= argument,或被它覆盖;named slots 让 ordering 明确且稳定。 实践中,大多数 callers 只会遇到两个 slots:USER(你的 system_prompt=)和 BASE(SDK default)。选择带 built-in profile 的 model(目前为 Anthropic 或 OpenAI)会添加 SUFFIX。完整四段式 assembly 主要在你编写 custom HarnessProfile,或 debug profile text 为什么出现在某个位置时相关。 四个 named parts 如下(每个都可能不存在):
NameSourceNotes
USERsystem_prompt= argument to create_deep_agentstr or SystemMessage; omitted when unset.
BASEThe SDK default (BASE_AGENT_PROMPT)Always present unless replaced by a profile’s CUSTOM.
CUSTOMHarnessProfile.base_system_promptReplaces BASE outright when a matching profile sets it.
SUFFIXHarnessProfile.system_prompt_suffixAppended last when a matching profile sets it.
顺序始终是 USER -> (BASE or CUSTOM) -> SUFFIX,并以空行(\n\n)连接。由此得到两个 invariants:
  1. USER 始终在最前面。 Caller text 位于任何 SDK 或 profile content 之前,因此无论选择哪个 model,persona/instructions 都优先。
  2. SUFFIX 始终在最后。 Profile suffixes 最接近 conversation history,model-tuning guidance 在这里最可靠。
Assembled shapes(✓ = field is set,- = field is unset):
system_prompt=profile base_system_prompt (CUSTOM)profile system_prompt_suffix (SUFFIX)Final assembled system prompt
None--BASE
None-BASE + SUFFIX
None-CUSTOM
NoneCUSTOM + SUFFIX
str--USER + BASE
str-USER + BASE + SUFFIX
str-USER + CUSTOM
strUSER + CUSTOM + SUFFIX
Worked example:built-in profiles(Anthropic、OpenAI)只附带 system_prompt_suffix,因此典型 call 会落在 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(而不是 string)会触发不同的 concatenation path:右侧 assembly(BASE-or-CUSTOM 加上任何 SUFFIX)会作为 additional text content block 追加到 message 现有的 content_blocks。相同 logical ordering 仍然适用(caller blocks 在前),并且 caller blocks 上的任何 cache_control markers 都会保留,这对于放置显式 Anthropic prompt-cache breakpoints 很有用。
Prompt assembly overlay rules 也适用于 declarative subagents:每个 subagent 会针对自己的 model重新运行 profile resolution,然后将 resolved profile 的 base_system_prompt / system_prompt_suffix 应用于其 authored system_prompt。Subagent 的 system_prompt 扮演 BASE 角色;CUSTOMSUFFIX 来自匹配 subagent model 的 profile(可能不同于 main agent profile)。
spec["system_prompt"]profile base_system_prompt (CUSTOM)profile system_prompt_suffix (SUFFIX)Final subagent system prompt
authored--authored
authored-authored + SUFFIX
authored-CUSTOM
authoredCUSTOM + SUFFIX
Subagents 没有 USER segment。Spec 中 authored system_prompt 是最接近的 analog,并保留在 BASE slot 中。只附带 system_prompt_suffix 的 profile(built-in Anthropic / OpenAI profiles 的常见情况)只会追加到 subagent author 写入的内容后。设置 base_system_prompt 的 profile 会直接替换 authored prompt。
Auto-added general-purpose subagent 遵循 prompt assembly overlay rules,但多一层:GP base prompt 会解析为 general_purpose_subagent.system_prompt(如果设置)-> HarnessProfile.base_system_prompt(如果设置)-> SDK general-purpose default。无论哪种情况,profile suffix 都会叠加其上。这两个 override fields 都可以携带 base-prompt replacement,但它们不可互换。general_purpose_subagent.system_prompt 是 general-purpose-specific configuration;base_system_prompt 是主要面向 main agent 的 global override。当二者都设置时,general-purpose-specific intent 会在 general-purpose subagent 上胜出,因此同时调优两个 fields 的 user 不会看到 GP override 被静默丢弃:
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.",
    ),
)
StackFinal system prompt
Main agent"You are ACME's support orchestrator." + SUFFIX
GP subagent"You are a research subagent. Cite sources." + SUFFIX
如果 general_purpose_subagent.system_prompt 未设置,GP subagent 会回退到 base_system_prompt(如果设置),最后回退到 SDK general-purpose default。

Middleware

Deep Agents 支持任何 middleware,包括下方列出的 built-in middleware、来自 LangChain 的 prebuilt middleware、provider-specific middleware,以及你自己编写的 custom middleware。 将 middleware 传给 createDeepAgentmiddleware argument。 默认情况下,Deep Agents 可以访问以下 middleware:

Default stack (main agent)

从前到后:
  1. TodoListMiddleware: Tracks and manages todo lists for organizing agent tasks and work.
  2. SkillsMiddleware: Only when you pass skills. Injected immediately after the todo middleware and before filesystem middleware so skill metadata is available before file tools run.
  3. FilesystemMiddleware: Handles file system operations such as reading, writing, and navigating directories. When you pass permissions, filesystem permissions enforcement is included here so it can evaluate every tool the agent might call.
  4. SubAgentMiddleware: Spawns and coordinates subagents for delegating tasks to specialized agents.
  5. SummarizationMiddleware: Condenses message history to stay within context limits when conversations grow long (via createSummarizationMiddleware).
  6. PatchToolCallsMiddleware: Automatic message history fixes when tool calls are interrupted or cancelled before receiving results. Runs before Anthropic prompt caching and the tail stack below.
  7. AsyncSubAgentMiddleware: Only when you configure async subagents.
  8. Your middleware argument: Optional middleware you pass as the middleware argument is appended here (after Patch, before the tail stack).
  9. Harness profile extras: Provider-specific middleware from the resolved model profile, if any. tools from the agent.
  10. AnthropicPromptCachingMiddleware: Automatically added when you are using an Anthropic mode. Runs after Patch and after your middleware so the cached prefix matches what is actually sent to the model.
  11. MemoryMiddleware: Only when you pass memory.
    MemoryMiddleware is placed after profile extras and Anthropic prompt caching so updates to injected memory are less likely to invalidate the Anthropic cache prefix. The same ordering concern is called out in the createDeepAgent implementation comments.
  12. HumanInTheLoopMiddleware: Only when you pass interruptOn. Pauses for human approval or input at configured tool calls.
  13. Excluded-tool filtering: When the harness profile lists excluded tools, middleware removes those ```

Default stack (synchronous subagents)

The built-in general-purpose subagent and each declarative synchronous SubAgent graph use a stack that createDeepAgent builds in code. It matches the main agent in broad shape (todo list, filesystem, summarization, Patch, profile extras, Anthropic caching, optional permissions) but differs in two ways:
  • Skills run after PatchToolCallsMiddleware on these inner agents (on the main agent, skills run before filesystem middleware when skills is set).
  • There is no SubAgentMiddleware inside a subagent graph (only the parent agent exposes the task tool).
When a declarative subagent sets interruptOn, that value is forwarded to createAgent for the subagent, which wires up human-in-the-loop handling for the configured tool calls.

Prebuilt middleware

LangChain 暴露 additional prebuilt middleware,可让你添加 retries、fallbacks 或 PII detection 等各种 features。更多信息请参阅 Prebuilt middleware deepagents package 也为同一 workflow 暴露 createSummarizationMiddleware。更多 details 请参阅 Summarization

Provider-specific middleware

针对特定 LLM providers 优化的 provider-specific middleware,请参阅 Official integrationsCommunity integrations

Custom middleware

你可以提供 additional middleware 来扩展 functionality、添加 tools,或实现 custom hooks:
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.5-flash",
  tools: [getWeather] as any,
  middleware: [logToolCallsMiddleware] as any,
});
初始化后不要 mutate attributes如果需要跨 hook invocations 跟踪 values(例如 counters 或 accumulated data),请使用 graph state。 Graph state 设计上作用域限定于 thread,因此并发下更新是安全的。推荐这样做:
const customMiddleware = createMiddleware({
  name: "CustomMiddleware",
  beforeAgent: async (state) => {
    return { x: (state.x ?? 0) + 1 }; // Update graph state instead
  },
});
不要这样做:
let x = 1;

const customMiddlewareBad = createMiddleware({
  name: "CustomMiddleware",
  beforeAgent: async () => {
    x += 1; // Mutation causes race conditions
  },
});
In-place mutation,例如在 beforeAgent 中修改 state.x、在 beforeAgent 中 mutate shared variable,或在 hooks 中更改其他 shared values,可能导致 subtle bugs 和 race conditions,因为许多 operations 会并发运行(subagents、parallel tools,以及不同 threads 上的 parallel invocations)。如果必须在 custom middleware 中使用 mutation,请考虑 subagents、parallel tools 或 concurrent agent invocations 同时运行时会发生什么。

Interpreters

使用 interpreters 添加在 scoped QuickJS runtime 中运行 JavaScript 的 eval tool。当 agent 需要以编程方式组合 tools、batch work、在 code 中处理 errors,或在没有完整 shell environment 的情况下 transform structured data 时,Interpreters 很有用。
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "google-genai:gemini-3.5-flash",
  middleware: [createCodeInterpreterMiddleware()],
});
有关 setup、programmatic tool calling、interpreter skills 和 limits,请参阅 Interpreters

Subagents

若要隔离 detailed work 并避免 context bloat,请使用 subagents:
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: "google-genai:gemini-3.5-flash", // Optional override, defaults to main agent model
};
const subagents = [researchSubagent];

const agent = createDeepAgent({
  model: "google_genai:gemini-3.5-flash",
  subagents,
});
更多信息请参阅 Subagents

Backends

Deep agent 的 tools 可以使用 virtual file systems 存储、访问和编辑 files。默认情况下,deep agents 使用 StateBackend 如果使用 skillsmemory,必须先将预期的 skill 或 memory files 添加到 backend,然后再创建 agent。
存储在 langgraph state 中的 thread-scoped filesystem backend。Files 会在 thread 内跨 turns 持久存在(通过 checkpointer),但不会跨 threads 共享。
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(),
});
更多信息请参阅 Backends

Sandboxes

Sandboxes 是 specialized backends,会在带有独立 filesystem 和用于 shell commands 的 execute tool 的 isolated environment 中运行 agent code。 当你希望 deep agent 写 files、安装 dependencies 并运行 commands,同时不更改 local machine 上任何内容时,请使用 sandbox backend。 创建 deep agent 时,将 sandbox backend 传给 backend 即可配置 sandboxes:
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();
}
更多信息请参阅 Sandboxes

Human-in-the-loop

某些 tool operations 可能比较敏感,需要在执行前获得 human approval。 你可以为每个 tool 配置 approval:
import { tool } from "langchain";
import { createDeepAgent } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";
import { z } from "zod";

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

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

const notifyEmail = tool(
  async ({
    to,
    subject,
    body,
  }: {
    to: string;
    subject: string;
    body: string;
  }) => {
    return `Sent email to ${to}`;
  },
  {
    name: "notify_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.5-flash",
  tools: [removeFile, fetchFile, notifyEmail],
  interruptOn: {
    remove_file: true, // Default: approve, edit, reject, respond
    fetch_file: false, // No interrupts needed
    notify_email: { allowedDecisions: ["approve", "reject"] }, // No editing
  },
  checkpointer, // Required!
});
你可以为 agents 和 subagents 配置在 tool call 时 interrupt,也可以从 tool calls 内部进行配置。 更多信息请参阅 Human-in-the-loop

Skills

你可以使用 skills 为 deep agent 提供 new capabilities 和 expertise。 Tools 通常覆盖 native file system actions 或 planning 等 lower level functionality,而 skills 可以包含如何完成 tasks 的详细 instructions、reference info,以及 templates 等其他 assets。 这些 files 只有在 agent 判断 skill 对当前 prompt 有用时才会加载。 这种 progressive disclosure 会减少 agent 在 startup 时必须考虑的 tokens 和 context 数量。 示例 skills 请参阅 Deep Agents example skills 若要向 deep agent 添加 skills,请将其作为 argument 传给 create_deep_agent
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
import { createDeepAgent, StateBackend, type FileData } from "deepagents";
import { MemorySaver } from "@langchain/langgraph";

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: "google-genai:gemini-3.1-pro-preview",
  backend,
  checkpointer, // Required !
  // 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?" }],
    files: skillsFiles,
  },
  config,
);

Memory

使用 AGENTS.md files 为 deep agent 提供 extra context。 创建 deep agent 时,可以向 memory parameter 传入一个或多个 file paths:
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.5-flash",
  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" } },
);

Structured output

Deep Agents 支持 structured output 可以在调用 createDeepAgent() 时通过 responseFormat argument 传入期望的 structured output schema。 当 model 生成 structured data 时,它会被 captured、validated,并在 agent state 的 structuredResponse key 中返回。
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

Advanced

createDeepAgent 会在 createAgent 之上预组装 middleware stack。若要构建 fully custom agent,并精确选择要包含哪些 capabilities,请参阅 Configure the harness