跳转到内容

循环模板工作流代理(Loop template workflow agent)

在 ADK 中得到支持。Python v0.1.0TypeScript v0.2.0Go v0.1.0Java v0.2.0Kotlin v0.1.0

The LoopAgent `class` 是一个……(这里的“……”需要根据上下文来填写具体内容。例如,它可以表示“类(class)是一种编程概念”或“`class` 是 Python 中的一个关键字”等。) 模板工作流程(Template Workflow) 该代理会以循环的方式执行其子代理(sub-agents),持续指定的迭代次数,或者直到满足某个终止条件为止。请使用该代理。 LoopAgent 当你的工作流程涉及重复性操作或迭代性改进(例如修改代码或文档)时,与其他基于模板的工作流程类似,该流程的执行方式也是相同的。 LoopAgent 该对象不由人工智能模型控制,其子代理的执行方式是确定性的(即每次执行的结果都是相同的)。定义在循环中的子代理可能会使用人工智能模型,也可能不会使用;不过这些子代理的整个执行过程最终仍由该系统进行管理。 LoopAgent 你定义的对象。

已弃用:请使用基于图形的工作流程(graph-based workflows)。

在 ADK 的 Python、TypeScript、Go 和 Kotlin 语言中,模板化的工作流程已被更灵活的工作流程结构所取代。 基于图的工作流程(graph-based workflows) 和 动态工作流程(Dynamic Workflows).

示例场景:

你想要构建一个能够生成食物图片的智能代理(agent),但有时候当你希望生成特定数量的食物(例如 7 个香蕉)时,该代理生成的图片中实际显示的香蕉数量却与预期不同。你手头有两个工具: Generate Image, Count Food Items如果你的目标是持续生成图像,直到生成出指定数量的目标对象为止,或者在进行了一定次数的迭代后停止生成,那么你可以使用以下方法来构建你的智能代理(agent): LoopAgent workflow.

它是如何工作的?

当……的时候 LoopAgent's Run Async 当该方法被调用时,它会执行以下操作:

  1. 子代理执行(Sub-Agent Execution): 它会遍历子代理(Sub Agents)的列表。 (用于表示某事按计划或预期进行)顺利地,正常地. 用于 每个;各自 子代理会调用代理的相应功能(或方法)。 Run Async method.
  2. 终止检查(Termination Check):

    至关重要的是……,the LoopAgent 它自己会(完成某件事)。 不;并非 必须自己决定何时停止循环。 必须;应当 需要实现一种终止机制,以防止程序陷入无限循环。常见的策略包括:

    • 最大迭代次数:设置迭代的最大次数。 LoopAgent. 循环将在完成那么多次迭代后终止。在 Python 中, max_iterations 默认值为…… None这意味着循环只有在情况升级(即问题变得更加严重)时才会停止。
    • 从次级代理(sub-agent)升级处理问题(Escalation from sub-agent)设计一个或多个子代理来评估某个条件(例如:“文档的质量是否足够好?”、“是否已经达成共识?”)。如果条件得到满足,子代理会通过发送一个事件来表示任务已完成;该事件会触发相应的后续操作。 escalate 将其值设置为 `True`。在 Python 中,自定义代理(custom agent)会生成相应的结果。 Event 使用(with) actions=EventActions(escalate=True)当回调函数被设置时(while a callback is set), callback_context.actions.escalate = True 以及一套工具集 tool_context.actions.escalate = True. 内置的 exit_loop 这些工具会自动为你标记出需要关注的内容(或错误等)。

Loop Agent

完整示例:迭代式文档改进

想象这样一个场景:你需要不断地对一份文档进行修改和优化(即对其进行迭代性的改进)。

  • Writer Agent: An LlmAgent 该工具能够根据某个主题生成或完善相应的草稿内容。
  • Critic Agent: An LlmAgent 该报告对草案进行了批评,并指出了需要改进的地方。

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

