ADK 多智能体编排:SequentialAgent、ParallelAgent 与 LoopAgent 解析

简介: ADK 提供 Sequential、Parallel、Loop 三种智能体编排模式,支持订单接收、库存检查、生产调度等多角色协同;状态通过 output_key 自动流转,无需手写胶水代码,轻松构建端到端业务流水线。

单个智能体的专业化程度有上限,真正的工作需要团队:一个角色接收订单,一个检查库存,一个安排生产,一个验证质量。ADK 的编排模式:SequentialAgent、ParallelAgent、LoopAgent可以将多个智能体组合成工作流,流程只定义一次,状态在智能体之间自动传递,故障由系统托管。本文讲介绍每种模式的适用场景、状态的流转机制,以及如何在不编写编排逻辑的前提下搭建一条完整的从订单到交付的流水线。

三种模式:顺序、并行、循环

ADK 提供三种核心模式来组合智能体,每种对应一类真实的业务流程。

模式 1:SequentialAgent——流水线

步骤必须按顺序执行时适用。

 Receive Order → Check Inventory → Schedule Production → Verify Quality → Ship

前一个步骤完成后,下一个才能启动。

 from google.adk.agents import LlmAgent, SequentialAgent  

# 定义每个智能体  
order_receiver = LlmAgent(  
    name="order_receiver",  
    model="gemini-3-flash-preview",  
    instruction="Extract order details from the customer request.",  
    output_key="order_details"  # 命名输出,供下一个智能体使用  
)  

availability_checker = LlmAgent(  
    name="availability_checker",  
    model="gemini-3-flash-preview",  
    instruction="""Check if items are available based on inventory.  
Input: {order_details}  

Respond with availability assessment.""",  
    output_key="availability_status"  
)  

production_scheduler = LlmAgent(  
    name="production_scheduler",  
    model="gemini-3-flash-preview",  
    instruction="""Schedule production given order and availability.  
Order: {order_details}  
Availability: {availability_status}  

Create a production schedule.""",  
    output_key="production_schedule"  
)  

quality_checker = LlmAgent(  
    name="quality_checker",  
    model="gemini-3-flash-preview",  
    instruction="""Verify production schedule meets quality standards.  
Schedule: {production_schedule}  

Approve or flag for revision.""",  
    output_key="quality_approval"  
)  

# 组合成流水线  
order_pipeline = SequentialAgent(  
    name="order_pipeline",  
    sub_agents=[  
        order_receiver,  
        availability_checker,  
        production_scheduler,  
        quality_checker  
    ]  
)  

# 运行  
runner = Runner(  
    agent=order_pipeline,  
    session_service=InMemorySessionService()  
)  

result = runner.send_message(  
    session_id="order-001",  
    message="Customer wants 50 units of Widget A, needs delivery by March 28"  
)  

print(result)  
 # 输出会追踪经过所有四个智能体的过程

output_key 参数是关键。它为每个智能体的输出命名,后续智能体用

{placeholder}

语法引用,ADK 自动完成状态传递。

典型场景:客户下单 → 账务处理付款 → 物流安排取件;代码审查 → 集成测试 → 部署到预发布环境 → 部署到生产环境;接收文档 → 提取字段 → 存入数据库 → 发送通知。

模式 2:ParallelAgent——部门协作

多个独立任务可以同时推进时适用。

 Customer Request  
     ├─ Check Pricing (independent)  
     ├─ Check Inventory (independent)  
     ├─ Check Certifications (independent)  
     └─ [Gather results]  
         → Make decision

各步骤之间不存在数据依赖,并行执行即可。

 from google.adk.agents import LlmAgent, ParallelAgent  

pricing_checker = LlmAgent(  
    name="pricing_checker",  
    model="gemini-3-flash-preview",  
    instruction="""Determine the best pricing for the requested item.  
Item: {order_details}  

Return pricing options.""",  
    output_key="pricing"  
)  

inventory_checker = LlmAgent(  
    name="inventory_checker",  
    model="gemini-3-flash-preview",  
    instruction="""Check warehouse inventory for availability.  
Item: {order_details}  

Return availability by location.""",  
    output_key="inventory"  
)  

