跳转到内容

顺序模板工作流代理(Sequential Template Workflow Agent)

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

The SequentialAgent `class` 是一个……(这里的“……”需要根据上下文来填写具体内容。例如,它可以表示“类(class)是一种编程概念”或“`class` 是 Python 中的一个关键字”等。) 模板工作流程(Template Workflow) 该代理按照列表中指定的顺序来执行其下属代理(sub-agents)。 使用说明: SequentialAgent 当你希望某个操作按照固定的、严格的顺序执行时,与其他基于模板的工作流程类似,该操作的执行过程也会被严格控制。 SequentialAgent 该对象不由人工智能模型控制,其执行子代理的方式是确定性的(即每次执行的结果都是固定的)。在序列执行计划中指定的子代理可能会使用人工智能模型,也可能不会使用;不过这些子代理的整体执行过程最终仍由人工或其他非人工智能系统进行管理。 SequentialAgent 你定义的对象。

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

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

示例场景:

你想要构建一个能够总结任何网页内容的代理程序,为此需要使用两个工具: 获取页面内容 和 “Summarize Page”(页面摘要功能)由于代理必须始终进行调用(即必须始终执行相应的操作),因此…… 获取页面内容 在调用之前 “Summarize Page”(页面摘要功能)你可以使用这些资源来构建你的代理(agent)。 SequentialAgent class.

它是如何工作的?

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

  1. 迭代次数(Iteration): 它会按照子代理(sub-agent)提供的顺序依次遍历这个列表。
  2. 子代理执行(Sub-Agent Execution): 对于列表中的每个子代理(sub-agent),程序会调用该子代理的相应函数或方法。 Run Async method.

顺序执行代理(Sequential Agent)

共享调用上下文(Shared Invocation Context)

The SequentialAgent 通过相同的测试/验证过程;结果相同。 InvocationContext 该系统将其会话状态发送给所有的子代理(sub-agents)。这意味着所有子代理都共享相同的会话状态,包括那些临时生成的(temporary)数据。temp:)命名空间(namespace)的使用使得在单次操作过程中,各个步骤之间能够轻松地传递数据。

完整示例:代码开发流程(Code Development Pipeline)

假设我们有一个简化的代码开发流程:

  • Code Writer Agent: 一个基于规范生成初始代码的 large language model(LLM)代理。
  • 代码审查代理(Code Reviewer Agent): 这是一个大型语言模型(LLM)代理,用于检查生成的代码是否存在错误、风格问题以及是否符合最佳编程实践。它接收来自“代码编写代理”(Code Writer Agent)的输出结果。
  • 代码重构代理(Code Refactorer Agent): 这是一个大型语言模型(LLM)代理,它接收被审核的代码以及审核者的评论,然后对代码进行重构,以提高代码质量并解决其中存在的问题。

使用…… SequentialAgent 这使得定义执行流程变得非常简单,如下代码片段所示:

SequentialAgent(name="CodePipelineAgent", sub_agents=[CodeWriterAgent, CodeReviewerAgent, CodeRefactorerAgent])

这确保了代码已经被编写出来。 然后 已经过审查; finally 代码经过了重构,重构过程遵循了严格、可靠的规则。 每个子代理的输出结果都会被存储在状态变量中,从而传递给下一个子代理。 输出键(Output Key).

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

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

# --- 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_MODEL,
    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"
)

# 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_MODEL,
    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"
)


# 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_MODEL,
    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}
    ```

    **Review Comments:**
    {review_comments}

    **Task:**
    Carefully apply the suggestions from the review comments to refactor the original code.
    If the review comments state "No major issues found," return the original code unchanged.
    Ensure the final code is complete, functional, and includes necessary imports and docstrings.

    **Output:**
    Output *only* the final, refactored Python code block, enclosed in triple backticks (```python ... ```).
    Do not add any other text before or after the code block.
    """,
    description="Refactors code based on review comments.",
    output_key="refactored_code"
)


# --- 2. Create the SequentialAgent ---
# This agent orchestrates the pipeline by running the sub_agents in order.
code_pipeline_agent = SequentialAgent(
    name="CodePipelineAgent",
    sub_agents=[code_writer_agent, code_reviewer_agent, code_refactorer_agent],
    description="Executes a sequence of code writing, reviewing, and refactoring.",
)

root_agent = code_pipeline_agent
// Part of agent.ts --> Follow https://adk.dev/get-started/ 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.
const codeWriterAgent = new LlmAgent({
    name: "CodeWriterAgent",
    model: GEMINI_MODEL,
    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.",
    outputKey: "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.
const codeReviewerAgent = new LlmAgent({
    name: "CodeReviewerAgent",
    model: GEMINI_MODEL,
    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.",
    outputKey: "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.
const codeRefactorerAgent = new LlmAgent({
    name: "CodeRefactorerAgent",
    model: GEMINI_MODEL,
    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}
  \`\`\`

  **Review Comments:**
  {review_comments}

**Task:**
Carefully apply the suggestions from the review comments to refactor the original code.
If the review comments state "No major issues found," return the original code unchanged.
Ensure the final code is complete, functional, and includes necessary imports and docstrings.

**Output:**
Output *only* the final, refactored Python code block, enclosed in triple backticks (\`\`\`python ... \`\`\`).
Do not add any other text before or after the code block.
`,
    description: "Refactors code based on review comments.",
    outputKey: "refactored_code", // Stores output in state['refactored_code']
});