在这种配置中, LoopAgent 将负责管理这个迭代过程。 CriticAgent 可能是;也许会 假设我们有一种用于处理问题升级(即问题从初级阶段升级到更高级别、需要更多资源或更复杂解决方案的阶段)的工具…… exit_loop当文档的质量达到满意的标准时,系统会调用该功能一次。这会阻止进一步的迭代过程。或者,也可以选择另一种方法…… max_iterations 可以使用该参数将进程限制在固定的循环次数内,或者可以实现外部逻辑来决定何时停止进程。 这个循环最多只会运行五次。这样可以确保迭代优化过程不会无限期地持续下去。

完整代码
from google.adk.agents import LoopAgent, LlmAgent, SequentialAgent
from google.adk.tools.tool_context import ToolContext
from google.adk.agents.callback_context import CallbackContext

# --- Constants ---
GEMINI_MODEL = "gemini-2.5-flash"

# --- State Keys ---
STATE_CURRENT_DOC = "current_document"
STATE_CRITICISM = "criticism"
# Define the exact phrase the Critic should use to signal completion
COMPLETION_PHRASE = "No major issues found."

# --- Tool Definition ---
def exit_loop(tool_context: ToolContext):
    """Call this function ONLY when the critique indicates no further changes are needed, signaling the iterative process should end."""
    print(f"  [Tool Call] exit_loop triggered by {tool_context.agent_name}")
    tool_context.actions.escalate = True
    tool_context.actions.skip_summarization = True
    # Return empty dict as tools should typically return JSON-serializable output
    return {}

# --- Before Agent Callback ---
def update_initial_topic_state(callback_context: CallbackContext):
    """Ensure 'initial_topic' is set in state before pipeline starts."""
    callback_context.state['initial_topic'] = callback_context.state.get('initial_topic', 'a robot developing unexpected emotions')

# --- Agent Definitions ---

# STEP 1: Initial Writer Agent (Runs ONCE at the beginning)
initial_writer_agent = LlmAgent(
    name="InitialWriterAgent",
    model=GEMINI_MODEL,
    include_contents='none',
    instruction=f"""
    You are a Creative Writing Assistant tasked with starting a story.
    Write a *very basic* first draft of a short story (just 1-2 simple sentences).
    Keep it plain and minimal - do NOT add descriptive language yet.
    Topic: {{initial_topic}}

    Output *only* the story/document text. Do not add introductions or explanations.
    """,
    description="Writes the initial document draft based on the topic, aiming for some initial substance.",
    output_key=STATE_CURRENT_DOC
)

# STEP 2a: Critic Agent (Inside the Refinement Loop)
critic_agent_in_loop = LlmAgent(
    name="CriticAgent",
    model=GEMINI_MODEL,
    include_contents='none',
    instruction=f"""
    You are a Constructive Critic AI reviewing a short story draft.

    **Document to Review:**
    ```
    {{current_document}}
    ```

    **Completion Criteria (ALL must be met):**
    1. At least 4 sentences long
    2. Has a clear beginning, middle, and end
    3. Includes at least one descriptive detail (sensory or emotional)

    **Task:**
    Check the document against the criteria above.

    IF any criteria is NOT met, provide specific feedback on what to add or improve.
    Output *only* the critique text.

    IF ALL criteria are met, respond *exactly* with: "{COMPLETION_PHRASE}"
    """,
    description="Reviews the current draft, providing critique if clear improvements are needed, otherwise signals completion.",
    output_key=STATE_CRITICISM
)