compliance_checker = LlmAgent(  
    name="compliance_checker",  
    model="gemini-3-flash-preview",  
    instruction="""Verify compliance requirements.  
Item: {order_details}  

Return compliance status.""",  
    output_key="compliance"  
)  

# 三个智能体同时运行  
evaluation = ParallelAgent(  
    name="order_evaluation",  
    sub_agents=[  
        pricing_checker,  
        inventory_checker,  
        compliance_checker  
    ]  
)  

# 然后一个决策智能体消费所有三个输出  
decision_maker = LlmAgent(  
    name="decision_maker",  
    model="gemini-3-flash-preview",  
    instruction="""Make a decision on the order.  
Pricing: {pricing}  
Inventory: {inventory}  
Compliance: {compliance}  

Decide: proceed or reject. Explain reasoning.""",  
    output_key="decision"  
)  

# 组合:先并行评估,再顺序决策  
full_flow = SequentialAgent(  
    name="order_flow",  
    sub_agents=[  
        evaluation,  
        decision_maker  
    ]  
 )

ParallelAgent 并发启动所有子智能体,等全部返回后再继续。对于彼此无依赖的任务,耗时取决于最慢的那一个,整体远快于串行执行。

典型场景:数据验证(多条规则同时校验)、风险评估(欺诈、合规、安全并行分析)、报价生成(同时向多个供应商询价)、报告生成(多数据源并行采集)。

并行执行意味着更高的资源开销,因为大量智能体同时运行时,API 速率限制和 Token 消耗都应纳入考量。

模式 3:LoopAgent——质量控制循环

需要反复迭代直到满足某个条件时适用。

 Produce Draft → Review → Approve?  
     ├─ No → Revise → Review → Approve?  
     └─ Yes → Complete
 from google.adk.agents import LlmAgent, LoopAgent  

content_producer = LlmAgent(  
    name="content_producer",  
    model="gemini-3-flash-preview",  
    instruction="""Generate content based on requirements.  
Topic: {topic}  
Iteration: {iteration}  

Produce high-quality content.""",  
    output_key="content"  
)  

quality_reviewer = LlmAgent(  
    name="quality_reviewer",  
    model="gemini-3-flash-preview",  
    instruction="""Review the content and decide if it's good enough.  
Content: {content}  

Respond with: APPROVED or NEEDS_REVISION with specific feedback.""",  
    output_key="review"  
)  

# LoopAgent 持续运行流程直到满足停止条件  
content_loop = LoopAgent(  
    name="content_review_loop",  
    sub_agents=[  
        content_producer,  
        quality_reviewer  
    ],  
    max_iterations=3,  # 防止无限循环  
    stop_condition=lambda output: "APPROVED" in output.get("review", "")  
 )

LoopAgent 好用,但有风险——务必设置 max_iterations 限制迭代上限。stop_condition 是一个返回布尔值的函数,返回 True 时循环终止。

典型场景:迭代式优化(写作、设计、代码生成)、质量保证(生产 → 测试 → 通过/失败 → 修复)、协商或共识构建(提议 → 评估 → 批准/修改)。

状态管理:数据在智能体之间的流转

这是整个编排机制的核心。ADK 依靠 output key 和占位符语法自动完成状态传递。

 agent_a = LlmAgent(  
    name="agent_a",  
    instruction="Extract customer name from request.",  
    output_key="customer_name"  
)  

agent_b = LlmAgent(  
    name="agent_b",  
    instruction="Create a welcome message for {customer_name}.",  
    # 注意 {customer_name} 占位符——引用 agent_a 的 output_key  
 )

用以上两个智能体构建 SequentialAgent 后,ADK 按如下步骤执行:运行 agent_a 并捕获输出,将其存储在 "customer_name" 键下,然后对 agent_b 的 instruction 做字符串替换——

{customer_name}

被替换为 agent_a 的实际输出——最终将替换后的指令交给 agent_b 执行。

嵌套工作流的机制相同:

 inner_workflow = SequentialAgent(  
    name="inner",  
    sub_agents=[agent_a, agent_b],  
    output_key="welcome_message"  # 整个工作流的输出  
)  

