动态子代理允许代理调度 子代理 从解释器代码中。代理可以使用 JavaScript 循环、分支和并行批次来路由工作到配置的子代理并综合结果,而不是让模型一次选择一个子代理调用。
当工作跨越多个独立单元、需要多个视角或受益于递归分析时使用此模式。有关通用解释器设置,请参阅 解释器.
快速入门
动态子代理需要两样东西:用于调度工作的子代理,以及一个代码解释器——一个安全、轻量级的运行时,模型在其中编写和执行编排代码。Deep Agents 包含一个基于 QuickJS 的可选代码解释器。安装 QuickJS 中间件包,然后通过 middleware 参数传递解释器中间件 create_deep_agent.
npm install deepagents @langchain/quickjs
pnpm add deepagents @langchain/quickjs
yarn add deepagents @langchain/quickjs
const agent = createDeepAgent({
model: "openai:gpt-5.5",
middleware: [createCodeInterpreterMiddleware()],
});
Deep Agents 内置了一个通用子代理,因此基本扇出无需额外配置即可工作。对于专业工作,配置具有自己名称、描述和系统提示的自定义子代理;名称和描述是代理知道应该使用哪个角色的方式。请参阅 子代理 进行配置。
要触发动态子代理,请使用单词 "workflow" 来提示代理:
const result = await agent.invoke({
messages: [{ role: "user", content: "Run a workflow that reviews every file in src/routes/ and summarizes the top risks." }],
});
与编码代理一起使用
尝试动态子代理的最快方式是使用 dcode,一个基于 Deep Agent 构建的 LangChain 终端编码代理。它默认启用了代码解释器,因此动态子代理开箱即用,无需任何配置。
安装 dcode:
curl -LsSf https://langch.in/dcode | bash
运行它:
dcode
要触发动态子代理,请请求一个 "workflow"。而不是通过其原生 task 工具来处理工作本身或管理扇出,代理会编写一个调用内置 task() global and runs it in the code interpreter. For example: "Run a workflow to review every file in src/ for SQL injection."
当子代理生成时, dcode 会在动态子代理面板中实时显示它们,按调度阶段分组。
!显示已生成子代理按调度阶段分组的 dcode 动态子代理面板
dcode 是尝试此操作的最快方式,但您也可以在您选择的编码代理中使用动态子代理 ACP (例如 Zed)。
工作原理
当代理拥有 子代理 和解释器中间件时,解释器会公开一个内置 task() 全局模式,从代码中分派子代理。跨越多个独立单元的任务(如审查目录中的每个文件、分拣一批工单)会变成一个将工作扇出的循环,从而以确定性方式运行,而不是每次由模型选择一个工具调用。
子代理编排还支持递归语言模型 (RLM) 工作流,这是一种在 递归语言模型论文中描述的方法:保持在解释器变量中的工作集,选择片段,使用 task()调用子代理,并综合结果。
task() 接受以下输入:
- -
description:子代理的提示词 - -
subagentType:要运行哪个已配置的子代理 - -
responseSchema(可选):结构化输出
A task() 运行完整的代理循环并解析为子代理的结果:
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 。
模式
代理根据任务的形态选择策略;这些模式从它编写的解释器代码中自然产生,而非来自配置,你提供的子代理决定了它能做什么。每种模式都共享一个模型:在 JS 变量中保存工作,使用 task()分派子代理,并在代码中合并结果。下图展示了常见的形态,每种都有可运行的示例。
分类与执行
项目首先被分类,然后根据其分类由专门的子代理处理每个项目。这让你能够处理混合输入,其中不同项目需要不同的专业知识。
graph LR
Task[Task] --> Classify{Classifier}
Classify --> |bug| A[Agent A]
Classify --> |feature| B[Agent B]
Classify --> |question| C[Agent C]
使用场景: 对工单、错误日志、用户反馈或任何需要根据类型不同处理的批量项目进行分类。
Example: classify and act
你的配置
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()],
});
const result = await agent.invoke({
messages: [{ role: "user", content: "Go through these 30 support tickets. Categorize each one, then for bugs give me reproduction steps, and for feature requests give me a feasibility assessment." }],
});
代理编写的代码
// 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;
扇出与综合
代理并行地向多个项目分派相同类型的工作,然后合并结果。
graph LR
Items[Items] --> W1[Worker]
Items --> W2[Worker]
Items --> W3[Worker]
W1 --> Collect[Collect]
W2 --> Collect
W3 --> Collect
Collect --> Synth[Synthesize]
使用场景: 跨目录的代码审查、分析一批文档、处理日志文件、对多个服务运行相同的检查。
Example: fan-out and synthesize
你的配置
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()],
});
const result = await agent.invoke({
messages: [{ role: "user", content: "Review all the route handlers in src/routes/ for authentication issues. Summarize the top risks." }],
});
代理编写的代码
// 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;
对抗性验证
一种两轮通过的模式。第一轮产生发现结果。第二轮将每个发现结果发送给独立的验证者,只有通过验证一致的发现结果才会被保留。当置信度比速度更重要时,这可以减少误报。
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]
使用场景: 误报成本高昂的安全审计、合规性检查、任何需要对发现结果有高度置信度的审查。
Example: adversarial verification
你的配置
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()],
});
const result = await agent.invoke({
messages: [{ role: "user", content: "Do a thorough security audit of the payments module. I only want confirmed vulnerabilities, not maybes." }],
});
代理编写的代码
// Pass 1: audit. Pass 2: verify each finding independently; keep only confirmed.
const { findings } = await task({
description: "Audit the payments module for vulnerabilities.",
subagentType: "auditor",
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;
生成与过滤
多个子代理对同一问题生成独立的解决方案。代理在代码中比较、评分和过滤结果,只保留最佳的。
graph LR
Prompt[Prompt] --> G1[Generator]
Prompt --> G2[Generator]
Prompt --> G3[Generator]
G1 --> Filter[Filter + rank]
G2 --> Filter
G3 --> Filter
Filter --> Best[Best result]
使用场景: 架构提案、重构策略、内容变体、任何需要在提交前探索多个选项以获得更好结果的任务。
Example: generate and filter
你的配置
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()],
});
const result = await agent.invoke({
messages: [{ role: "user", content: "Generate three different approaches to restructure the database schema for the orders system, then pick the best one." }],
});
代理编写的代码
// 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;
淘汰赛
变体由评判子智能体进行一对一比较,获胜者通过淘汰轮晋级。
graph LR
A1[Attempt] --> J1{Judge}
A2[Attempt] --> J1
A3[Attempt] --> J2{Judge}
A4[Attempt] --> J2
J1 --> JF{Final}
J2 --> JF
JF --> Winner[Winner]
使用场景: 主观标准下的优化、风格选择、在竞争性实现之间做出选择。
Example: tournament
配置项
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()],
});
const result = await agent.invoke({
messages: [{ role: "user", content: "Rewrite the processOrder function in src/checkout.ts five different ways and find the most readable version." }],
});
智能体写入内容
// 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
循环直至完成
智能体运行发现循环,对已找到的结果进行去重,直到没有新结果出现。当工作范围无法预先确定时,此功能非常有用。
graph LR
Agent[Agent] --> Check{New findings?}
Check --> |yes| Agent
Check --> |no| Done[Done]
使用场景: 穷举搜索、死代码检测、依赖审计,以及任何需要完整性而非固定数量结果的全量扫描。
Example: loop until done
配置项
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()],
});
const result = await agent.invoke({
messages: [{ role: "user", content: "Find all the dead code in this repo. Be thorough. I want every unused export and unreachable function." }],
});
智能体写入内容
// 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;
禁用动态子智能体
默认情况下,只要智能体具有子智能体,就会启用子智能体分派。如果希望子智能体仅通过正常的 task 工具路径可用,请禁用此功能。
const agent = createDeepAgent({
model: "openai:gpt-5.5",
subagents: [{ name: "reviewer", description: "Reviews code", systemPrompt: "Review code." }],
middleware: [createCodeInterpreterMiddleware({ subagents: false })],
});