开发者指南:ADK 中的 multi-agent 模式

发布: (2026年1月28日 GMT+8 08:04)
12 min read

Source: Google Developers Blog

2025年12月16日

软件开发领域已经明白了一个道理:单体应用无法扩展。无论你是在构建大型电子商务平台还是复杂的 AI 应用,依赖单一的“一体化”实体都会产生瓶颈、增加调试成本,并限制专门化的性能。

同样的原则也适用于 AI 代理。让单个代理承担过多职责会导致它成为“样样通,样样松”。随着指令的复杂度提升,对特定规则的遵循度下降,错误率叠加,进而产生越来越多的“幻觉”。如果你的代理出现故障,你不应该必须拆除整个提示来寻找 bug。

可靠性来源于去中心化和专业化。多代理系统(MAS)让你能够构建 AI 版的微服务架构。通过为各个代理分配特定角色(如 ParserCriticDispatcher),你可以构建本质上更具模块化、可测试且可靠的系统。

在本指南中,我们将使用 Google Agent Development Kit (ADK) 来阐释八种关键设计模式——从顺序流水线到人机交互模式——提供构建生产级代理团队所需的具体模式和伪代码。

1. 顺序流水线模式(又称 装配线

把这个模式想象成经典的装配线,Agent A 完成任务后直接把“接力棒”交给 Agent B。它是线性的、确定性的,并且因为你总是能确切知道数据来源,所以调试起来非常轻松。

典型用例: 处理原始文档。
ParserExtractorSummarizer

顺序模式

在 ADK 中,SequentialAgent 原语为你处理编排工作。关键在于 状态管理:只需使用 output_key 将结果写入共享的 session.state,这样链中的下一个代理就能准确知道从哪里继续工作。

# ADK Pseudocode

# Step 1: Parse the PDF
parser = LlmAgent(
    name="ParserAgent",
    instruction="Parse raw PDF and extract text.",
    tools=[PDFParser],
    output_key="raw_text"
)

# Step 2: Extract structured data
extractor = LlmAgent(
    name="ExtractorAgent",
    instruction="Extract structured data from {raw_text}.",
    tools=[RegexExtractor],
    output_key="structured_data"
)

# Step 3: Summarize
summarizer = LlmAgent(
    name="SummarizerAgent",
    instruction="Generate summary from {structured_data}.",
    tools=[SummaryEngine]
)

# Orchestrate the Assembly Line
pipeline = SequentialAgent(
    name="PDFProcessingPipeline",
    sub_agents=[parser, extractor, summarizer]
)

2. Coordinator / Dispatcher Pattern(又称 礼宾员

有时你不需要链式结构;你需要一个决策者。在此模式中,一个中心的、智能的代理充当 调度器。它分析用户意图并将请求路由到最适合该任务的专门代理。

典型用例: 需要将用户路由到“计费”专员或“技术支持”专员的复杂客服机器人。

协调‑调度器模式

这依赖于 LLM 驱动的委派。定义一个父级 CoordinatorAgent 并提供一组专门的 sub_agents。ADK 的 AutoFlow 机制会根据你为子代理提供的描述转移执行。

# ADK Pseudocode

billing_specialist = LlmAgent(
    name="BillingSpecialist",
    description="Handles billing inquiries and invoices.",
    tools=[BillingSystemDB]
)

tech_support = LlmAgent(
    name="TechSupportSpecialist",
    description="Troubleshoots technical issues.",
    tools=[DiagnosticTool]
)

# The Coordinator (Dispatcher)
coordinator = LlmAgent(
    name="CoordinatorAgent",
    instruction=(
        "Analyze user intent. Route billing issues to BillingSpecialist "
        "and bugs to TechSupportSpecialist."
    ),
    sub_agents=[billing_specialist, tech_support]
)

Source:

3. 并行 Fan‑Out / Gather 模式(又称 章鱼模式

速度至关重要。如果任务之间没有依赖关系,为什么要一个接一个地执行呢?在此模式下,多个代理 同时 执行任务,以降低延迟或获得多元化的视角。它们的输出随后由最终的 “合成器” 代理进行聚合。

典型用例: 自动代码审查。并行生成 安全审计员风格执行者性能分析师,然后用 合成器 代理将它们的反馈合并。

Parallel fan‑out pattern

ADK 中的 ParallelAgent 会并发运行 sub_agents。虽然这些代理在不同的执行线程中运行,但它们共享同一会话状态,因此在写入共享键时需注意竞争条件。

# ADK Pseudocode

security_auditor = LlmAgent(
    name="SecurityAuditor",
    instruction="Check the PR for security vulnerabilities.",
    tools=[StaticAnalyzer]
)

style_enforcer = LlmAgent(
    name="StyleEnforcer",
    instruction="Enforce coding style guidelines.",
    tools=[Linter]
)

performance_analyst = LlmAgent(
    name="PerformanceAnalyst",
    instruction="Identify performance bottlenecks.",
    tools=[PerfProfiler]
)

# Synthesizer that gathers the three reports
synthesizer = LlmAgent(
    name="ReviewSynthesizer",
    instruction=(
        "Combine the outputs from SecurityAuditor, StyleEnforcer, and "
        "PerformanceAnalyst into a single, cohesive review comment."
    ),
    tools=[TextCombiner]
)

# Parallel orchestration
parallel_review = ParallelAgent(
    name="ParallelCodeReview",
    sub_agents=[security_auditor, style_enforcer, performance_analyst],
    gather_agent=synthesizer
)

其余五种模式(Human‑in‑the‑loop、Critic‑Reviewer、Adaptive Routing、Stateful Conversation 和 Self‑Healing)遵循类似的原理,详细内容请参阅完整的 ADK 文档。

4. 并行分支(又称 “Swarm”)

当一个任务可以拆分为相互独立的子任务时,你可以并行运行多个代理,然后合并它们的结果。每个子代理将其输出写入会话状态中的唯一键,以避免竞争条件。

# ADK Pseudo

# Define parallel workers
security_scanner = LlmAgent(
    name="SecurityAuditor",
    instruction="Check for vulnerabilities like injection attacks.",
    output_key="security_report"
)

style_checker = LlmAgent(
    name="StyleEnforcer",
    instruction="Check for PEP8 compliance and formatting issues.",
    output_key="style_report"
)

complexity_analyzer = LlmAgent(
    name="PerformanceAnalyst",
    instruction="Analyze time complexity and resource usage.",
    output_key="performance_report"
)

# Fan‑out (the Swarm)
parallel_reviews = ParallelAgent(
    name="CodeReviewSwarm",
    sub_agents=[security_scanner, style_checker, complexity_analyzer]
)

# Gather / Synthesize
pr_summarizer = LlmAgent(
    name="PRSummarizer",
    instruction=(
        "Create a consolidated Pull Request review using "
        "{security_report}, {style_report}, and {performance_report}."
    )
)

# Wrap in a sequence
workflow = SequentialAgent(sub_agents=[parallel_reviews, pr_summarizer])

5. 层次分解(又称俄罗斯套娃)

大型任务可能超出单个代理的上下文窗口。高级代理可以将目标拆分为子任务,并将它们委派给低级代理。与简单路由不同,父代理可以在继续自身推理之前等待子任务的结果。

层次任务分解代理

您可以将子代理视为工具,通过将其包装在 AgentTool 中。父代理随后将整个子工作流作为单个函数调用。

# ADK Pseudocode

# Level 3: Tool agents
web_searcher = LlmAgent(
    name="WebSearchAgent",
    description="Searches the web for facts."
)

summarizer = LlmAgent(
    name="SummarizerAgent",
    description="Condenses text."
)

# Level 2: Coordinator agent
research_assistant = LlmAgent(
    name="ResearchAssistant",
    description="Finds and summarizes info.",
    sub_agents=[web_searcher, summarizer]
)

# Level 1: Top‑level agent
report_writer = LlmAgent(
    name="ReportWriter",
    instruction=(
        "Write a comprehensive report on AI trends. "
        "Use the ResearchAssistant to gather info."
    ),
    tools=[AgentTool(research_assistant)]
)

6. Generator & Critic(也称编辑桌)

将创作与验证分离。Generator 负责生成草稿;Critic 根据硬编码标准检查草稿。如果草稿未通过,反馈会返回给 Generator 进行修订。该循环持续进行,直至输出通过质量门。

generator‑critic agent pattern

实现使用 SequentialAgent 进行草稿‑评审交互,并使用 LoopAgent 强制退出条件。

# ADK Pseudocode

# Generator
generator = LlmAgent(
    name="Generator",
    instruction=(
        "Generate a SQL query. If you receive {feedback}, "
        "fix the errors and generate again."
    ),
    output_key="draft"
)

# Critic
critic = LlmAgent(
    name="Critic",
    instruction=(
        "Check if {draft} is valid SQL. If correct, output 'PASS'. "
        "If not, output error details."
    ),
    output_key="feedback"
)

# Loop that repeats until the critic returns PASS
validation_loop = LoopAgent(
    name="ValidationLoop",
    sub_agents=[generator, critic],
    condition_key="feedback",
    exit_condition="PASS"
)

7. 迭代细化(又称雕塑家)

对于那些通过逐步改进而不是简单的通过/失败来获益的任务,使用 生成器 → 批评者 → 细化 代理的循环。当达到质量阈值时,循环结束;这可以是在固定的迭代次数后,或是某个代理提前发出完成信号(escalate=True)。

iterative refinement agent pattern

# ADK Pseudocode

# Generator
generator = LlmAgent(
    name="Generator",
    instruction="Create a first draft of the document.",
    output_key="draft"
)

# Critic (provides improvement notes)
critic = LlmAgent(
    name="Critic",
    instruction="Review {draft} and return a list of improvement suggestions.",
    output_key="feedback"
)

# Refinement (applies suggestions)
refiner = LlmAgent(
    name="Refiner",
    instruction=(
        "Take {draft} and the suggestions in {feedback}, "
        "and produce an improved version."
    ),
    output_key="refined"
)

# Loop that continues until the critic signals quality or max_iterations is hit
refinement_loop = LoopAgent(
    name="IterativeRefinement",
    sub_agents=[generator, critic, refiner],
    condition_key="feedback",
    exit_condition="QUALITY_OK",
    max_iterations=5
)

模式概览

模式何时使用核心原语
并行分支可以并发执行的独立子任务ParallelAgent, SequentialAgent
层次分解单个上下文窗口容纳不了的庞大任务嵌套的 LlmAgentAgentTool 包装
生成器 & 批评者需要严格的正确性或合规性检查SequentialAgent + LoopAgent
迭代细化质量通过多轮迭代逐步提升带自定义退出逻辑的 LoopAgent

这些模式可以组合使用,以 ADK 框架构建复杂且可靠的工作流。

generator = LlmAgent(
    name="Generator",
    instruction="Generate an initial rough draft.",
    output_key="current_draft"
)

# Critique Agent
critic = LlmAgent(
    name="Critic",
    instruction="Review {current_draft}. List ways to optimize it for performance.",
    output_key="critique_notes"
)

# Refiner Agent
refiner = LlmAgent(
    name="Refiner",
    instruction="Read {current_draft} and {critique_notes}. Rewrite the draft to be more efficient.",
    output_key="current_draft"
)

# The Loop (Critique → Refine)
loop = LoopAgent(
    name="RefinementLoop",
    max_iterations=3,
    sub_agents=[critic, refiner]
)

# Complete Workflow
workflow = SequentialAgent(sub_agents=[generator, loop])

8. 人在回路中(人类安全网)

AI 代理功能强大,但在关键决策时有时需要人类坐在驾驶座上。在此模型中,代理负责基础工作,而人类必须授权高风险操作——尤其是那些不可逆或会产生重大后果的操作(例如执行金融交易、将代码部署到生产环境或处理敏感数据)。这可确保安全性和问责制。

图示展示了一个 Transaction Agent 处理常规工作。当需要进行高风险检查时,它会调用 ApprovalTool Agent,该代理会暂停执行并等待 Human Reviewer 给出“是”或“否”的回答。

human‑in‑the‑loop 模式

ADK 允许您通过自定义工具实现此功能。代理可以调用 approval_tool,该工具会暂停执行或触发外部系统请求人工干预。

# ADK Pseudocode
transaction_agent = LlmAgent(
    name="TransactionAgent",
    instruction="Handle routine processing. If high stakes, call ApprovalTool.",
    tools=[ApprovalTool]
)

approval_agent = LlmAgent(
    name="ApprovalToolAgent",
    instruction="Pause execution and request human input."
)

workflow = SequentialAgent(sub_agents=[transaction_agent, approval_agent])

9. Composite patterns (the mix‑and‑match)

实际的企业应用程序很少能单独归入某一种模式。您可能需要将这些模式组合起来,以构建生产级系统。

示例: 一个强大的客户支持系统可能使用 Coordinator 来路由请求。如果用户遇到技术问题,该分支可以触发对文档和用户历史的 Parallel 并行搜索。最终答案可能会经过 Generator → Critic 循环,以确保语气一致性,然后发送给用户。

composite agent pattern

Back to Blog

相关文章

阅读更多 »