outer_workflow = SequentialAgent(  
    name="outer",  
    sub_agents=[  
        some_initial_agent,  
        inner_workflow,  
        final_agent  # 可以引用 {welcome_message}  
    ]  
 )

命名 output key 时有几个原则:用 snake_case,名称应当自解释,并在文档中记录每个键的含义。

 # 好的做法  
 inventory_status = LlmAgent(..., output_key="inventory_status")  

 # 不好的做法  
 checker = LlmAgent(..., output_key="result")  # 什么 result?

完整示例:从订单到交付的流水线

客户提交了一个订单,系统需要依次完成六件事:接收并解析订单、检查库存、安排生产(库存充足的前提下)、质量检查、安排发货(检查通过的前提下)、发送确认信息。

 from google.adk.agents import LlmAgent, SequentialAgent, ParallelAgent, Agent, FunctionTool  
from google.adk.runners import Runner  
from google.adk.sessions import InMemorySessionService  

# 阶段 1:接收  
order_receiver = LlmAgent(  
    name="order_receiver",  
    model="gemini-3-flash-preview",  
    instruction="""Parse the customer order and extract:  
- Item SKU  
- Quantity  
- Requested delivery date  
- Customer contact info  

Output as structured data.""",  
    output_key="parsed_order"  
)  

# 阶段 2:并行检查  
def check_inventory_tool(sku: str, quantity: int) -> dict:  
    """检查是否有库存。"""  
    # 模拟数据  
    stock = {"SKU-001": 500, "SKU-002": 45}  
    available = stock.get(sku, 0)  
    return {  
        "sku": sku,  
        "requested": quantity,  
        "available": available,  
        "can_fulfill": available >= quantity  
    }  

def get_pricing_tool(sku: str, quantity: int) -> dict:  
    """获取当前定价。"""  
    unit_prices = {"SKU-001": 12.50, "SKU-002": 25.00}  
    price_per_unit = unit_prices.get(sku, 0)  
    total = price_per_unit * quantity  
    return {  
        "sku": sku,  
        "unit_price": price_per_unit,  
        "quantity": quantity,  
        "total_price": total  
    }  

inventory_checker = LlmAgent(  
    name="inventory_checker",  
    model="gemini-3-flash-preview",  
    instruction="""Check inventory for the requested item.  
Order: {parsed_order}  

Use the check_inventory_tool to verify stock.""",  
    tools=[FunctionTool(check_inventory_tool)],  
    output_key="inventory_check"  
)  

pricing_agent = LlmAgent(  
    name="pricing_agent",  
    model="gemini-3-flash-preview",  
    instruction="""Determine pricing for the order.  
Order: {parsed_order}  

Use the get_pricing_tool to calculate the total.""",  
    tools=[FunctionTool(get_pricing_tool)],  
    output_key="pricing_info"  
)  

# 并行评估  
evaluation = ParallelAgent(  
    name="evaluation",  
    sub_agents=[inventory_checker, pricing_agent]  
)  

# 阶段 3:决策  
approval_agent = LlmAgent(  
    name="approval_agent",  
    model="gemini-3-flash-preview",  
    instruction="""Decide if we can fulfill the order.  
Order: {parsed_order}  
Inventory: {inventory_check}  
Pricing: {pricing_info}  

Respond with: APPROVED or REJECTED with reasoning.""",  
    output_key="approval"  
)  

# 阶段 4:生产(仅在批准后)  
production_scheduler = LlmAgent(  
    name="production_scheduler",  
    model="gemini-3-flash-preview",  
    instruction="""Schedule production for the approved order.  
Order: {parsed_order}  
Approval: {approval}  

Create a production schedule with delivery date.""",  
    output_key="production_schedule"  
)  

# 阶段 5:质量检查  
quality_checker = LlmAgent(  
    name="quality_checker",  
    model="gemini-3-flash-preview",  
    instruction="""Verify production schedule meets quality standards.  
Schedule: {production_schedule}  

Approve if acceptable, flag issues otherwise.""",  
    output_key="quality_status"  
)  

