Skip to content

循环智能体

LoopAgent

LoopAgent 是一种工作流智能体,它循环(即迭代)执行其子智能体。它_重复运行_一系列智能体,执行指定次数的迭代或直到满足终止条件。

当你的工作流涉及重复或迭代改进时,如修改代码,请使用 LoopAgent

示例

  • 你想构建一个可以生成食物图像的智能体,但有时当你想生成特定数量的物品(例如 5 个香蕉)时,它生成的图像中包含了不同数量的物品(例如一张有 7 个香蕉的图像)。你有两个工具:generate_imagecount_food_items。因为你想不断生成图像,直到它正确生成指定数量的物品,或者达到一定的迭代次数,所以你应该使用 LoopAgent 构建你的智能体。

与其他工作流智能体一样,LoopAgent 不是由 LLM 驱动的,因此它的执行方式是确定性的。也就是说,工作流智能体只关注它们的执行方式(即循环),而不是它们的内部逻辑;工作流智能体的工具或子智能体可能使用也可能不使用 LLM。

工作原理

当调用 LoopAgentrun_async() 方法时,它执行以下操作:

  1. 子智能体执行: 它_按顺序_遍历 sub_agents 列表。对于_每个_子智能体,它调用该智能体的 run_async() 方法。
  2. 终止检查:

    至关重要的是LoopAgent 本身_不_固有地决定何时停止循环。你_必须_实现一个终止机制以防止无限循环。常见的策略包括:

    • max_iterations:在 LoopAgent 中设置最大迭代次数。循环将在达到该迭代次数后终止
    • 来自子智能体的升级:设计一个或多个子智能体来评估条件(例如,"文档质量是否足够好?","是否已达成共识?")。如果满足条件,子智能体可以发出终止信号(例如,通过触发自定义事件、在共享上下文中设置标志,或返回特定值)。

循环智能体

完整示例:迭代文档改进

想象一个你想要迭代改进文档的场景:

  • 编写智能体: 一个生成或改进主题草稿的 LlmAgent
  • 评论智能体: 一个对草稿进行评论,识别需要改进的领域的 LlmAgent

    LoopAgent(sub_agents=[WriterAgent, CriticAgent], max_iterations=5)
    

在这个设置中,LoopAgent 将管理迭代过程。CriticAgent 可以被设计为在文档达到令人满意的质量水平时返回"STOP"信号,防止进一步迭代。或者,可以使用 max_iterations 参数将过程限制为固定数量的循环,或者可以实现外部逻辑来做出停止决定。循环将最多运行五次,确保迭代改进不会无限期继续。

完整代码
from google.adk.agents.loop_agent import LoopAgent
from google.adk.agents.llm_agent import LlmAgent
from google.genai import types
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner

# --- Constants ---
APP_NAME = "doc_writing_app"
USER_ID = "dev_user_01"
SESSION_ID = "session_01"
GEMINI_MODEL = "gemini-2.0-flash"

# --- State Keys ---
STATE_INITIAL_TOPIC = "quantum physics"
STATE_CURRENT_DOC = "current_document"
STATE_CRITICISM = "criticism"

writer_agent = LlmAgent(
    name="WriterAgent",
    model=GEMINI_MODEL,
    instruction=f"""
    You are a Creative Writer AI.
    Check the session state for '{STATE_CURRENT_DOC}'.
    If '{STATE_CURRENT_DOC}' does NOT exist or is empty, write a very short (1-2 sentence) story or document based on the topic in state key '{STATE_INITIAL_TOPIC}'.
    If '{STATE_CURRENT_DOC}' *already exists* and '{STATE_CRITICISM}', refine '{STATE_CURRENT_DOC}' according to the comments in '{STATE_CRITICISM}'."
    Output *only* the story or the exact pass-through message.
    """,
    description="Writes the initial document draft.",
    output_key=STATE_CURRENT_DOC # Saves output to state
)

# Critic Agent (LlmAgent)
critic_agent = LlmAgent(
    name="CriticAgent",
    model=GEMINI_MODEL,
    instruction=f"""
    You are a Constructive Critic AI.
    Review the document provided in the session state key '{STATE_CURRENT_DOC}'.
    Provide 1-2 brief suggestions for improvement (e.g., "Make it more exciting", "Add more detail").
    Output *only* the critique.
    """,
    description="Reviews the current document draft.",
    output_key=STATE_CRITICISM # Saves critique to state
)

# Create the LoopAgent
loop_agent = LoopAgent(
    name="LoopAgent", sub_agents=[writer_agent, critic_agent], max_iterations=5
)

# Session and Runner
session_service = InMemorySessionService()
session = session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
runner = Runner(agent=loop_agent, app_name=APP_NAME, session_service=session_service)

# Agent Interaction
def call_agent(query):
    content = types.Content(role='user', parts=[types.Part(text=query)])
    events = runner.run(user_id=USER_ID, session_id=SESSION_ID, new_message=content)

    for event in events:
        if event.is_final_response():
            final_response = event.content.parts[0].text
            print("Agent Response: ", final_response)

call_agent("execute")