# STEP 2b: Refiner/Exiter Agent (Inside the Refinement Loop)
refiner_agent_in_loop = LlmAgent(
    name="RefinerAgent",
    model=GEMINI_MODEL,
    # Relies solely on state via placeholders
    include_contents='none',
    instruction=f"""
    You are a Creative Writing Assistant refining a document based on feedback OR exiting the process.
    **Current Document:**
    ```
    {{current_document}}
    ```
    **Critique/Suggestions:**
    {{criticism}}

    **Task:**
    Analyze the 'Critique/Suggestions'.
    IF the critique is *exactly* "{COMPLETION_PHRASE}":
    You MUST call the 'exit_loop' function. Do not output any text.
    ELSE (the critique contains actionable feedback):
    Carefully apply the suggestions to improve the 'Current Document'. Output *only* the refined document text.

    Do not add explanations. Either output the refined document OR call the exit_loop function.
    """,
    description="Refines the document based on critique, or calls exit_loop if critique indicates completion.",
    tools=[exit_loop], # Provide the exit_loop tool
    output_key=STATE_CURRENT_DOC # Overwrites state['current_document'] with the refined version
)

# STEP 2: Refinement Loop Agent
refinement_loop = LoopAgent(
    name="RefinementLoop",
    # Agent order is crucial: Critique first, then Refine/Exit
    sub_agents=[
        critic_agent_in_loop,
        refiner_agent_in_loop,
    ],
    max_iterations=5 # Limit loops
)

# STEP 3: Overall Sequential Pipeline
# For ADK tools compatibility, the root agent must be named `root_agent`
root_agent = SequentialAgent(
    name="IterativeWritingPipeline",
    sub_agents=[
        initial_writer_agent, # Run first to create initial doc
        refinement_loop       # Then run the critique/refine loop
    ],
    before_agent_callback=update_initial_topic_state, # set initial topic in state
    description="Writes an initial document and then iteratively refines it with critique using an exit tool."
)
// Part of agent.ts --> Follow https://adk.dev/get-started/ to learn the setup

import { LoopAgent, LlmAgent, SequentialAgent, FunctionTool } from '@google/adk';
import { z } from 'zod';

// --- Constants ---
const GEMINI_MODEL = "gemini-2.5-flash";
const STATE_INITIAL_TOPIC = "initial_topic";

// --- State Keys ---
const STATE_CURRENT_DOC = "current_document";
const STATE_CRITICISM = "criticism";
// Define the exact phrase the Critic should use to signal completion
const COMPLETION_PHRASE = "No major issues found.";

// --- Tool Definition ---
const exitLoopTool = new FunctionTool({
    name: 'exit_loop',
    description: 'Call this function ONLY when the critique indicates no further changes are needed, signaling the iterative process should end.',
    parameters: z.object({}),
    execute: (input, context) => {
        if (context) {
            console.log(`  [Tool Call] exit_loop triggered by ${context.agentName} with input: ${input}`);
            context.actions.escalate = true;
        }
        return {};
    },
});

// --- Agent Definitions ---

// STEP 1: Initial Writer Agent (Runs ONCE at the beginning)
const initialWriterAgent = new LlmAgent({
    name: "InitialWriterAgent",
    model: GEMINI_MODEL,
    includeContents: 'none',
    // MODIFIED Instruction: Ask for a slightly more developed start
    instruction: `You are a Creative Writing Assistant tasked with starting a story.
    Write the *first draft* of a short story (aim for 2-4 sentences).
    Base the content *only* on the topic provided below. Try to introduce a specific element (like a character, a setting detail, or a starting action) to make it engaging.
    Topic: {{${STATE_INITIAL_TOPIC}}}

    Output *only* the story/document text. Do not add introductions or explanations.
    `,
    description: "Writes the initial document draft based on the topic, aiming for some initial substance.",
    outputKey: STATE_CURRENT_DOC
});