# 阶段 6:发货(取决于质量审批)  
shipping_agent = LlmAgent(  
    name="shipping_agent",  
    model="gemini-3-flash-preview",  
    instruction="""Schedule shipping for the approved order.  
Order: {parsed_order}  
Production: {production_schedule}  
Quality: {quality_status}  

Create a shipping manifest.""",  
    output_key="shipping_manifest"  
)  

# 阶段 7:确认  
confirmation_agent = LlmAgent(  
    name="confirmation_agent",  
    model="gemini-3-flash-preview",  
    instruction="""Generate a confirmation message for the customer.  
Order: {parsed_order}  
Pricing: {pricing_info}  
Shipping: {shipping_manifest}  

Write a professional confirmation email.""",  
    output_key="confirmation"  
)  

# 构建完整的流水线  
order_to_delivery = SequentialAgent(  
    name="order_to_delivery_pipeline",  
    sub_agents=[  
        order_receiver,  
        evaluation,  
        approval_agent,  
        production_scheduler,  
        quality_checker,  
        shipping_agent,  
        confirmation_agent  
    ]  
)  

# 运行  
runner = Runner(  
    agent=order_to_delivery,  
    session_service=InMemorySessionService()  
)  

customer_request = """  
I'd like to order 100 units of SKU-001.  
I need delivery by March 28.  
Contact me at alice@acme.com.  
"""  

result = runner.send_message(  
    session_id="order-2026-0847",  
    message=customer_request  
)  

print(result)  
 # 输出完整的确认信息,追踪经过所有 7 个阶段的过程

状态经由占位符

{parsed_order}

{inventory_check}

等在各阶段间传递;ParallelAgent 让库存检查和定价查询同时进行;每个智能体只负责一个决策或动作;整个流程靠组合声明,而非命令式代码串联。

CustomAgent:预定义模式覆盖不到的场景

三种模式各有边界。当业务逻辑涉及条件分支或异常恢复时,CustomAgent 提供完全自定义的执行控制:

 from google.adk.agents import CustomAgent, LlmAgent  

class SmartRouter(CustomAgent):  
    """根据复杂度将订单路由到不同的履行路径。"""  

    def __init__(self):  
        self.simple_path = SequentialAgent(  
            name="simple_fulfillment",  
            sub_agents=[...simple agents...]  
        )  
        self.complex_path = SequentialAgent(  
            name="complex_fulfillment",  
            sub_agents=[...complex agents...]  
        )  
        self.router = LlmAgent(  
            name="order_router",  
            instruction="""Analyze the order and decide: SIMPLE or COMPLEX.  
Order: {order}  

Simple orders: standard items, normal quantities, no customization.  
Complex orders: custom requests, bulk, integration required."""  
        )  

    async def execute(self, session, context):  
        """自定义执行逻辑。"""  
        # 运行路由器  
        router_output = await self.router.execute(session, context)  

        # 根据决策进行分支  
        if "SIMPLE" in router_output:  
            result = await self.simple_path.execute(session, context)  
        else:  
            result = await self.complex_path.execute(session, context)  

         return result

上面的 SmartRouter 先用一个 LLM 判断订单复杂度,再根据判断结果将订单分发到两条不同的履行路径。条件分支、错误恢复这类需求都可以在 execute() 方法中自由实现。

编排示意图:三种模式总览


Custom:自行实现 execute() 方法,执行逻辑完全由开发者控制。

总结

以上构建的是一家数字化公司——七个智能体,各有分工,经由结构化状态传递工作,没有胶水代码,没有命令式编排。

但一个现实摆在面前:整个体系仍然是静态的。组织架构在定义时就已固定。下一个阶段的方向是动态编排——智能体按需创建团队、分配角色、根据负载重新组织协作拓扑。

基础已经搭好,接下来要做的事情更有意思。

https://avoid.overfit.cn/post/2fc744264a4f455782f15036922bdc5b

by Matteo Gazzurelli

