教程9.2:循环智能体——迭代计划优化器


文档摘要

教程 9.2:循环智能体——迭代计划优化器 您将学到的内容 循环智能体的组合:以循环方式依次执行子智能体 有状态的迭代:在每次迭代中持久化计数器和标志位 终止条件:达到最大迭代次数或当某个子智能体升级时停止 Streamlit Web 界面:用于运行迭代优化的交互式 UI 核心概念:带条件的 LoopAgent 根据 ADK 工作流智能体文档,LoopAgent 会在每次迭代中重复执行一组子智能体,并在迭代之间共享相同的上下文/状态。本教程演示了一个迭代计划优化器,它会在多个迭代中逐步改进计划,并在满足特定条件时停止。 终止条件:如果可选的 is reached, or if any sub-agent returns an with in its .

教程 9.2:循环智能体——迭代计划优化器

您将学到的内容

  • 循环智能体的组合:以循环方式依次执行子智能体
  • 有状态的迭代:在每次迭代中持久化计数器和标志位
  • 终止条件:达到最大迭代次数或当某个子智能体升级时停止
  • Streamlit Web 界面:用于运行迭代优化的交互式 UI

核心概念:带条件的 LoopAgent

根据 ADK 工作流智能体文档,LoopAgent 会在每次迭代中重复执行一组子智能体,并在迭代之间共享相同的上下文/状态。本教程演示了一个迭代计划优化器,它会在多个迭代中逐步改进计划,并在满足特定条件时停止。

Topic → LoopAgent → [Refine Plan] → [Increment Iteration] → [Check Completion] ↑ │ └──────────────────────────── Repeat until stop ─────────┘

终止条件:如果可选的 max_iterations is reached, or if any sub-agent returns an Event with escalate=True in its EventActions.

Context & State: The same InvocationContext and session.state are used across iterations, allowing values like iteration, target_iterations, and accepted 被设置为真,则循环会停止,以便持久化并控制循环流程。

项目结构

9_2_loop agent/ ├── agent.py # LoopAgent with 3 sub-agents and session-state control ├── app.py # Streamlit UI to run the loop refinement └── README.md # This documentation

开始使用

1. 安装依赖

cd "9_2_loop agent" pip install -r ../9_1_sequential_agent/requirements.txt

2. 配置环境

创建一个 .env 文件,并填入您的 Google API 密钥(或复用顺序示例中的密钥):

echo "GOOGLE_API_KEY=your_ai_studio_key_here" > .env

3. 运行 Streamlit 应用

streamlit run app.py

工作原理

  • plan_refiner (LlmAgent):在每次迭代中生成简洁且改进后的计划。
  • increment_iteration (BaseAgent):递增 session.state['iteration'].
  • check_completion (BaseAgent): Escalates (to stop) if accepted=True or iteration >= target_iterations.

The LoopAgent sequences these sub-agents on every iteration, persisting and updating state until a stop condition is met.

Session State Keys

  • topic: The subject being refined.
  • iteration: Current iteration counter.
  • target_iterations: Loop budget before stopping.
  • accepted: When set to True, the loop stops immediately.

Try It

  • Enter a topic (e.g., "AI-powered customer support platform launch plan").
  • Set 目标迭代次数 to 3–5.
  • Run and observe the final refined plan and run metadata.

ADK Concepts Demonstrated

  • LoopAgent pattern with sequential sub-agents.
  • Session state persistence across iterations.
  • Escalation-based termination with EventActions(escalate=True).
  • Runner + SessionService execution pattern.

Troubleshooting

  • Ensure GOOGLE_API_KEY is set in .env.
  • Run from the directory containing app.py
  • 如果您之前运行过该应用,将复用相同的会话 ID;更改话题或目标会相应更新状态。

关键要点

  • LoopAgent 可实现迭代优化的工作流。
  • 共享状态 允许复杂的控制信号在迭代之间累积。
  • 清晰、模块化的子智能体 使循环逻辑保持清晰且易于维护。

免责声明
本文档采用基于机器的 AI 翻译服务进行翻译。尽管我们力求准确,但请注意,自动翻译可能存在错误或不准确之处。应以原文语言版本的文档作为权威依据。如需获取关键信息,建议使用专业的人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。


发布者: 作者: 转发
评论区 (0)
U