// STEP 2a: Critic Agent (Inside the Refinement Loop)
const criticAgentInLoop = new LlmAgent({
    name: "CriticAgent",
    model: GEMINI_MODEL,
    includeContents: 'none',
    // MODIFIED Instruction: More nuanced completion criteria, look for clear improvement paths.
    instruction: `You are a Constructive Critic AI reviewing a short document draft (typically 2-6 sentences). Your goal is balanced feedback.

    **Document to Review:**

    {{current_document}}


    **Task:**
    Review the document for clarity, engagement, and basic coherence according to the initial topic (if known).

    IF you identify 1-2 *clear and actionable* ways the document could be improved to better capture the topic or enhance reader engagement (e.g., "Needs a stronger opening sentence", "Clarify the character's goal"):
    Provide these specific suggestions concisely. Output *only* the critique text.

    ELSE IF the document is coherent, addresses the topic adequately for its length, and has no glaring errors or obvious omissions:
    Respond *exactly* with the phrase "${COMPLETION_PHRASE}" and nothing else. It doesn't need to be perfect, just functionally complete for this stage. Avoid suggesting purely subjective stylistic preferences if the core is sound.

    Do not add explanations. Output only the critique OR the exact completion.
`,
    description: "Reviews the current draft, providing critique if clear improvements are needed, otherwise signals completion.",
    outputKey: STATE_CRITICISM
});


// STEP 2b: Refiner/Exiter Agent (Inside the Refinement Loop)
const refinerAgentInLoop = new LlmAgent({
    name: "RefinerAgent",
    model: GEMINI_MODEL,
    // Relies solely on state via placeholders
    includeContents: 'none',
    instruction: `You are a Creative Writing Assistant refining a document based on feedback OR exiting the process.
    **Current Document:**

    {{current_document}}

    **Critique/Suggestions:**
    {{criticism}}

    **Task:**
    Analyze the 'Critique/Suggestions'.
    IF the critique is *exactly* "${COMPLETION_PHRASE}":
    You MUST call the 'exit_loop' function. Do not output any text.
    ELSE (the critique contains actionable feedback):
    Carefully apply the suggestions to improve the 'Current Document'. Output *only* the refined document text.

    Do not add explanations. Either output the refined document OR call the exit_loop function.
`,
    tools: [exitLoopTool],
    description: "Refines the document based on critique, or calls exit_loop if critique indicates completion.",
    outputKey: STATE_CURRENT_DOC
});


// STEP 2: Refinement Loop Agent
const refinementLoop = new LoopAgent({
    name: "RefinementLoop",
    // Agent order is crucial: Critique first, then Refine/Exit
    subAgents: [
        criticAgentInLoop,
        refinerAgentInLoop,
    ],
    maxIterations: 5 // Limit loops
});

// STEP 3: Overall Sequential Pipeline
// For ADK tools compatibility, the root agent must be named `root_agent`
export const rootAgent = new SequentialAgent({
    name: "IterativeWritingPipeline",
    subAgents: [
        initialWriterAgent, // Run first to create initial doc
        refinementLoop       // Then run the critique/refine loop
    ],
    description: "Writes an initial document and then iteratively refines it with critique using an exit tool."
});
// ExitLoopArgs defines the (empty) arguments for the ExitLoop tool.
type ExitLoopArgs struct{}

// ExitLoopResults defines the output of the ExitLoop tool.
type ExitLoopResults struct{}

// ExitLoop is a tool that signals the loop to terminate by setting Escalate to true.
func ExitLoop(ctx agent.Context, input ExitLoopArgs) (ExitLoopResults, error) {
    fmt.Printf("[Tool Call] exitLoop triggered by %s \n", ctx.AgentName())
    ctx.Actions().Escalate = true
    return ExitLoopResults{}, nil
}

func main() {
    ctx := context.Background()

    if err := runAgent(ctx, "Write a document about a cat"); err != nil {
        log.Fatalf("Agent execution failed: %v", err)
    }
}