目录
相关文章
|
25天前
|
人工智能 自动驾驶 安全
AI时代程序员必看!揭秘Harness Engineerin
当AI批量写代码,程序员会失业吗?OpenAI实验显示:3名工程师+1500个AI智能体,5个月完成100万行代码——人类零编码!关键不在模型,而在“Harness Engineering”系统工程法:以规格书、质检台、工具架构建AI“自动驾驶”体系,重塑程序员为架构师、规则者与工具锻造师。
|
26天前
|
缓存 Prometheus Cloud Native
从零构建 Mini-vLLM:KV-Cache、动态批处理与分布式推理全流程
Mini-vLLM 是一个从零打造的高效推理引擎,直击 HuggingFace `.generate()` 的 O(N²) 注意力瓶颈。通过手动实现 KV 缓存、动态批处理、gRPC 通信、Prometheus/Grafana 可观测性、分布式多 worker 架构及 Docker 容器化,显著提升吞吐与延迟。纯 CPU 下达 1307+ req/s,目标是真正理解而非复用轮子。
168 5
从零构建 Mini-vLLM:KV-Cache、动态批处理与分布式推理全流程
|
2月前
|
Python
5个让你爱不释手的Python冷门技巧
5个让你爱不释手的Python冷门技巧
306 144
|
2月前
|
数据库 决策智能
多 Agent 验证架构实战:从输出评分到过程验证
2026年生产级Agent系统最典型失败:多步流水线中错误静默累积,最终输出流畅却全错。本文详解四种验证模式——输出评分、Reflexion、对抗辩论与过程验证,揭示其适用场景、失效边界及真实成本(验证器用小模型可降本10倍),强调验证层是演示与落地的分水岭。
159 0
多 Agent 验证架构实战:从输出评分到过程验证
|
25天前
|
缓存 算法 数据可视化
大模型应用:本地数学模型:从导数求解到公式推导轻松搞定数学任务.74
Qwen2-Math-1.5B-Instruct是一款专精数学的轻量级大模型,仅1.5B参数,纯CPU即可流畅运行。它深耕代数、几何、概率等领域,支持分步解题、公式推导与通俗解析,输出规范易复用,适用于教学备课、作业辅导与数学科普。
208 8
大模型应用:本地数学模型:从导数求解到公式推导轻松搞定数学任务.74
|
24天前
|
人工智能 测试技术 C++
让AI更懂你:3个提示词技巧提升大模型回答质量
让AI更懂你:3个提示词技巧提升大模型回答质量
175 8
|
28天前
|
人工智能 缓存 固态存储
投机解码原理详解:小模型打草稿,大模型一次验证
生产环境中,推理成本远超训练——自回归解码受制于内存带宽墙,70B模型在H100上每token需700亿次计算。投机解码(2026年已成标配)用小模型“猜词+大模型并行验证”,严格保质提速2–2.5倍;SSD更进一步,复用大模型浅层自生成草稿、构建回滚树,接受率提升、显存零新增。vLLM已原生支持,开箱即用。
180 2
投机解码原理详解:小模型打草稿,大模型一次验证
|
25天前
|
人工智能
阿里云百炼Coding Plan售罄了怎么办?解决方法一次讲清,Lite停售,Pro怎么购买更省钱?
阿里云百炼Coding Plan Lite版已下架,Pro版200元/月限量售罄。每日9:30补货,建议定闹钟抢购。替代方案:①购AI大模型节省计划(低至4.5折);②开通百炼免费领7000万Tokens官方入口:https://t.aliyun.com/U/fPVHqY
|
24天前
|
人工智能 弹性计算 自然语言处理
阿里云轻量应用服务器部署OpenClaw,以及OpenClaw Web页面集成图文教程
本文介绍了在购买阿里云轻量应用服务器部署OpenClaw应用镜像的步骤、费用说明及配置流程,以及OpenClaw Web页面集成教程,包括如何配置OpenClaw、创建AI助手、实现Web页面集成等。此外,还解答了如何重启OpenClaw网关、查看端口号、更改调用模型等常见问题。通过本文,用户可快速掌握OpenClaw从本地部署到Web集成的完整路径。
|
23天前
|
数据采集 人工智能 缓存
ModelEngine思想落地指南:用“智能体 + 插件”构建可复用AI应用.76
ModelEngine是一种AI应用开发范式,通过角色化智能体分工、插件化工具集成与双模式(低代码+代码)开发,解决重复造轮子、流程碎片化、技术门槛高等痛点,实现高效、灵活、可复用的AI应用构建。
154 13