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

单个智能体的专业化程度有上限,真正的工作需要团队:一个角色接收订单,一个检查库存,一个安排生产,一个验证质量。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

相关推荐
人生百态,人生如梦6 小时前
情感交互仿生人从技术到落地构想3——技术交流贴(2026.7)
人工智能·机器学习·人机交互·交互·具身智能
用户652238438116 小时前
为什么成熟的 LLM 应用,都把"后端地址"做成可切换的配置
人工智能
Aa99883346 小时前
AI视觉检测设备厂家的技术评估框架——以及AI视觉检测的检出边界与适用条件
人工智能
wuhanzhanhui6 小时前
当AI遇见储能!2026武汉国际数字能源产业与新型电力及储能技术展览会
人工智能·能源
赶紧写完去睡觉6 小时前
Anaconda 创建虚拟环境与使用
python·pycharm·conda
迷途呀6 小时前
Python:函数中的参数类型
开发语言·笔记·python·langchain·nlp
Tangyuewei6 小时前
给 AI 套上缰绳:Harness Engineering 是什么
人工智能
AI棒棒牛6 小时前
第11讲 | 目标检测任务:边界框、IoU、类别与置信度
人工智能·yolo·目标检测·yolo26
allione6 小时前
AI时代测试方向AI for Testing和Testing for AI
人工智能·ai测试
武子康6 小时前
GPT-Red:自动化红队如何形成 Agent 安全数据飞轮(4 个闭环 + 6 类评测指标 + 5 类风险误读)
人工智能·openai·agent