// --- 2. Create the SequentialAgent ---
// This agent orchestrates the pipeline by running the sub_agents in order.
const rootAgent = new SequentialAgent({
    name: "CodePipelineAgent",
    subAgents: [codeWriterAgent, codeReviewerAgent, codeRefactorerAgent],
    description: "Executes a sequence of code writing, reviewing, and refactoring.",
    // The agents will run in the order provided: Writer -> Reviewer -> Refactorer
});
    model, err := gemini.NewModel(ctx, modelName, &genai.ClientConfig{})
    if err != nil {
        return fmt.Errorf("failed to create model: %v", err)
    }

    codeWriterAgent, err := llmagent.New(llmagent.Config{
        Name:        "CodeWriterAgent",
        Model:       model,
        Description: "Writes initial Go code based on a specification.",
        Instruction: `You are a Go Code Generator.
Based *only* on the user's request, write Go code that fulfills the requirement.
Output *only* the complete Go code block, enclosed in triple backticks ('''go ... ''').
Do not add any other text before or after the code block.`,
        OutputKey: "generated_code",
    })
    if err != nil {
        return fmt.Errorf("failed to create code writer agent: %v", err)
    }

    codeReviewerAgent, err := llmagent.New(llmagent.Config{
        Name:        "CodeReviewerAgent",
        Model:       model,
        Description: "Reviews code and provides feedback.",
        Instruction: `You are an expert Go Code Reviewer.
Your task is to provide constructive feedback on the provided code.

**Code to Review:**
'''go
{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 Go style guidelines?
3.  **Idiomatic Go:** Does the code use Go's features in a natural and standard way?
4.  **Edge Cases:** Does the code handle potential edge cases or invalid inputs gracefully?
5.  **Best Practices:** Does the code follow common Go 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.`,
        OutputKey: "review_comments",
    })
    if err != nil {
        return fmt.Errorf("failed to create code reviewer agent: %v", err)
    }

    codeRefactorerAgent, err := llmagent.New(llmagent.Config{
        Name:        "CodeRefactorerAgent",
        Model:       model,
        Description: "Refactors code based on review comments.",
        Instruction: `You are a Go Code Refactoring AI.
Your goal is to improve the given Go code based on the provided review comments.

**Original Code:**
'''go
{generated_code}
'''

**Review Comments:**
{review_comments}

**Task:**
Carefully apply the suggestions from the review comments to refactor the original code.
If the review comments state "No major issues found," return the original code unchanged.
Ensure the final code is complete, functional, and includes necessary imports.

**Output:**
Output *only* the final, refactored Go code block, enclosed in triple backticks ('''go ... ''').
Do not add any other text before or after the code block.`,
        OutputKey: "refactored_code",
    })
    if err != nil {
        return fmt.Errorf("failed to create code refactorer agent: %v", err)
    }

    codePipelineAgent, err := sequentialagent.New(sequentialagent.Config{
        AgentConfig: agent.Config{
            Name:        appName,
            Description: "Executes a sequence of code writing, reviewing, and refactoring.",
            SubAgents: []agent.Agent{
                codeWriterAgent,
                codeReviewerAgent,
                codeRefactorerAgent,
            },
        },
    })
    if err != nil {
        return fmt.Errorf("failed to create sequential agent: %v", err)
    }
import com.google.adk.agents.LlmAgent;
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.genai.types.Content;
import com.google.genai.types.Part;
import io.reactivex.rxjava3.core.Flowable;

public class SequentialAgentExample {

  private static final String APP_NAME = "CodePipelineAgent";
  private static final String USER_ID = "test_user_456";
  private static final String MODEL_NAME = "gemini-2.0-flash";

  public static void main(String[] args) {
    SequentialAgentExample sequentialAgentExample = new SequentialAgentExample();
    sequentialAgentExample.runAgent(
        "Write a Java function to calculate the factorial of a number.");
  }

