Google ADK Sequential Agents 指南 -- 五分钟构建智能代码开发流水线

302 阅读5分钟

深入学习Google ADK的Sequential Agents,通过构建一个完整的代码开发流水线(代码生成→代码审查→代码重构),掌握工作流代理的核心概念和实践技巧。从零开始,让你的AI Agent具备按序执行复杂任务的能力!

什么是 Sequential Agents

Sequential Agents(顺序工作流代理)是 Google ADK 中的一种工作流代理,它能够按照预定义的顺序执行多个子代理。这种设计模式特别适合需要严格执行顺序的任务场景。

想象一下,你需要构建一个智能代码开发助手:

  1. 🔧 代码生成代理 - 根据需求写出初始代码
  2. 👀 代码审查代理 - 检查代码质量和问题
  3. 代码重构代理 - 根据审查意见优化代码

这就是 Sequential Agents 的典型应用场景!每个步骤都必须按顺序执行,前一步的输出作为后一步的输入。

核心特点

  • 确定性执行:不依赖LLM决策,按固定顺序执行
  • 状态传递:通过 output_key 在代理间传递数据
  • 灵活组合:可以组合任意数量和类型的子代理
  • 严格顺序:保证执行的可预测性和可靠性

1. 环境准备

项目结构

根据官方规范,我们需要构建如下项目架构:

parent_folder/
    workflow_seq_agent/
        __init__.py
        agent.py
        .env

创建项目

请参考 # 5分钟入门Google ADK -- 从零构建你的第一个AI Agent,这里直接拷贝multi_tool_agent,然后替换agent.py为workflow agent代码即可

cp -r multi_tool_agent workflow_seq_agent

2. 构建代码开发流水线

核心代码实现

将以下代码复制到 workflow_seq_agent/agent.py

from google.adk.agents.llm_agent import LlmAgent
from google.adk.agents.sequential_agent import SequentialAgent

# Part of agent.py --> Follow https://google.github.io/adk-docs/get-started/quickstart/ to learn the setup

# --- 1. Define Sub-Agents for Each Pipeline Stage ---

# Code Writer Agent
# Takes the initial specification (from user query) and writes code.
code_writer_agent = LlmAgent(
    name="CodeWriterAgent",
    model="gemini-2.0-flash",
    # Change 3: Improved instruction
    instruction="""You are a Python Code Generator.
Based *only* on the user's request, write Python code that fulfills the requirement.
Output *only* the complete Python code block, enclosed in triple backticks (```python ... ```). 
Do not add any other text before or after the code block.
""",
    description="Writes initial Python code based on a specification.",
    output_key="generated_code" # Stores output in state['generated_code']
)

# Code Reviewer Agent
# Takes the code generated by the previous agent (read from state) and provides feedback.
code_reviewer_agent = LlmAgent(
    name="CodeReviewerAgent",
    model="gemini-2.0-flash",
    # Change 3: Improved instruction, correctly using state key injection
    instruction="""You are an expert Python Code Reviewer. 
    Your task is to provide constructive feedback on the provided code.

    **Code to Review:**
    ```python
    {generated_code}
    ```

**Review Criteria:**
1.  **Correctness:** Does the code work as intended? Are there logic errors?
2.  **Readability:** Is the code clear and easy to understand? Follows PEP 8 style guidelines?
3.  **Efficiency:** Is the code reasonably efficient? Any obvious performance bottlenecks?
4.  **Edge Cases:** Does the code handle potential edge cases or invalid inputs gracefully?
5.  **Best Practices:** Does the code follow common Python best practices?

**Output:**
Provide your feedback as a concise, bulleted list. Focus on the most important points for improvement.
If the code is excellent and requires no changes, simply state: "No major issues found."
Output *only* the review comments or the "No major issues" statement.
""",
    description="Reviews code and provides feedback.",
    output_key="review_comments", # Stores output in state['review_comments']
)


