> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 动态子代理

> 使用解释器从代码中调度和编排 Deep Agents 子智能体

动态子智能体允许智能体从解释器代码中[分发](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/subagents.md)子智能体。与每次要求模型选择一个子智能体调用不同，智能体可以使用JavaScript循环、分支和并行批次来路由工作到配置的子智能体，并合成结果。

使用此模式适用于工作跨越多个独立单元、需要多种视角，或从递归分析中受益的场景。对于通用解释器设置，请参考[解释器](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/interpreters.md)。

> [!WARNING]
>
> 动态子智能体使用解释器运行时，该运行时处于[**beta**](https://langchain-docs-zh.mintlify.site/langchain/oss/versioning.md)。API和生命周期行为可能在版本间发生变化。

:::python

> [!NOTE]
>
> 解释器需要 `langchain-quickjs>=0.2.0` 和Python 3.11或更高版本。

:::

:::js

> [!NOTE]
>
> 解释器需要 `@langchain/quickjs`。

:::

## 快速开始

动态子智能体需要[解释器](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/interpreters.md)中间件。先安装并配置解释器。内置的[通用用途子智能体](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/subagents.md#默认子智能体)可处理基本分发无需额外配置。

:::python

```python Google theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="google_genai:gemini-3.6-flash",
    subagents=[{
        "name": "reviewer",
        "description": "Reviews code for security issues, citing lines and severity",
        "system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
    }],
    middleware=[CodeInterpreterMiddleware()],
)
```

```python OpenAI theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="openai:gpt-5.5",
    subagents=[{
        "name": "reviewer",
        "description": "Reviews code for security issues, citing lines and severity",
        "system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
    }],
    middleware=[CodeInterpreterMiddleware()],
)
```

```python Anthropic theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="anthropic:claude-sonnet-5",
    subagents=[{
        "name": "reviewer",
        "description": "Reviews code for security issues, citing lines and severity",
        "system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
    }],
    middleware=[CodeInterpreterMiddleware()],
)
```

```python OpenRouter theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="openrouter:z-ai/glm-5.2",
    subagents=[{
        "name": "reviewer",
        "description": "Reviews code for security issues, citing lines and severity",
        "system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
    }],
    middleware=[CodeInterpreterMiddleware()],
)
```

```python Fireworks theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="fireworks:accounts/fireworks/models/glm-5p2",
    subagents=[{
        "name": "reviewer",
        "description": "Reviews code for security issues, citing lines and severity",
        "system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
    }],
    middleware=[CodeInterpreterMiddleware()],
)
```

```python Baseten theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="baseten:zai-org/GLM-5.2",
    subagents=[{
        "name": "reviewer",
        "description": "Reviews code for security issues, citing lines and severity",
        "system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
    }],
    middleware=[CodeInterpreterMiddleware()],
)
```

```python Ollama theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="ollama:north-mini-code-1.0",
    subagents=[{
        "name": "reviewer",
        "description": "Reviews code for security issues, citing lines and severity",
        "system_prompt": "You are a security-focused code reviewer. Report issues with line numbers and severity.",
    }],
    middleware=[CodeInterpreterMiddleware()],
)
```

:::

:::js

```ts Google theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "google:gemini-3.6-flash",
  subagents: [{
    name: "reviewer",
    description: "Reviews code for security issues, citing lines and severity",
    systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
  }],
  middleware: [createCodeInterpreterMiddleware()],
});
```

```ts OpenAI theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "openai:gpt-5.5",
  subagents: [{
    name: "reviewer",
    description: "Reviews code for security issues, citing lines and severity",
    systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
  }],
  middleware: [createCodeInterpreterMiddleware()],
});
```

```ts Anthropic theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "anthropic:claude-sonnet-5",
  subagents: [{
    name: "reviewer",
    description: "Reviews code for security issues, citing lines and severity",
    systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
  }],
  middleware: [createCodeInterpreterMiddleware()],
});
```

```ts OpenRouter theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "openrouter:z-ai/glm-5.2",
  subagents: [{
    name: "reviewer",
    description: "Reviews code for security issues, citing lines and severity",
    systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
  }],
  middleware: [createCodeInterpreterMiddleware()],
});
```

```ts Fireworks theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "fireworks:accounts/fireworks/models/glm-5p2",
  subagents: [{
    name: "reviewer",
    description: "Reviews code for security issues, citing lines and severity",
    systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
  }],
  middleware: [createCodeInterpreterMiddleware()],
});
```

```ts Baseten theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "baseten:zai-org/GLM-5.2",
  subagents: [{
    name: "reviewer",
    description: "Reviews code for security issues, citing lines and severity",
    systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
  }],
  middleware: [createCodeInterpreterMiddleware()],
});
```

```ts Ollama theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "ollama:north-mini-code-1.0",
  subagents: [{
    name: "reviewer",
    description: "Reviews code for security issues, citing lines and severity",
    systemPrompt: "You are a security-focused code reviewer. Report issues with line numbers and severity.",
  }],
  middleware: [createCodeInterpreterMiddleware()],
});
```

:::

安装步骤和解释器配置请参考[解释器](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/interpreters.md#快速入门)。

对于专业场景，[配置自定义](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/subagents.md)子智能体，并为它们指定名称、描述和系统提示词。子智能体的名称和描述将作为信息供智能体评估其应承担的角色。

要触发动态子智能体，向智能体输入单词"workflow"：

:::python

```python theme={null}
result = agent.invoke({
    "messages": [{"role": "user", "content": "Run a workflow that reviews every file in src/routes/ and summarizes the top risks."}]
})
```

:::

:::js

```ts theme={null}
const result = await agent.invoke({
  messages: [{ role: "user", content: "Run a workflow that reviews every file in src/routes/ and summarizes the top risks." }],
});
```

:::

> [!TIP]
>
> **"workflow"是一个实用触发词。** 解析器系统提示词将"workflow"视为组织工作的信号，通过解析器从代码中`task()`调度子智能体，而非逐项执行模型选择的工具调用。将请求表述为"workflow"是主动调用动态编排机制的手柄。对于单次直接委派，建议直接表述请求。

> [!NOTE]
>
> 使用动态子智能体`dcode`，LangChain终端编码智能体`dcode`内置了代码解析器，因此动态子智能体可即插即用。请参考[dcode子智能体页面](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/code/subagents.md)查看配置和使用细节。

## 工作原理

[当智能体包含](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/subagents.md)子智能体和解析器中间件时，解析器会暴露内置的`task()`全局变量用于从代码中调度子智能体。处理跨多个独立单元的任务（如遍历目录中的所有文件、分批处理工单）会形成循环，将工作均匀分布以实现确定性执行，而非逐次执行模型选择的工具调用。

子智能体编排还支持递归语言模型（RLM）工作流，该方案详见[递归语言模型论文](https://arxiv.org/abs/2512.24601)：保持工作集在解析器变量中，选择切片，通过`task()`调用子智能体，并合成结果。

许多编排工作流结合动态子智能体与[程序化工具调用（PTC）](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/interpreters.md#程序化工具调用-ptc)：使用`tools.*`从解析器代码中获取输入或过滤输入，再通过`task()`调度子智能体。PTC默认关闭；需在解析器中间件中显式启用白名单。

`task()`是子智能体执行的桥梁能力，类似PTC对工具的作用。关于隔离默认值、审批边界和中间件选项，请参考[安全](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/interpreters.md#安全)和[配置](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/interpreters.md#配置)。

:::python

> [!NOTE]
>
> 多轮编排可以在使用 `mode="thread"`（默认值）时持久化解释器变量。请参阅[解释器](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/interpreters.md#持久化)页面中的持久化说明。

:::

`task()` 接受以下输入：

* `description`: 子智能体的提示词
* `subagentType`: 要运行的配置子智能体
* `responseSchema`（可选）：结构化输出

一个 `task()` 会运行完整的智能体循环，并解析为子智能体的结果：

```ts theme={null}
const review = await task({
  description: "Review src/auth/login.ts for auth issues. Cite line numbers.",
  subagentType: "reviewer",
  responseSchema: {
    type: "object",
    properties: {
      issues: { type: "array", items: { type: "object", properties: {
        file: { type: "string" }, line: { type: "number" },
        severity: { type: "string" }, description: { type: "string" },
      }}},
    },
  },
});

// With responseSchema, the result is already a typed value, so no JSON.parse is needed.
const critical = review.issues.filter((issue) => issue.severity === "high");
```

当传递 `responseSchema` 时，解析值已经是类型化的JavaScript对象；只有当子智能体有意返回JSON字符串时才调用 `JSON.parse`。

## 模式

智能体根据任务的形态选择策略；这些策略源于解释器代码的编写方式，而非配置，而可用的子智能体决定了它能实现的功能。所有模式都采用相同的编排方式：在JavaScript变量中暂存工作，通过 `task()` 分发子智能体，并在代码中合并结果。下方图表展示了常见形态，每个形态都配有可运行的示例。

### 分类与执行

首先对项目进行分类，然后根据分类结果为每个项目分配专精的子智能体处理。这适用于需要不同处理方式的混合输入场景。

```mermaid theme={null}
graph LR
    Task[Task] --> Classify{Classifier}
    Classify --> |bug| A[Agent A]
    Classify --> |feature| B[Agent B]
    Classify --> |question| C[Agent C]
```

**应用场景：** 支持工单分诊、错误日志分析、用户反馈处理，或任何需按类型差异化处理的批次项目。

> [accordion] Example: classify and act
>
> **需配置的内容**
>
> :::python
>
> ```python Google theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="google_genai:gemini-3.6-flash",
>     subagents=[
>         {
>             "name": "bug-fixer",
>             "description": "Investigates bug reports and provides reproduction steps",
>             "system_prompt": "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>         },
>         {
>             "name": "feature-analyst",
>             "description": "Evaluates feature requests for feasibility and effort",
>             "system_prompt": "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>         },
>         {
>             "name": "support-agent",
>             "description": "Answers user questions based on documentation",
>             "system_prompt": "You are a support specialist. Answer user questions clearly based on the available documentation.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python OpenAI theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="openai:gpt-5.5",
>     subagents=[
>         {
>             "name": "bug-fixer",
>             "description": "Investigates bug reports and provides reproduction steps",
>             "system_prompt": "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>         },
>         {
>             "name": "feature-analyst",
>             "description": "Evaluates feature requests for feasibility and effort",
>             "system_prompt": "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>         },
>         {
>             "name": "support-agent",
>             "description": "Answers user questions based on documentation",
>             "system_prompt": "You are a support specialist. Answer user questions clearly based on the available documentation.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Anthropic theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="anthropic:claude-sonnet-5",
>     subagents=[
>         {
>             "name": "bug-fixer",
>             "description": "Investigates bug reports and provides reproduction steps",
>             "system_prompt": "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>         },
>         {
>             "name": "feature-analyst",
>             "description": "Evaluates feature requests for feasibility and effort",
>             "system_prompt": "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>         },
>         {
>             "name": "support-agent",
>             "description": "Answers user questions based on documentation",
>             "system_prompt": "You are a support specialist. Answer user questions clearly based on the available documentation.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python OpenRouter theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="openrouter:z-ai/glm-5.2",
>     subagents=[
>         {
>             "name": "bug-fixer",
>             "description": "Investigates bug reports and provides reproduction steps",
>             "system_prompt": "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>         },
>         {
>             "name": "feature-analyst",
>             "description": "Evaluates feature requests for feasibility and effort",
>             "system_prompt": "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>         },
>         {
>             "name": "support-agent",
>             "description": "Answers user questions based on documentation",
>             "system_prompt": "You are a support specialist. Answer user questions clearly based on the available documentation.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Fireworks theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="fireworks:accounts/fireworks/models/glm-5p2",
>     subagents=[
>         {
>             "name": "bug-fixer",
>             "description": "Investigates bug reports and provides reproduction steps",
>             "system_prompt": "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>         },
>         {
>             "name": "feature-analyst",
>             "description": "Evaluates feature requests for feasibility and effort",
>             "system_prompt": "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>         },
>         {
>             "name": "support-agent",
>             "description": "Answers user questions based on documentation",
>             "system_prompt": "You are a support specialist. Answer user questions clearly based on the available documentation.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Baseten theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="baseten:zai-org/GLM-5.2",
>     subagents=[
>         {
>             "name": "bug-fixer",
>             "description": "Investigates bug reports and provides reproduction steps",
>             "system_prompt": "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>         },
>         {
>             "name": "feature-analyst",
>             "description": "Evaluates feature requests for feasibility and effort",
>             "system_prompt": "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>         },
>         {
>             "name": "support-agent",
>             "description": "Answers user questions based on documentation",
>             "system_prompt": "You are a support specialist. Answer user questions clearly based on the available documentation.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Ollama theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="ollama:north-mini-code-1.0",
>     subagents=[
>         {
>             "name": "bug-fixer",
>             "description": "Investigates bug reports and provides reproduction steps",
>             "system_prompt": "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>         },
>         {
>             "name": "feature-analyst",
>             "description": "Evaluates feature requests for feasibility and effort",
>             "system_prompt": "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>         },
>         {
>             "name": "support-agent",
>             "description": "Answers user questions based on documentation",
>             "system_prompt": "You are a support specialist. Answer user questions clearly based on the available documentation.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> :::
>
> :::js
>
> ```ts Google theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "google:gemini-3.6-flash",
>   subagents: [
>     {
>       name: "bug-fixer",
>       description: "Investigates bug reports and provides reproduction steps",
>       systemPrompt: "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>     },
>     {
>       name: "feature-analyst",
>       description: "Evaluates feature requests for feasibility and effort",
>       systemPrompt: "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>     },
>     {
>       name: "support-agent",
>       description: "Answers user questions based on documentation",
>       systemPrompt: "You are a support specialist. Answer user questions clearly based on the available documentation.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts OpenAI theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "openai:gpt-5.5",
>   subagents: [
>     {
>       name: "bug-fixer",
>       description: "Investigates bug reports and provides reproduction steps",
>       systemPrompt: "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>     },
>     {
>       name: "feature-analyst",
>       description: "Evaluates feature requests for feasibility and effort",
>       systemPrompt: "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>     },
>     {
>       name: "support-agent",
>       description: "Answers user questions based on documentation",
>       systemPrompt: "You are a support specialist. Answer user questions clearly based on the available documentation.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Anthropic theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "anthropic:claude-sonnet-5",
>   subagents: [
>     {
>       name: "bug-fixer",
>       description: "Investigates bug reports and provides reproduction steps",
>       systemPrompt: "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>     },
>     {
>       name: "feature-analyst",
>       description: "Evaluates feature requests for feasibility and effort",
>       systemPrompt: "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>     },
>     {
>       name: "support-agent",
>       description: "Answers user questions based on documentation",
>       systemPrompt: "You are a support specialist. Answer user questions clearly based on the available documentation.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts OpenRouter theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "openrouter:z-ai/glm-5.2",
>   subagents: [
>     {
>       name: "bug-fixer",
>       description: "Investigates bug reports and provides reproduction steps",
>       systemPrompt: "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>     },
>     {
>       name: "feature-analyst",
>       description: "Evaluates feature requests for feasibility and effort",
>       systemPrompt: "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>     },
>     {
>       name: "support-agent",
>       description: "Answers user questions based on documentation",
>       systemPrompt: "You are a support specialist. Answer user questions clearly based on the available documentation.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Fireworks theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "fireworks:accounts/fireworks/models/glm-5p2",
>   subagents: [
>     {
>       name: "bug-fixer",
>       description: "Investigates bug reports and provides reproduction steps",
>       systemPrompt: "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>     },
>     {
>       name: "feature-analyst",
>       description: "Evaluates feature requests for feasibility and effort",
>       systemPrompt: "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>     },
>     {
>       name: "support-agent",
>       description: "Answers user questions based on documentation",
>       systemPrompt: "You are a support specialist. Answer user questions clearly based on the available documentation.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Baseten theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "baseten:zai-org/GLM-5.2",
>   subagents: [
>     {
>       name: "bug-fixer",
>       description: "Investigates bug reports and provides reproduction steps",
>       systemPrompt: "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>     },
>     {
>       name: "feature-analyst",
>       description: "Evaluates feature requests for feasibility and effort",
>       systemPrompt: "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>     },
>     {
>       name: "support-agent",
>       description: "Answers user questions based on documentation",
>       systemPrompt: "You are a support specialist. Answer user questions clearly based on the available documentation.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Ollama theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "ollama:north-mini-code-1.0",
>   subagents: [
>     {
>       name: "bug-fixer",
>       description: "Investigates bug reports and provides reproduction steps",
>       systemPrompt: "You are a bug triage specialist. Investigate each bug report and provide clear reproduction steps.",
>     },
>     {
>       name: "feature-analyst",
>       description: "Evaluates feature requests for feasibility and effort",
>       systemPrompt: "You are a product analyst. Evaluate each feature request for technical feasibility, estimated effort, and potential impact.",
>     },
>     {
>       name: "support-agent",
>       description: "Answers user questions based on documentation",
>       systemPrompt: "You are a support specialist. Answer user questions clearly based on the available documentation.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> :::
>
> **智能体生成的代码**
>
> ```ts theme={null}
> // The agent has already classified each ticket; this routes every item to
> // the right specialist and collects the handled results.
> const SPECIALIST = { bug: "bug-fixer", feature: "feature-analyst", question: "support-agent" };
>
> const handled = await Promise.all(
>   tickets.map((ticket) =>
>     task({
>       description: `Handle this ${ticket.category}:\n${ticket.text}`,
>       subagentType: SPECIALIST[ticket.category],
>     }),
>   ),
> );
> // ... group handled results by category into a single triage report
> handled;
> ```

### 并行分发与聚合

智能体对多个项目并行分发相同类型的工作，并在完成后聚合结果。

```mermaid theme={null}
graph LR
    Items[Items] --> W1[Worker]
    Items --> W2[Worker]
    Items --> W3[Worker]
    W1 --> Collect[Collect]
    W2 --> Collect
    W3 --> Collect
    Collect --> Synth[Synthesize]
```

**应用场景：** 跨目录代码审查、批量文档分析、日志文件处理、对多个服务执行相同检查。

从解释器代码中获取文件需启用[程序化工具调用（PTC）](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/interpreters.md#程序化工具调用-ptc)。在解释器中间件中为PTC设置允许列表 `glob`。

> [accordion] Example: fan-out and synthesize
>
> **需配置的内容**
>
> :::python
>
> ```python Google theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="google_genai:gemini-3.6-flash",
>     subagents=[{
>         "name": "reviewer",
>         "description": "Reviews code for security issues, citing lines and severity",
>         "system_prompt": "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>     }],
>     middleware=[CodeInterpreterMiddleware(ptc=["glob"])],
> )
> ```
>
> ```python OpenAI theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="openai:gpt-5.5",
>     subagents=[{
>         "name": "reviewer",
>         "description": "Reviews code for security issues, citing lines and severity",
>         "system_prompt": "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>     }],
>     middleware=[CodeInterpreterMiddleware(ptc=["glob"])],
> )
> ```
>
> ```python Anthropic theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="anthropic:claude-sonnet-5",
>     subagents=[{
>         "name": "reviewer",
>         "description": "Reviews code for security issues, citing lines and severity",
>         "system_prompt": "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>     }],
>     middleware=[CodeInterpreterMiddleware(ptc=["glob"])],
> )
> ```
>
> ```python OpenRouter theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="openrouter:z-ai/glm-5.2",
>     subagents=[{
>         "name": "reviewer",
>         "description": "Reviews code for security issues, citing lines and severity",
>         "system_prompt": "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>     }],
>     middleware=[CodeInterpreterMiddleware(ptc=["glob"])],
> )
> ```
>
> ```python Fireworks theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="fireworks:accounts/fireworks/models/glm-5p2",
>     subagents=[{
>         "name": "reviewer",
>         "description": "Reviews code for security issues, citing lines and severity",
>         "system_prompt": "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>     }],
>     middleware=[CodeInterpreterMiddleware(ptc=["glob"])],
> )
> ```
>
> ```python Baseten theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="baseten:zai-org/GLM-5.2",
>     subagents=[{
>         "name": "reviewer",
>         "description": "Reviews code for security issues, citing lines and severity",
>         "system_prompt": "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>     }],
>     middleware=[CodeInterpreterMiddleware(ptc=["glob"])],
> )
> ```
>
> ```python Ollama theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="ollama:north-mini-code-1.0",
>     subagents=[{
>         "name": "reviewer",
>         "description": "Reviews code for security issues, citing lines and severity",
>         "system_prompt": "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>     }],
>     middleware=[CodeInterpreterMiddleware(ptc=["glob"])],
> )
> ```
>
> :::
>
> :::js
>
> ```ts Google theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "google:gemini-3.6-flash",
>   subagents: [{
>     name: "reviewer",
>     description: "Reviews code for security issues, citing lines and severity",
>     systemPrompt: "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>   }],
>   middleware: [createCodeInterpreterMiddleware({ ptc: ["glob"] })],
> });
> ```
>
> ```ts OpenAI theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "openai:gpt-5.5",
>   subagents: [{
>     name: "reviewer",
>     description: "Reviews code for security issues, citing lines and severity",
>     systemPrompt: "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>   }],
>   middleware: [createCodeInterpreterMiddleware({ ptc: ["glob"] })],
> });
> ```
>
> ```ts Anthropic theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "anthropic:claude-sonnet-5",
>   subagents: [{
>     name: "reviewer",
>     description: "Reviews code for security issues, citing lines and severity",
>     systemPrompt: "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>   }],
>   middleware: [createCodeInterpreterMiddleware({ ptc: ["glob"] })],
> });
> ```
>
> ```ts OpenRouter theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "openrouter:z-ai/glm-5.2",
>   subagents: [{
>     name: "reviewer",
>     description: "Reviews code for security issues, citing lines and severity",
>     systemPrompt: "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>   }],
>   middleware: [createCodeInterpreterMiddleware({ ptc: ["glob"] })],
> });
> ```
>
> ```ts Fireworks theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "fireworks:accounts/fireworks/models/glm-5p2",
>   subagents: [{
>     name: "reviewer",
>     description: "Reviews code for security issues, citing lines and severity",
>     systemPrompt: "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>   }],
>   middleware: [createCodeInterpreterMiddleware({ ptc: ["glob"] })],
> });
> ```
>
> ```ts Baseten theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "baseten:zai-org/GLM-5.2",
>   subagents: [{
>     name: "reviewer",
>     description: "Reviews code for security issues, citing lines and severity",
>     systemPrompt: "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>   }],
>   middleware: [createCodeInterpreterMiddleware({ ptc: ["glob"] })],
> });
> ```
>
> ```ts Ollama theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "ollama:north-mini-code-1.0",
>   subagents: [{
>     name: "reviewer",
>     description: "Reviews code for security issues, citing lines and severity",
>     systemPrompt: "You are a security-focused code reviewer. Read the file carefully and report any authentication or authorization issues with line numbers and severity.",
>   }],
>   middleware: [createCodeInterpreterMiddleware({ ptc: ["glob"] })],
> });
> ```
>
> :::
>
> **智能体生成的代码**
>
> ```ts theme={null}
> // One reviewer per file, dispatched in parallel, then findings merged.
> const files = (await tools.glob({ pattern: "src/routes/**/*.ts" }))
>   .split("\n")
>   .filter(Boolean);
>
> const reviews = await Promise.all(
>   files.map((file) =>
>     task({
>       description: `Review ${file} for authentication issues. Cite line numbers.`,
>       subagentType: "reviewer",
>       responseSchema: issuesSchema, // -> { issues: [{ file, line, severity }] }
>     }),
>   ),
> );
>
> const issues = reviews.flatMap((r) => r.issues);
> // ... sort by severity, drop duplicates, summarize the top risks
> issues;
> ```

### 对抗性验证

两阶段模式。第一阶段生成检测项，第二阶段将每个检测项发送给独立验证者，仅通过一致性验证的项被保留。当置信度比速度更重要时，此模式可减少误报。

```mermaid theme={null}
graph LR
    Items[Items] --> Workers[Workers]
    Workers --> Findings[Findings]
    Findings --> V1[Verifier]
    Findings --> V2[Verifier]
    Findings --> V3[Verifier]
    V1 --> Vote[Majority vote]
    V2 --> Vote
    V3 --> Vote
    Vote --> Confirmed[Confirmed]
```

**应用场景：** 安全审计（误报成本高）、合规检查、需高置信度的审查场景。

> [accordion] Example: adversarial verification
>
> **需配置的内容**
>
> :::python
>
> ```python Google theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="google_genai:gemini-3.6-flash",
>     subagents=[
>         {
>             "name": "reviewer",
>             "description": "Finds potential security vulnerabilities in code",
>             "system_prompt": "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>         },
>         {
>             "name": "verifier",
>             "description": "Independently verifies whether a reported vulnerability is real",
>             "system_prompt": "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python OpenAI theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="openai:gpt-5.5",
>     subagents=[
>         {
>             "name": "reviewer",
>             "description": "Finds potential security vulnerabilities in code",
>             "system_prompt": "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>         },
>         {
>             "name": "verifier",
>             "description": "Independently verifies whether a reported vulnerability is real",
>             "system_prompt": "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Anthropic theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="anthropic:claude-sonnet-5",
>     subagents=[
>         {
>             "name": "reviewer",
>             "description": "Finds potential security vulnerabilities in code",
>             "system_prompt": "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>         },
>         {
>             "name": "verifier",
>             "description": "Independently verifies whether a reported vulnerability is real",
>             "system_prompt": "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python OpenRouter theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="openrouter:z-ai/glm-5.2",
>     subagents=[
>         {
>             "name": "reviewer",
>             "description": "Finds potential security vulnerabilities in code",
>             "system_prompt": "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>         },
>         {
>             "name": "verifier",
>             "description": "Independently verifies whether a reported vulnerability is real",
>             "system_prompt": "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Fireworks theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="fireworks:accounts/fireworks/models/glm-5p2",
>     subagents=[
>         {
>             "name": "reviewer",
>             "description": "Finds potential security vulnerabilities in code",
>             "system_prompt": "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>         },
>         {
>             "name": "verifier",
>             "description": "Independently verifies whether a reported vulnerability is real",
>             "system_prompt": "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Baseten theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="baseten:zai-org/GLM-5.2",
>     subagents=[
>         {
>             "name": "reviewer",
>             "description": "Finds potential security vulnerabilities in code",
>             "system_prompt": "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>         },
>         {
>             "name": "verifier",
>             "description": "Independently verifies whether a reported vulnerability is real",
>             "system_prompt": "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Ollama theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="ollama:north-mini-code-1.0",
>     subagents=[
>         {
>             "name": "reviewer",
>             "description": "Finds potential security vulnerabilities in code",
>             "system_prompt": "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>         },
>         {
>             "name": "verifier",
>             "description": "Independently verifies whether a reported vulnerability is real",
>             "system_prompt": "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> :::
>
> :::js
>
> ```ts Google theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "google:gemini-3.6-flash",
>   subagents: [
>     {
>       name: "reviewer",
>       description: "Finds potential security vulnerabilities in code",
>       systemPrompt: "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>     },
>     {
>       name: "verifier",
>       description: "Independently verifies whether a reported vulnerability is real",
>       systemPrompt: "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts OpenAI theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "openai:gpt-5.5",
>   subagents: [
>     {
>       name: "reviewer",
>       description: "Finds potential security vulnerabilities in code",
>       systemPrompt: "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>     },
>     {
>       name: "verifier",
>       description: "Independently verifies whether a reported vulnerability is real",
>       systemPrompt: "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Anthropic theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "anthropic:claude-sonnet-5",
>   subagents: [
>     {
>       name: "reviewer",
>       description: "Finds potential security vulnerabilities in code",
>       systemPrompt: "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>     },
>     {
>       name: "verifier",
>       description: "Independently verifies whether a reported vulnerability is real",
>       systemPrompt: "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts OpenRouter theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "openrouter:z-ai/glm-5.2",
>   subagents: [
>     {
>       name: "reviewer",
>       description: "Finds potential security vulnerabilities in code",
>       systemPrompt: "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>     },
>     {
>       name: "verifier",
>       description: "Independently verifies whether a reported vulnerability is real",
>       systemPrompt: "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Fireworks theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "fireworks:accounts/fireworks/models/glm-5p2",
>   subagents: [
>     {
>       name: "reviewer",
>       description: "Finds potential security vulnerabilities in code",
>       systemPrompt: "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>     },
>     {
>       name: "verifier",
>       description: "Independently verifies whether a reported vulnerability is real",
>       systemPrompt: "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Baseten theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "baseten:zai-org/GLM-5.2",
>   subagents: [
>     {
>       name: "reviewer",
>       description: "Finds potential security vulnerabilities in code",
>       systemPrompt: "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>     },
>     {
>       name: "verifier",
>       description: "Independently verifies whether a reported vulnerability is real",
>       systemPrompt: "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Ollama theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "ollama:north-mini-code-1.0",
>   subagents: [
>     {
>       name: "reviewer",
>       description: "Finds potential security vulnerabilities in code",
>       systemPrompt: "You are a security auditor. Find potential vulnerabilities and report each with file, line, and description.",
>     },
>     {
>       name: "verifier",
>       description: "Independently verifies whether a reported vulnerability is real",
>       systemPrompt: "You are a security verification specialist. Given a reported vulnerability, independently verify whether it is exploitable. Be skeptical. Only confirm real issues.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> :::
>
> **智能体生成的代码**
>
> ```ts theme={null}
> // Pass 1: audit. Pass 2: verify each finding independently; keep only confirmed.
> const { findings } = await task({
>   description: "Audit the payments module for vulnerabilities.",
>   subagentType: "reviewer",
>   responseSchema: findingsSchema, // -> { findings: [{ id, file, line, description }] }
> });
>
> const verdicts = await Promise.all(
>   findings.map((f) =>
>     task({
>       description: `Verify ${f.file}:${f.line} (${f.description}). Confirm or refute.`,
>       subagentType: "verifier",
>       responseSchema: verdictSchema, // -> { confirmed: boolean }
>     }),
>   ),
> );
>
> const confirmed = findings.filter((_, i) => verdicts[i]?.confirmed);
> // ... report only the confirmed vulnerabilities
> confirmed;
> ```

### 生成与筛选

多个子智能体独立生成同一问题的解决方案，智能体通过代码进行对比、评分和筛选，仅保留最佳结果。

```mermaid theme={null}
graph LR
    Prompt[Prompt] --> G1[Generator]
    Prompt --> G2[Generator]
    Prompt --> G3[Generator]
    G1 --> Filter[Filter + rank]
    G2 --> Filter
    G3 --> Filter
    Filter --> Best[Best result]
```

**应用场景：** 架构提案、重构策略、内容变体生成、需多方案探索后再决策的任务。

> [accordion] Example: generate and filter
>
> **需配置的内容**
>
> :::python
>
> ```python Google theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="google_genai:gemini-3.6-flash",
>     subagents=[{
>         "name": "architect",
>         "description": "Proposes a database schema design with tradeoff analysis",
>         "system_prompt": "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python OpenAI theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="openai:gpt-5.5",
>     subagents=[{
>         "name": "architect",
>         "description": "Proposes a database schema design with tradeoff analysis",
>         "system_prompt": "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Anthropic theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="anthropic:claude-sonnet-5",
>     subagents=[{
>         "name": "architect",
>         "description": "Proposes a database schema design with tradeoff analysis",
>         "system_prompt": "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python OpenRouter theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="openrouter:z-ai/glm-5.2",
>     subagents=[{
>         "name": "architect",
>         "description": "Proposes a database schema design with tradeoff analysis",
>         "system_prompt": "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Fireworks theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="fireworks:accounts/fireworks/models/glm-5p2",
>     subagents=[{
>         "name": "architect",
>         "description": "Proposes a database schema design with tradeoff analysis",
>         "system_prompt": "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Baseten theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="baseten:zai-org/GLM-5.2",
>     subagents=[{
>         "name": "architect",
>         "description": "Proposes a database schema design with tradeoff analysis",
>         "system_prompt": "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Ollama theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="ollama:north-mini-code-1.0",
>     subagents=[{
>         "name": "architect",
>         "description": "Proposes a database schema design with tradeoff analysis",
>         "system_prompt": "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> :::
>
> :::js
>
> ```ts Google theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "google:gemini-3.6-flash",
>   subagents: [{
>     name: "architect",
>     description: "Proposes a database schema design with tradeoff analysis",
>     systemPrompt: "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts OpenAI theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "openai:gpt-5.5",
>   subagents: [{
>     name: "architect",
>     description: "Proposes a database schema design with tradeoff analysis",
>     systemPrompt: "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Anthropic theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "anthropic:claude-sonnet-5",
>   subagents: [{
>     name: "architect",
>     description: "Proposes a database schema design with tradeoff analysis",
>     systemPrompt: "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts OpenRouter theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "openrouter:z-ai/glm-5.2",
>   subagents: [{
>     name: "architect",
>     description: "Proposes a database schema design with tradeoff analysis",
>     systemPrompt: "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Fireworks theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "fireworks:accounts/fireworks/models/glm-5p2",
>   subagents: [{
>     name: "architect",
>     description: "Proposes a database schema design with tradeoff analysis",
>     systemPrompt: "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Baseten theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "baseten:zai-org/GLM-5.2",
>   subagents: [{
>     name: "architect",
>     description: "Proposes a database schema design with tradeoff analysis",
>     systemPrompt: "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Ollama theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "ollama:north-mini-code-1.0",
>   subagents: [{
>     name: "architect",
>     description: "Proposes a database schema design with tradeoff analysis",
>     systemPrompt: "You are a database architect. Propose a schema design for the given requirements. Include tradeoffs, migration considerations, and a clear rationale.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> :::
>
> **智能体生成的代码**
>
> ```ts theme={null}
> // Generate independent proposals in parallel, then score and keep the best.
> const proposals = await Promise.all(
>   [1, 2, 3].map((n) =>
>     task({
>       description: `Approach ${n}: redesign the orders schema, with tradeoffs.`,
>       subagentType: "architect",
>       responseSchema: designSchema, // -> { design, tradeoffs }
>     }),
>   ),
> );
>
> // ... score each proposal against the requirements
> const best = proposals.sort((a, b) => score(b) - score(a))[0];
> best;
> ```

### 淘汰赛

多个方案通过评委子智能体进行一对一比拼，胜者进入下一轮 elimination 轮次。

```mermaid theme={null}
graph LR
    A1[Attempt] --> J1{Judge}
    A2[Attempt] --> J1
    A3[Attempt] --> J2{Judge}
    A4[Attempt] --> J2
    J1 --> JF{Final}
    J2 --> JF
    JF --> Winner[Winner]
```

**应用场景：** 主观标准下的优化、风格选择、实现方案竞争性评估。

> [accordion] Example: tournament
>
> **需配置的内容**
>
> :::python
>
> ```python Google theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="google_genai:gemini-3.6-flash",
>     subagents=[
>         {
>             "name": "writer",
>             "description": "Rewrites a function with a focus on readability and clarity",
>             "system_prompt": "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>         },
>         {
>             "name": "judge",
>             "description": "Compares two code implementations and picks the more readable one",
>             "system_prompt": "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python OpenAI theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="openai:gpt-5.5",
>     subagents=[
>         {
>             "name": "writer",
>             "description": "Rewrites a function with a focus on readability and clarity",
>             "system_prompt": "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>         },
>         {
>             "name": "judge",
>             "description": "Compares two code implementations and picks the more readable one",
>             "system_prompt": "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Anthropic theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="anthropic:claude-sonnet-5",
>     subagents=[
>         {
>             "name": "writer",
>             "description": "Rewrites a function with a focus on readability and clarity",
>             "system_prompt": "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>         },
>         {
>             "name": "judge",
>             "description": "Compares two code implementations and picks the more readable one",
>             "system_prompt": "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python OpenRouter theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="openrouter:z-ai/glm-5.2",
>     subagents=[
>         {
>             "name": "writer",
>             "description": "Rewrites a function with a focus on readability and clarity",
>             "system_prompt": "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>         },
>         {
>             "name": "judge",
>             "description": "Compares two code implementations and picks the more readable one",
>             "system_prompt": "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Fireworks theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="fireworks:accounts/fireworks/models/glm-5p2",
>     subagents=[
>         {
>             "name": "writer",
>             "description": "Rewrites a function with a focus on readability and clarity",
>             "system_prompt": "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>         },
>         {
>             "name": "judge",
>             "description": "Compares two code implementations and picks the more readable one",
>             "system_prompt": "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Baseten theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="baseten:zai-org/GLM-5.2",
>     subagents=[
>         {
>             "name": "writer",
>             "description": "Rewrites a function with a focus on readability and clarity",
>             "system_prompt": "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>         },
>         {
>             "name": "judge",
>             "description": "Compares two code implementations and picks the more readable one",
>             "system_prompt": "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Ollama theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="ollama:north-mini-code-1.0",
>     subagents=[
>         {
>             "name": "writer",
>             "description": "Rewrites a function with a focus on readability and clarity",
>             "system_prompt": "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>         },
>         {
>             "name": "judge",
>             "description": "Compares two code implementations and picks the more readable one",
>             "system_prompt": "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>         },
>     ],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> :::
>
> :::js
>
> ```ts Google theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "google:gemini-3.6-flash",
>   subagents: [
>     {
>       name: "writer",
>       description: "Rewrites a function with a focus on readability and clarity",
>       systemPrompt: "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>     },
>     {
>       name: "judge",
>       description: "Compares two code implementations and picks the more readable one",
>       systemPrompt: "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts OpenAI theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "openai:gpt-5.5",
>   subagents: [
>     {
>       name: "writer",
>       description: "Rewrites a function with a focus on readability and clarity",
>       systemPrompt: "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>     },
>     {
>       name: "judge",
>       description: "Compares two code implementations and picks the more readable one",
>       systemPrompt: "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Anthropic theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "anthropic:claude-sonnet-5",
>   subagents: [
>     {
>       name: "writer",
>       description: "Rewrites a function with a focus on readability and clarity",
>       systemPrompt: "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>     },
>     {
>       name: "judge",
>       description: "Compares two code implementations and picks the more readable one",
>       systemPrompt: "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts OpenRouter theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "openrouter:z-ai/glm-5.2",
>   subagents: [
>     {
>       name: "writer",
>       description: "Rewrites a function with a focus on readability and clarity",
>       systemPrompt: "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>     },
>     {
>       name: "judge",
>       description: "Compares two code implementations and picks the more readable one",
>       systemPrompt: "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Fireworks theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "fireworks:accounts/fireworks/models/glm-5p2",
>   subagents: [
>     {
>       name: "writer",
>       description: "Rewrites a function with a focus on readability and clarity",
>       systemPrompt: "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>     },
>     {
>       name: "judge",
>       description: "Compares two code implementations and picks the more readable one",
>       systemPrompt: "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Baseten theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "baseten:zai-org/GLM-5.2",
>   subagents: [
>     {
>       name: "writer",
>       description: "Rewrites a function with a focus on readability and clarity",
>       systemPrompt: "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>     },
>     {
>       name: "judge",
>       description: "Compares two code implementations and picks the more readable one",
>       systemPrompt: "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Ollama theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "ollama:north-mini-code-1.0",
>   subagents: [
>     {
>       name: "writer",
>       description: "Rewrites a function with a focus on readability and clarity",
>       systemPrompt: "You are an expert programmer focused on clean code. Rewrite the given function to maximize readability. Explain your choices.",
>     },
>     {
>       name: "judge",
>       description: "Compares two code implementations and picks the more readable one",
>       systemPrompt: "You are a code quality judge. Compare two implementations and pick the more readable one. Justify your choice with specific criteria.",
>     },
>   ],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> :::
>
> **智能体生成的代码**
>
> ```ts theme={null}
> // Generate variants, then judge pairwise until a single winner remains.
> let bracket = await Promise.all(
>   [1, 2, 3, 4, 5].map((n) =>
>     task({ description: `Rewrite processOrder for readability (variant ${n}).`, subagentType: "writer" }),
>   ),
> );
>
> while (bracket.length > 1) {
>   const winners = [];
>   for (let i = 0; i < bracket.length; i += 2) {
>     if (bracket[i + 1] === undefined) { winners.push(bracket[i]); break; }
>     const { winner } = await task({
>       description: `Pick the more readable:\n\nA:\n${bracket[i]}\n\nB:\n${bracket[i + 1]}`,
>       subagentType: "judge",
>       responseSchema: pickSchema, // -> { winner: "A" | "B" }
>     });
>     winners.push(winner === "A" ? bracket[i] : bracket[i + 1]);
>   }
>   bracket = winners;
> }
> bracket[0]; // the winning rewrite
> ```

### 循环直到完成

智能体执行发现循环，通过去重机制确保不重复结果，直至无新结果产生。适用于任务范围不明确的前置条件。

```mermaid theme={null}
graph LR
    Agent[Agent] --> Check{New findings?}
    Check --> |yes| Agent
    Check --> |no| Done[Done]
```

**应用场景：** 全量搜索、死代码检测、依赖审计、追求完整性的全面扫描。

> [accordion] Example: loop until done
>
> **需配置的内容**
>
> :::python
>
> ```python Google theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="google_genai:gemini-3.6-flash",
>     subagents=[{
>         "name": "analyzer",
>         "description": "Analyzes code for unused exports, functions, and dead code paths",
>         "system_prompt": "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python OpenAI theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="openai:gpt-5.5",
>     subagents=[{
>         "name": "analyzer",
>         "description": "Analyzes code for unused exports, functions, and dead code paths",
>         "system_prompt": "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Anthropic theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="anthropic:claude-sonnet-5",
>     subagents=[{
>         "name": "analyzer",
>         "description": "Analyzes code for unused exports, functions, and dead code paths",
>         "system_prompt": "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python OpenRouter theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="openrouter:z-ai/glm-5.2",
>     subagents=[{
>         "name": "analyzer",
>         "description": "Analyzes code for unused exports, functions, and dead code paths",
>         "system_prompt": "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Fireworks theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="fireworks:accounts/fireworks/models/glm-5p2",
>     subagents=[{
>         "name": "analyzer",
>         "description": "Analyzes code for unused exports, functions, and dead code paths",
>         "system_prompt": "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Baseten theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="baseten:zai-org/GLM-5.2",
>     subagents=[{
>         "name": "analyzer",
>         "description": "Analyzes code for unused exports, functions, and dead code paths",
>         "system_prompt": "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> ```python Ollama theme={null}
> from deepagents import create_deep_agent
> from langchain_quickjs import CodeInterpreterMiddleware
>
> agent = create_deep_agent(
>     model="ollama:north-mini-code-1.0",
>     subagents=[{
>         "name": "analyzer",
>         "description": "Analyzes code for unused exports, functions, and dead code paths",
>         "system_prompt": "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>     }],
>     middleware=[CodeInterpreterMiddleware()],
> )
> ```
>
> :::
>
> :::js
>
> ```ts Google theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "google:gemini-3.6-flash",
>   subagents: [{
>     name: "analyzer",
>     description: "Analyzes code for unused exports, functions, and dead code paths",
>     systemPrompt: "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts OpenAI theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "openai:gpt-5.5",
>   subagents: [{
>     name: "analyzer",
>     description: "Analyzes code for unused exports, functions, and dead code paths",
>     systemPrompt: "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Anthropic theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "anthropic:claude-sonnet-5",
>   subagents: [{
>     name: "analyzer",
>     description: "Analyzes code for unused exports, functions, and dead code paths",
>     systemPrompt: "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts OpenRouter theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "openrouter:z-ai/glm-5.2",
>   subagents: [{
>     name: "analyzer",
>     description: "Analyzes code for unused exports, functions, and dead code paths",
>     systemPrompt: "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Fireworks theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "fireworks:accounts/fireworks/models/glm-5p2",
>   subagents: [{
>     name: "analyzer",
>     description: "Analyzes code for unused exports, functions, and dead code paths",
>     systemPrompt: "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Baseten theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "baseten:zai-org/GLM-5.2",
>   subagents: [{
>     name: "analyzer",
>     description: "Analyzes code for unused exports, functions, and dead code paths",
>     systemPrompt: "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> ```ts Ollama theme={null}
> import { createDeepAgent } from "deepagents";
> import { createCodeInterpreterMiddleware } from "@langchain/quickjs";
>
> const agent = createDeepAgent({
>   model: "ollama:north-mini-code-1.0",
>   subagents: [{
>     name: "analyzer",
>     description: "Analyzes code for unused exports, functions, and dead code paths",
>     systemPrompt: "You are a code analyst specializing in dead code detection. Find unused exports, unreachable functions, and orphaned modules. Report each with file path and evidence.",
>   }],
>   middleware: [createCodeInterpreterMiddleware()],
> });
> ```
>
> :::
>
> **智能体生成的代码**
>
> ```ts theme={null}
> // Keep dispatching rounds, deduping against what's found, until a round adds nothing.
> const seen = new Set();
> const found = [];
>
> while (true) {
>   const { items } = await task({
>     description: `Find dead code. Already found: ${[...seen].join(", ") || "(none)"}.`,
>     subagentType: "analyzer",
>     responseSchema: itemsSchema, // -> { items: [{ id, file }] }
>   });
>   const fresh = items.filter((i) => !seen.has(i.id));
>   if (fresh.length === 0) break; // converged: nothing new
>   for (const i of fresh) { seen.add(i.id); found.push(i); }
> }
> found;
> ```

:::python

> [!WARNING]
>
> `task()` 在已运行的 `eval` 调用内部分发。它不经过常规工具调用路径，因此父智能体的 `interrupt_on` 审批工作流对每个分发不生效。若需在编排前审批，需对 `eval` 工具本身设置权限门禁。

:::
:::js

> [!WARNING]
>
> `task()` 在已运行的 `eval` 调用内部分发。它不经过常规工具调用路径，因此父智能体的 `interruptOn` 审批工作流对每个分发不生效。若需在编排前审批，需对 `eval` 工具本身设置权限门禁。

:::

## 禁用动态子智能体

智能体默认在包含子智能体时启用分发。若需仅通过常规 `task` 工具路径访问子智能体，可禁用此功能。其他中间件配置请参阅[解释器](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/interpreters.md#配置)页面中的配置说明。

:::python

```python Google theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="google_genai:gemini-3.6-flash",
    subagents=[{"name": "reviewer", "description": "Reviews code", "system_prompt": "Review code."}],
    middleware=[CodeInterpreterMiddleware(subagents=False)],
)
```

```python OpenAI theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="openai:gpt-5.5",
    subagents=[{"name": "reviewer", "description": "Reviews code", "system_prompt": "Review code."}],
    middleware=[CodeInterpreterMiddleware(subagents=False)],
)
```

```python Anthropic theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="anthropic:claude-sonnet-5",
    subagents=[{"name": "reviewer", "description": "Reviews code", "system_prompt": "Review code."}],
    middleware=[CodeInterpreterMiddleware(subagents=False)],
)
```

```python OpenRouter theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="openrouter:z-ai/glm-5.2",
    subagents=[{"name": "reviewer", "description": "Reviews code", "system_prompt": "Review code."}],
    middleware=[CodeInterpreterMiddleware(subagents=False)],
)
```

```python Fireworks theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="fireworks:accounts/fireworks/models/glm-5p2",
    subagents=[{"name": "reviewer", "description": "Reviews code", "system_prompt": "Review code."}],
    middleware=[CodeInterpreterMiddleware(subagents=False)],
)
```

```python Baseten theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="baseten:zai-org/GLM-5.2",
    subagents=[{"name": "reviewer", "description": "Reviews code", "system_prompt": "Review code."}],
    middleware=[CodeInterpreterMiddleware(subagents=False)],
)
```

```python Ollama theme={null}
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="ollama:north-mini-code-1.0",
    subagents=[{"name": "reviewer", "description": "Reviews code", "system_prompt": "Review code."}],
    middleware=[CodeInterpreterMiddleware(subagents=False)],
)
```

:::

:::js

```ts Google theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "google:gemini-3.6-flash",
  subagents: [{ name: "reviewer", description: "Reviews code", systemPrompt: "Review code." }],
  middleware: [createCodeInterpreterMiddleware({ subagents: false })],
});
```

```ts OpenAI theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "openai:gpt-5.5",
  subagents: [{ name: "reviewer", description: "Reviews code", systemPrompt: "Review code." }],
  middleware: [createCodeInterpreterMiddleware({ subagents: false })],
});
```

```ts Anthropic theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "anthropic:claude-sonnet-5",
  subagents: [{ name: "reviewer", description: "Reviews code", systemPrompt: "Review code." }],
  middleware: [createCodeInterpreterMiddleware({ subagents: false })],
});
```

```ts OpenRouter theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "openrouter:z-ai/glm-5.2",
  subagents: [{ name: "reviewer", description: "Reviews code", systemPrompt: "Review code." }],
  middleware: [createCodeInterpreterMiddleware({ subagents: false })],
});
```

```ts Fireworks theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "fireworks:accounts/fireworks/models/glm-5p2",
  subagents: [{ name: "reviewer", description: "Reviews code", systemPrompt: "Review code." }],
  middleware: [createCodeInterpreterMiddleware({ subagents: false })],
});
```

```ts Baseten theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "baseten:zai-org/GLM-5.2",
  subagents: [{ name: "reviewer", description: "Reviews code", systemPrompt: "Review code." }],
  middleware: [createCodeInterpreterMiddleware({ subagents: false })],
});
```

```ts Ollama theme={null}
import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "ollama:north-mini-code-1.0",
  subagents: [{ name: "reviewer", description: "Reviews code", systemPrompt: "Review code." }],
  middleware: [createCodeInterpreterMiddleware({ subagents: false })],
});
```

:::

## 参考文档

* [解释器](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/interpreters.md)：QuickJS配置、程序化工具调用、持久化、安全设置与中间件配置
* [子智能体](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/subagents.md)：配置子智能体名称、描述和系统提示词
* [事件流式输出](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/event-streaming.md)：从协调者和委派子智能体接收更新流

***

> 官方原文：[src/oss/deepagents/dynamic-subagents.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/deepagents/dynamic-subagents.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.