func runAgent(ctx context.Context, prompt string) error {
    model, err := gemini.NewModel(ctx, modelName, &genai.ClientConfig{})
    if err != nil {
        return fmt.Errorf("failed to create model: %v", err)
    }

    // STEP 1: Initial Writer Agent (Runs ONCE at the beginning)
    initialWriterAgent, err := llmagent.New(llmagent.Config{
        Name:        "InitialWriterAgent",
        Model:       model,
        Description: "Writes the initial document draft based on the topic.",
        Instruction: `You are a Creative Writing Assistant tasked with starting a story.
Write the *first draft* of a short story (aim for 2-4 sentences).
Base the content *only* on the topic provided in the user's prompt.
Output *only* the story/document text. Do not add introductions or explanations.`,
        OutputKey: stateDoc,
    })
    if err != nil {
        return fmt.Errorf("failed to create initial writer agent: %v", err)
    }

    // STEP 2a: Critic Agent (Inside the Refinement Loop)
    criticAgentInLoop, err := llmagent.New(llmagent.Config{
        Name:        "CriticAgent",
        Model:       model,
        Description: "Reviews the current draft, providing critique or signaling completion.",
        Instruction: fmt.Sprintf(`You are a Constructive Critic AI reviewing a short document draft.
**Document to Review:**
"""
{%s}
"""
**Task:**
Review the document.
IF you identify 1-2 *clear and actionable* ways it could be improved:
Provide these specific suggestions concisely. Output *only* the critique text.
ELSE IF the document is coherent and addresses the topic adequately:
Respond *exactly* with the phrase "%s" and nothing else.`, stateDoc, donePhrase),
        OutputKey: stateCrit,
    })
    if err != nil {
        return fmt.Errorf("failed to create critic agent: %v", err)
    }

    exitLoopTool, err := functiontool.New(
        functiontool.Config{
            Name:        "exitLoop",
            Description: "Call this function ONLY when the critique indicates no further changes are needed.",
        },
        ExitLoop,
    )
    if err != nil {
        return fmt.Errorf("failed to create exit loop tool: %v", err)
    }

    // STEP 2b: Refiner/Exiter Agent (Inside the Refinement Loop)
    refinerAgentInLoop, err := llmagent.New(llmagent.Config{
        Name:  "RefinerAgent",
        Model: model,
        Instruction: fmt.Sprintf(`You are a Creative Writing Assistant refining a document based on feedback OR exiting the process.
**Current Document:**

"""
{%s}
"""

**Critique/Suggestions:**
{%s}
**Task:**
Analyze the 'Critique/Suggestions'.
IF the critique is *exactly* "%s":
You MUST call the 'exitLoop' function. Do not output any text.
ELSE (the critique contains actionable feedback):
Carefully apply the suggestions to improve the 'Current Document'. Output *only* the refined document text.`, stateDoc, stateCrit, donePhrase),
        Description: "Refines the document based on critique, or calls exitLoop if critique indicates completion.",
        Tools:       []tool.Tool{exitLoopTool},
        OutputKey:   stateDoc,
    })
    if err != nil {
        return fmt.Errorf("failed to create refiner agent: %v", err)
    }

    // STEP 2: Refinement Loop Agent
    refinementLoop, err := loopagent.New(loopagent.Config{
        AgentConfig: agent.Config{
            Name:      "RefinementLoop",
            SubAgents: []agent.Agent{criticAgentInLoop, refinerAgentInLoop},
        },
        MaxIterations: 5,
    })
    if err != nil {
        return fmt.Errorf("failed to create loop agent: %v", err)
    }

    // STEP 3: Overall Sequential Pipeline
    iterativeWriterAgent, err := sequentialagent.New(sequentialagent.Config{
        AgentConfig: agent.Config{
            Name:      appName,
            SubAgents: []agent.Agent{initialWriterAgent, refinementLoop},
        },
    })
    if err != nil {
        return fmt.Errorf("failed to create sequential agent pipeline: %v", err)
    }
import static com.google.adk.agents.LlmAgent.IncludeContents.NONE;

import com.google.adk.agents.LlmAgent;
import com.google.adk.agents.LoopAgent;
import com.google.adk.agents.SequentialAgent;
import com.google.adk.events.Event;
import com.google.adk.runner.InMemoryRunner;
import com.google.adk.sessions.Session;
import com.google.adk.tools.Annotations.Schema;
import com.google.adk.tools.FunctionTool;
import com.google.adk.tools.ToolContext;
import com.google.genai.types.Content;
import com.google.genai.types.Part;
import io.reactivex.rxjava3.core.Flowable;
import java.util.Map;

public class LoopAgentExample {

  // --- Constants ---
  private static final String APP_NAME = "IterativeWritingPipeline";
  private static final String USER_ID = "test_user_456";
  private static final String MODEL_NAME = "gemini-2.0-flash";

  // --- State Keys ---
  private static final String STATE_CURRENT_DOC = "current_document";
  private static final String STATE_CRITICISM = "criticism";

  public static void main(String[] args) {
    LoopAgentExample loopAgentExample = new LoopAgentExample();
    loopAgentExample.runAgent("Write a document about a cat");
  }

  // --- Tool Definition ---
  @Schema(
      description =
          "Call this function ONLY when the critique indicates no further changes are needed,"
              + " signaling the iterative process should end.")
  public static Map<String, Object> exitLoop(@Schema(name = "toolContext") ToolContext toolContext) {
    System.out.printf("[Tool Call] exitLoop triggered by %s \n", toolContext.agentName());
    toolContext.actions().setEscalate(true);
    //  Return empty dict as tools should typically return JSON-serializable output
    return Map.of();
  }

  // --- Agent Definitions ---
  public void runAgent(String prompt) {
    // STEP 1: Initial Writer Agent (Runs ONCE at the beginning)
    LlmAgent initialWriterAgent =
        LlmAgent.builder()
            .model(MODEL_NAME)
            .name("InitialWriterAgent")
            .description(
                "Writes the initial document draft based on the topic, aiming for some initial"
                    + " substance.")
            .instruction(
                """
                    You are a Creative Writing Assistant tasked with starting a story.
                    Write the *first draft* of a short story (aim for 2-4 sentences).
                    Base the content *only* on the topic provided below. Try to introduce a specific element (like a character, a setting detail, or a starting action) to make it engaging.

                    Output *only* the story/document text. Do not add introductions or explanations.
                """)
            .outputKey(STATE_CURRENT_DOC)
            .includeContents(NONE)
            .build();

    // STEP 2a: Critic Agent (Inside the Refinement Loop)
    LlmAgent criticAgentInLoop =
        LlmAgent.builder()
            .model(MODEL_NAME)
            .name("CriticAgent")
            .description(
                "Reviews the current draft, providing critique if clear improvements are needed,"
                    + " otherwise signals completion.")
            .instruction(
                """
                    You are a Constructive Critic AI reviewing a short document draft (typically 2-6 sentences). Your goal is balanced feedback.

                    **Document to Review:**
                    ```
                    {{current_document}}
                    ```

                    **Task:**
                    Review the document for clarity, engagement, and basic coherence according to the initial topic (if known).

                    IF you identify 1-2 *clear and actionable* ways the document could be improved to better capture the topic or enhance reader engagement (e.g., "Needs a stronger opening sentence", "Clarify the character's goal"):
                    Provide these specific suggestions concisely. Output *only* the critique text.

                    ELSE IF the document is coherent, addresses the topic adequately for its length, and has no glaring errors or obvious omissions:
                    Respond *exactly* with the phrase "No major issues found." and nothing else. It doesn't need to be perfect, just functionally complete for this stage. Avoid suggesting purely subjective stylistic preferences if the core is sound.

                    Do not add explanations. Output only the critique OR the exact completion phrase.
                    """)
            .outputKey(STATE_CRITICISM)
            .includeContents(NONE)
            .build();

    // STEP 2b: Refiner/Exiter Agent (Inside the Refinement Loop)
    LlmAgent refinerAgentInLoop =
        LlmAgent.builder()
            .model(MODEL_NAME)
            .name("RefinerAgent")
            .description(
                "Refines the document based on critique, or calls exitLoop if critique indicates"
                    + " completion.")
            .instruction(
                """
                    You are a Creative Writing Assistant refining a document based on feedback OR exiting the process.
                    **Current Document:**
                    ```
                    {{current_document}}
                    ```
                    **Critique/Suggestions:**
                    {{criticism}}

                    **Task:**
                    Analyze the 'Critique/Suggestions'.
                    IF the critique is *exactly* "No major issues found.":
                    You MUST call the 'exitLoop' function. Do not output any text.
                    ELSE (the critique contains actionable feedback):
                    Carefully apply the suggestions to improve the 'Current Document'. Output *only* the refined document text.

                    Do not add explanations. Either output the refined document OR call the exitLoop function.
                """)
            .outputKey(STATE_CURRENT_DOC)
            .includeContents(NONE)
            .tools(FunctionTool.create(LoopAgentExample.class, "exitLoop"))
            .build();

    // STEP 2: Refinement Loop Agent
    LoopAgent refinementLoop =
        LoopAgent.builder()
            .name("RefinementLoop")
            .description("Repeatedly refines the document with critique and then exits.")
            .subAgents(criticAgentInLoop, refinerAgentInLoop)
            .maxIterations(5)
            .build();

    // STEP 3: Overall Sequential Pipeline
    SequentialAgent iterativeWriterAgent =
        SequentialAgent.builder()
            .name(APP_NAME)
            .description(
                "Writes an initial document and then iteratively refines it with critique using an"
                    + " exit tool.")
            .subAgents(initialWriterAgent, refinementLoop)
            .build();

    // Create an InMemoryRunner
    InMemoryRunner runner = new InMemoryRunner(iterativeWriterAgent, APP_NAME);
    // InMemoryRunner automatically creates a session service. Create a session using the service
    Session session = runner.sessionService().createSession(APP_NAME, USER_ID).blockingGet();
    Content userMessage = Content.fromParts(Part.fromText(prompt));

    // Run the agent
    Flowable<Event> eventStream = runner.runAsync(USER_ID, session.id(), userMessage);

    // Stream event response
    eventStream.blockingForEach(
        event -> {
          if (event.finalResponse()) {
            System.out.println(event.stringifyContent());
          }
        });
  }
}
import com.google.adk.kt.agents.Instruction
import com.google.adk.kt.agents.LlmAgent
import com.google.adk.kt.agents.LlmAgent.IncludeContents
import com.google.adk.kt.agents.LoopAgent
import com.google.adk.kt.agents.SequentialAgent
import com.google.adk.kt.annotations.Tool
import com.google.adk.kt.callbacks.BeforeAgentCallback
import com.google.adk.kt.callbacks.CallbackChoice
import com.google.adk.kt.models.Gemini
import com.google.adk.kt.tools.ToolContext

// --- Constants ---
private const val GEMINI_MODEL = "gemini-flash-latest"

// --- State Keys ---
const val STATE_CURRENT_DOC = "current_document"
const val STATE_CRITICISM = "criticism"

// Define the exact phrase the Critic should use to signal completion
const val COMPLETION_PHRASE = "No major issues found."

// --- Tool Definition ---
class LoopTools {
    /**
     * Call this function ONLY when the critique indicates no further changes are needed, signaling
     * the iterative process should end.
     */
    @Tool(name = "exit_loop")
    fun exitLoop(context: ToolContext): Map<String, String> {
        println("  [Tool Call] exit_loop triggered by ${context.agentName}")
        context.actions.escalate = true
        context.actions.skipSummarization = true
        // Return empty map as tools should typically return JSON-serializable output
        return emptyMap()
    }
}

// --- Before Agent Callback ---
// Ensure 'initial_topic' is set in state before pipeline starts.
val updateInitialTopicState =
    BeforeAgentCallback { context ->
        context.updateState(
            "initial_topic",
            context.state["initial_topic"] ?: "a robot developing unexpected emotions",
        )
        CallbackChoice.Continue(context.eventActions)
    }

// --- Agent Definitions ---
val model = Gemini(name = GEMINI_MODEL)

// STEP 1: Initial Writer Agent (Runs ONCE at the beginning)
val initialWriterAgent =
    LlmAgent(
        name = "InitialWriterAgent",
        model = model,
        includeContents = IncludeContents.NONE,
        instruction =
            Instruction(
                """
                You are a Creative Writing Assistant tasked with starting a story.
                Write a *very basic* first draft of a short story (just 1-2 simple sentences).
                Keep it plain and minimal - do NOT add descriptive language yet.
                Topic: {initial_topic}

                Output *only* the story/document text. Do not add introductions or explanations.
                """.trimIndent(),
            ),
        description =
            "Writes the initial document draft based on the topic, aiming for some initial " +
                "substance.",
        outputKey = STATE_CURRENT_DOC,
    )

// STEP 2a: Critic Agent (Inside the Refinement Loop)
val criticAgentInLoop =
    LlmAgent(
        name = "CriticAgent",
        model = model,
        includeContents = IncludeContents.NONE,
        instruction =
            Instruction(
                """
                You are a Constructive Critic AI reviewing a short story draft.

                **Document to Review:**
                ```
                {current_document}
                ```

                **Completion Criteria (ALL must be met):**
                1. At least 4 sentences long
                2. Has a clear beginning, middle, and end
                3. Includes at least one descriptive detail (sensory or emotional)

                **Task:**
                Check the document against the criteria above.

                IF any criteria is NOT met, provide specific feedback on what to add or improve.
                Output *only* the critique text.

                IF ALL criteria are met, respond *exactly* with: "$COMPLETION_PHRASE"
                """.trimIndent(),
            ),
        description =
            "Reviews the current draft, providing critique if clear improvements are needed, " +
                "otherwise signals completion.",
        outputKey = STATE_CRITICISM,
    )

// STEP 2b: Refiner/Exiter Agent (Inside the Refinement Loop)
val refinerAgentInLoop =
    LlmAgent(
        name = "RefinerAgent",
        model = model,
        // Relies solely on state via placeholders
        includeContents = IncludeContents.NONE,
        instruction =
            Instruction(
                """
                You are a Creative Writing Assistant refining a document based on feedback OR exiting the process.
                **Current Document:**
                ```
                {current_document}
                ```
                **Critique/Suggestions:**
                {criticism}

                **Task:**
                Analyze the 'Critique/Suggestions'.
                IF the critique is *exactly* "$COMPLETION_PHRASE":
                You MUST call the 'exit_loop' function. Do not output any text.
                ELSE (the critique contains actionable feedback):
                Carefully apply the suggestions to improve the 'Current Document'. Output *only* the refined document text.

                Do not add explanations. Either output the refined document OR call the exit_loop function.
                """.trimIndent(),
            ),
        description =
            "Refines the document based on critique, or calls exit_loop if critique indicates " +
                "completion.",
        // Provide the exit_loop tool
        tools = LoopTools().generatedTools(),
        // Overwrites state['current_document'] with the refined version
        outputKey = STATE_CURRENT_DOC,
    )

// STEP 2: Refinement Loop Agent
val refinementLoop =
    LoopAgent(
        name = "RefinementLoop",
        // Agent order is crucial: Critique first, then Refine/Exit
        subAgents =
            listOf(
                criticAgentInLoop,
                refinerAgentInLoop,
            ),
        // Limit loops
        maxIterations = 5,
    )

// STEP 3: Overall Sequential Pipeline
private val rootAgent =
    SequentialAgent(
        name = "IterativeWritingPipeline",
        subAgents =
            listOf(
                // Run first to create initial doc
                initialWriterAgent,
                // Then run the critique/refine loop
                refinementLoop,
            ),
        // set initial topic in state
        beforeAgentCallbacks = listOf(updateInitialTopicState),
        description =
            "Writes an initial document and then iteratively refines it with critique using an " +
                "exit tool.",
    )

适用于所有代理的全局性指令

在整个工作流程中应用一致的规则。 GlobalInstructionPlugin 在你的(设备或系统上) App (Python, TypeScript, Java或者 GlobalInstruction 您代理程序中的参数……)Go).