# Code Refactorer Agent
# Takes the original code and the review comments (read from state) and refactors the code.
code_refactorer_agent = LlmAgent(
    name="CodeRefactorerAgent",
    model="gemini-2.0-flash",
    # Change 3: Improved instruction, correctly using state key injection
    instruction="""You are a Python Code Refactoring AI.
Your goal is to improve the given Python code based on the provided review comments.

  **Original Code:**
  ```python
  {generated_code}

这个 agent.py 文件展示了一个代码开发流水线的完整实现,使用了 Google ADK 的 SequentialAgent 来按顺序执行三个AI代理:

  • CodeWriterAgent - 根据用户需求生成初始代码
  • CodeReviewerAgent - 审查代码并提供改进建议
  • CodeRefactorerAgent - 根据审查意见重构代码

每个代理的输出会通过 output_key 存储在状态中,供下一个代理使用。这种设计确保了代码开发的严格顺序:编写 → 审查 → 重构。

3. 工作原理深度解析

执行流程

graph TD
    A[用户输入需求] --> B[CodeWriterAgent]
    B --> C[生成代码存储到 state中的generated_code]
    C --> D[CodeReviewerAgent]
    D --> E[审查意见存储到 state中的review_comments]
    E --> F[CodeRefactorerAgent]
    F --> G[重构代码存储到 state中的refactored_code]
    G --> H[返回最终结果]

状态管理机制

Sequential Agent 通过状态传递实现数据流转:

  1. CodeWriterAgent 执行后,输出通过 output_key="generated_code" 存储
  2. CodeReviewerAgent 通过 {generated_code} 模板变量读取上一步结果
  3. CodeRefactorerAgent 同时读取 {generated_code}{review_comments} 两个状态

模板变量注入

ADK 自动将状态中的数据注入到指令模板中:

{generated_code}  # 自动从 state['generated_code'] 注入

{review_comments}  # 自动从 state['review_comments'] 注入

4. 运行和测试

启动Web界面

# 在 workflow_seq_agent 的父目录执行
adk web

测试用例

尝试以下测试场景:

用户输入:write a math caculator.

期望流程:

  1. 🔧 代码生成代理:生成计算器的函数
  2. 👀 代码审查代理:检查错误处理、边界情况等
  3. 代码重构代理:根据建议优化代码

6. 常见应用场景

文档处理流水线

doc_pipeline = SequentialAgent(
    sub_agents=[
        document_parser,      # 解析文档
        content_extractor,    # 提取关键信息  
        summary_generator,    # 生成摘要
        formatter            # 格式化输出
    ]
)

数据分析流水线

data_pipeline = SequentialAgent(
    sub_agents=[
        data_loader,         # 加载数据
        data_cleaner,        # 清洗数据
        data_analyzer,       # 分析数据
        report_generator     # 生成报告
    ]
)

内容创作流水线

content_pipeline = SequentialAgent(
    sub_agents=[
        topic_researcher,    # 主题研究
        outline_creator,     # 创建大纲
        content_writer,      # 撰写内容
        editor_reviewer      # 编辑审查
    ]
)

💡 最佳实践

1. 指令设计原则

  • 清晰明确:每个代理的职责要明确定义
  • 格式统一:输出格式要保持一致
  • 错误处理:考虑异常情况的处理

2. 状态管理

  • 键名规范:使用描述性的 output_key 名称
  • 数据结构:保持状态数据的结构化
  • 大小控制:避免在状态中存储过大的数据

3. 测试策略

  • 单元测试:分别测试每个子代理
  • 集成测试:测试整个流水线
  • 边界测试:测试异常输入和错误情况

🎉 总结

恭喜你掌握了 Google ADK Sequential Agents 的核心技能!🎊

你现在具备了:

  • ✅ Sequential Agents 的工作原理和设计模式
  • ✅ 构建复杂AI工作流的实践能力
  • ✅ 状态管理和数据流转的深度理解
  • ✅ 调试和优化 Sequential Agents 的方法技巧

Sequential Agents 为你开启了构建复杂AI系统的大门。通过合理的任务分解和代理组合,你可以构建出功能强大、逻辑清晰的AI应用。

下一步,尝试将这些概念应用到你的实际项目中,构建属于自己的智能工作流系统吧!🚀


参考资料:

希望本文对你有所帮助,想了解更多AI实践,关注我的同名公众号:),定期分享AI实战,一起探索AI的无限可能!