  public void runAgent(String prompt) {

    LlmAgent codeWriterAgent =
        LlmAgent.builder()
            .model(MODEL_NAME)
            .name("CodeWriterAgent")
            .description("Writes initial Java code based on a specification.")
            .instruction(
                """
                You are a Java Code Generator.
                Based *only* on the user's request, write Java code that fulfills the requirement.
                Output *only* the complete Java code block, enclosed in triple backticks (```java ... ```).
                Do not add any other text before or after the code block.
                """)
            .outputKey("generated_code")
            .build();

    LlmAgent codeReviewerAgent =
        LlmAgent.builder()
            .model(MODEL_NAME)
            .name("CodeReviewerAgent")
            .description("Reviews code and provides feedback.")
            .instruction(
                """
                    You are an expert Java Code Reviewer.
                    Your task is to provide constructive feedback on the provided code.

                    **Code to Review:**
                    ```java
                    {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 Java 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 Java 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.
                """)
            .outputKey("review_comments")
            .build();

    LlmAgent codeRefactorerAgent =
        LlmAgent.builder()
            .model(MODEL_NAME)
            .name("CodeRefactorerAgent")
            .description("Refactors code based on review comments.")
            .instruction(
                """
                You are a Java Code Refactoring AI.
                Your goal is to improve the given Java code based on the provided review comments.

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

                  **Review Comments:**
                  {review_comments}

                **Task:**
                Carefully apply the suggestions from the review comments to refactor the original code.
                If the review comments state "No major issues found," return the original code unchanged.
                Ensure the final code is complete, functional, and includes necessary imports and docstrings.

                **Output:**
                Output *only* the final, refactored Java code block, enclosed in triple backticks (```java ... ```).
                Do not add any other text before or after the code block.
                """)
            .outputKey("refactored_code")
            .build();

    SequentialAgent codePipelineAgent =
        SequentialAgent.builder()
            .name(APP_NAME)
            .description("Executes a sequence of code writing, reviewing, and refactoring.")
            // The agents will run in the order provided: Writer -> Reviewer -> Refactorer
            .subAgents(codeWriterAgent, codeReviewerAgent, codeRefactorerAgent)
            .build();

    // Create an InMemoryRunner
    InMemoryRunner runner = new InMemoryRunner(codePipelineAgent, 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.SequentialAgent
import com.google.adk.kt.models.Gemini

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

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

// Code Writer Agent
// Takes the initial specification (from user query) and writes code.
val codeWriterAgent =
    LlmAgent(
        name = "CodeWriterAgent",
        model = Gemini(name = GEMINI_MODEL),
        instruction =
            Instruction(
                """
                You are a Kotlin Code Generator.
                Based *only* on the user's request, write Kotlin code that fulfills the requirement.
                Output *only* the complete Kotlin code block, enclosed in triple backticks (```kotlin ... ```).
                Do not add any other text before or after the code block.
                """.trimIndent(),
            ),
        description = "Writes initial Kotlin code based on a specification.",
        outputKey = "generated_code",
    )

// Code Reviewer Agent
// Takes the code generated by the previous agent (read from state) and provides feedback.
val codeReviewerAgent =
    LlmAgent(
        name = "CodeReviewerAgent",
        model = Gemini(name = GEMINI_MODEL),
        instruction =
            Instruction(
                """
                You are an expert Kotlin Code Reviewer.
                Your task is to provide constructive feedback on the provided code.

                **Code to Review:**
                ```kotlin
                {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 Kotlin coding conventions?
                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 Kotlin 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.
                """.trimIndent(),
            ),
        description = "Reviews code and provides feedback.",
        outputKey = "review_comments",
    )

// Code Refactorer Agent
// Takes the original code and the review comments (read from state) and refactors the code.
val codeRefactorerAgent =
    LlmAgent(
        name = "CodeRefactorerAgent",
        model = Gemini(name = GEMINI_MODEL),
        instruction =
            Instruction(
                """
                You are a Kotlin Code Refactoring AI.
                Your goal is to improve the given Kotlin code based on the provided review comments.

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

                **Review Comments:**
                {review_comments}

                **Task:**
                Carefully apply the suggestions from the review comments to refactor the original code.
                If the review comments state "No major issues found," return the original code unchanged.
                Ensure the final code is complete, functional, and includes necessary imports and KDoc comments.

                **Output:**
                Output *only* the final, refactored Kotlin code block, enclosed in triple backticks (```kotlin ... ```).
                Do not add any other text before or after the code block.
                """.trimIndent(),
            ),
        description = "Refactors code based on review comments.",
        outputKey = "refactored_code",
    )

// --- 2. Create the SequentialAgent ---
// This agent orchestrates the pipeline by running the subAgents in order.
val codePipelineAgent =
    SequentialAgent(
        name = "CodePipelineAgent",
        subAgents = listOf(codeWriterAgent, codeReviewerAgent, codeRefactorerAgent),
        description = "Executes a sequence of code writing, reviewing, and refactoring.",
    )

private val rootAgent = codePipelineAgent

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

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