跳转到内容

并行模板工作流代理(Parallel Template Workflow Agent)

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

The ParallelAgent `class` 是一个……(这里的“……”需要根据上下文来填写具体内容。例如,它可以表示“类(class)是一种编程概念”或“`class` 是 Python 中的一个关键字”等。) 模板工作流程(Template Workflow) 该代理能够同时执行其下属代理(sub-agents)。这种执行策略可以显著加快工作流程的效率——尤其是在需要独立完成两个或多个任务的情况下。对于那些重视处理速度、且涉及资源密集型独立任务的场景而言,这种模板化的工作流程能够实现任务的并行执行,从而大幅缩短整体处理时间。在使用这种工作流程类型时,必须确保每个下属代理都能独立运行(即不依赖于其他下属代理)。这种工作流程类型特别适用于需要从多个数据源获取信息或进行复杂计算的操作;在这些场景中,并行处理能够带来显著的性能提升。

与其他基于模板的工作流程类似,该工作流程的执行过程也是类似的。 ParallelAgent 该对象不由 AI 模型控制,其子代理的执行方式是确定性的(即每次执行的结果都是相同的)。在并行执行设置中指定的子代理可能会使用 AI 模型,也可能不会使用;不过这些子代理的整个执行过程最终仍由该系统进行管理。 ParallelAgent 你定义的对象。

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

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

它是如何工作的?

当……的时候 ParallelAgent's run_async() 调用的方法是:

  1. 并发执行(Concurrent Execution): 它启动了…… run_async() ……的方法 每个;各自 系统中存在一个子代理(sub-agent)。 sub_agents list 同时地;并行地这意味着所有代理程序几乎会同时开始运行。
  2. 独立分支机构: 每个子代理都在自己的执行分支中运行。 no 这些分支之间会自动共享对话记录。 在执行过程中,每个子代理只能看到自己所在分支上的事件。会话状态是共享的:所有分支都使用同一个会话;因此,某个子代理写入的任何数据(例如通过某种方式)都会被其他所有分支看到。 output_key该信息对其他分支以及后续处理的代理程序都是可见的。
  3. 结果集合(Result Collection): The ParallelAgent 该系统会合并各个子代理的事件流,并在事件产生时立即将其显示出来;它不会将这些事件结果收集到一个可供后续查看的列表中。由于各个子代理的事件流是交错发生的,因此事件的具体顺序是不可预测的。如果要使用某个子代理的处理结果,需要从共享的会话状态中获取该结果(例如,通过该子代理获得的唯一标识符或键值对)。 output_key.

独立执行与状态管理

It’s crucial(关键的、重要的) 要理解的是:在一个组织或系统内部,那些被称为“次级代理人”(sub-agents)的人或团队…… ParallelAgent 可以独立运行。如果你…… 需要 在这些代理之间实现通信或数据共享时,你必须明确地设计相应的机制。可行的方法包括:

  • 共享会话状态(Shared session state): 所有分支都使用同一个会话(session)进行操作;因此,请为每个子代理(sub-agent)分配一个独立的会话标识符。 output_key 然后从后续代理的指令中读取这些密钥。由于各个分支是并行运行的,因此不要依赖某个分支读取密钥的行为;另一个分支可能仍在写入数据。
  • 外部状态管理(External State Management): 可以使用外部数据库、消息队列或其他机制来管理共享状态,并促进各个代理之间的通信。
  • 后期处理(Post-Processing): 从每个分支中收集结果,然后编写逻辑来协调这些数据。

并行代理(Parallel Agent)

完整示例:并行网络研究(Full Example: Parallel Web Research)

想象一下,你需要同时研究多个主题……

  1. 研究员代理1: An LlmAgent 那项研究的主题是“可再生能源”。
  2. 研究员代理 2: An LlmAgent 那项研究的内容是“电动汽车技术”。
  3. 研究员代理 3: An LlmAgent 那项研究的主题是“碳捕获方法”。

    ParallelAgent(name="ParallelWebResearchAgent", sub_agents=[ResearcherAgent1, ResearcherAgent2, ResearcherAgent3])
    

这些研究任务是相互独立的。可以使用……(此处应填写具体的方法或工具)。 ParallelAgent 这允许这些任务同时运行,从而与顺序执行这些任务相比,显著缩短总的研究时间。要使用每个代理的结果,需要先对它们进行处理(或:要使用每个代理的结果,需要先对它们进行相应的处理)。 output_key 然后从会话状态中读取该密钥。

完整代码
 from google.adk.agents.parallel_agent import ParallelAgent
 from google.adk.agents.llm_agent import LlmAgent
 from google.adk.agents.sequential_agent import SequentialAgent
 from google.adk.tools import google_search

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

 # --- 1. Define Researcher Sub-Agents (to run in parallel) ---
 # Researcher 1: Renewable Energy
 researcher_agent_1 = LlmAgent(
     name="RenewableEnergyResearcher",
     model=GEMINI_MODEL,
     instruction="""
     You are an AI Research Assistant specializing in energy.
     Research the latest advancements in 'renewable energy sources'.
     Use the Google Search tool provided.
     Summarize your key findings concisely (1-2 sentences).
     Output *only* the summary.
     """,
     description="Researches renewable energy sources.",
     tools=[google_search],
     # Store result in state for the merger agent
     output_key="renewable_energy_result"
 )

 # Researcher 2: Electric Vehicles
 researcher_agent_2 = LlmAgent(
     name="EVResearcher",
     model=GEMINI_MODEL,
     instruction="""
     You are an AI Research Assistant specializing in transportation.
     Research the latest developments in 'electric vehicle technology'.
     Use the Google Search tool provided.
     Summarize your key findings concisely (1-2 sentences).
     Output *only* the summary.
     """,
     description="Researches electric vehicle technology.",
     tools=[google_search],
     # Store result in state for the merger agent
     output_key="ev_technology_result"
 )

 # Researcher 3: Carbon Capture
 researcher_agent_3 = LlmAgent(
     name="CarbonCaptureResearcher",
     model=GEMINI_MODEL,
     instruction="""
     You are an AI Research Assistant specializing in climate solutions.
     Research the current state of 'carbon capture methods'.
     Use the Google Search tool provided.
     Summarize your key findings concisely (1-2 sentences).
     Output *only* the summary.
     """,
     description="Researches carbon capture methods.",
     tools=[google_search],
     # Store result in state for the merger agent
     output_key="carbon_capture_result"
 )

 # --- 2. Create the ParallelAgent (Runs researchers concurrently) ---
 # This agent orchestrates the concurrent execution of the researchers.
 # It finishes once all researchers have completed and stored their results in state.
 parallel_research_agent = ParallelAgent(
     name="ParallelWebResearchAgent",
     sub_agents=[researcher_agent_1, researcher_agent_2, researcher_agent_3],
     description="Runs multiple research agents in parallel to gather information."
 )

 # --- 3. Define the Merger Agent (Runs *after* the parallel agents) ---
 # This agent takes the results stored in the session state by the parallel agents
 # and synthesizes them into a single, structured response with attributions.
 merger_agent = LlmAgent(
     name="SynthesisAgent",
     model=GEMINI_MODEL,  # Or potentially a more powerful model if needed for synthesis
     instruction="""
     You are an AI Assistant responsible for combining research findings into a structured report.

     Your primary task is to synthesize the following research summaries, clearly attributing findings to their source areas. Structure your response using headings for each topic. Ensure the report is coherent and integrates the key points smoothly.

     **Crucially: Your entire response MUST be grounded *exclusively* on the information provided in the 'Input Summaries' below. Do NOT add any external knowledge, facts, or details not present in these specific summaries.**

     **Input Summaries:**

     *   **Renewable Energy:**
         {renewable_energy_result}

     *   **Electric Vehicles:**
         {ev_technology_result}

     *   **Carbon Capture:**
         {carbon_capture_result}

     **Output Format:**

     ## Summary of Recent Sustainable Technology Advancements

     ### Renewable Energy Findings
     (Based on RenewableEnergyResearcher's findings)
     [Synthesize and elaborate *only* on the renewable energy input summary provided above.]

     ### Electric Vehicle Findings
     (Based on EVResearcher's findings)
     [Synthesize and elaborate *only* on the EV input summary provided above.]

     ### Carbon Capture Findings
     (Based on CarbonCaptureResearcher's findings)
     [Synthesize and elaborate *only* on the carbon capture input summary provided above.]

     ### Overall Conclusion
     [Provide a brief (1-2 sentence) concluding statement that connects *only* the findings presented above.]

     Output *only* the structured report following this format. Do not include introductory or concluding phrases outside this structure, and strictly adhere to using only the provided input summary content.
     """,
     description="Combines research findings from parallel agents into a structured, cited report, strictly grounded on provided inputs.",
     # No tools needed for merging
     # No output_key needed here, as its direct response is the final output of the sequence
 )


 # --- 4. Create the SequentialAgent (Orchestrates the overall flow) ---
 # This is the main agent that will be run. It first executes the ParallelAgent
 # to populate the state, and then executes the MergerAgent to produce the final output.
 sequential_pipeline_agent = SequentialAgent(
     name="ResearchAndSynthesisPipeline",
     # Run parallel research first, then merge
     sub_agents=[parallel_research_agent, merger_agent],
     description="Coordinates parallel research and synthesizes the results."
 )

 root_agent = sequential_pipeline_agent
 // Part of agent.ts --> Follow https://adk.dev/get-started/ to learn the setup
 // --- 1. Define Researcher Sub-Agents (to run in parallel) ---

 const researchTools = [GOOGLE_SEARCH];

 // Researcher 1: Renewable Energy
 const researcherAgent1 = new LlmAgent({
     name: "RenewableEnergyResearcher",
     model: GEMINI_MODEL,
     instruction: `You are an AI Research Assistant specializing in energy.
 Research the latest advancements in 'renewable energy sources'.
 Use the Google Search tool provided.
 Summarize your key findings concisely (1-2 sentences).
 Output *only* the summary.
 `,
     description: "Researches renewable energy sources.",
     tools: researchTools,
     // Store result in state for the merger agent
     outputKey: "renewable_energy_result"
 });

 // Researcher 2: Electric Vehicles
 const researcherAgent2 = new LlmAgent({
     name: "EVResearcher",
     model: GEMINI_MODEL,
     instruction: `You are an AI Research Assistant specializing in transportation.
 Research the latest developments in 'electric vehicle technology'.
 Use the Google Search tool provided.
 Summarize your key findings concisely (1-2 sentences).
 Output *only* the summary.
 `,
     description: "Researches electric vehicle technology.",
     tools: researchTools,
     // Store result in state for the merger agent
     outputKey: "ev_technology_result"
 });

 // Researcher 3: Carbon Capture
 const researcherAgent3 = new LlmAgent({
     name: "CarbonCaptureResearcher",
     model: GEMINI_MODEL,
     instruction: `You are an AI Research Assistant specializing in climate solutions.
 Research the current state of 'carbon capture methods'.
 Use the Google Search tool provided.
 Summarize your key findings concisely (1-2 sentences).
 Output *only* the summary.
 `,
     description: "Researches carbon capture methods.",
     tools: researchTools,
     // Store result in state for the merger agent
     outputKey: "carbon_capture_result"
 });

 // --- 2. Create the ParallelAgent (Runs researchers concurrently) ---
 // This agent orchestrates the concurrent execution of the researchers.
 // It finishes once all researchers have completed and stored their results in state.
 const parallelResearchAgent = new ParallelAgent({
     name: "ParallelWebResearchAgent",
     subAgents: [researcherAgent1, researcherAgent2, researcherAgent3],
     description: "Runs multiple research agents in parallel to gather information."
 });

 // --- 3. Define the Merger Agent (Runs *after* the parallel agents) ---
 // This agent takes the results stored in the session state by the parallel agents
 // and synthesizes them into a single, structured response with attributions.
 const mergerAgent = new LlmAgent({
     name: "SynthesisAgent",
     model: GEMINI_MODEL,  // Or potentially a more powerful model if needed for synthesis
     instruction: `You are an AI Assistant responsible for combining research findings into a structured report.

 Your primary task is to synthesize the following research summaries, clearly attributing findings to their source areas. Structure your response using headings for each topic. Ensure the report is coherent and integrates the key points smoothly.

 **Crucially: Your entire response MUST be grounded *exclusively* on the information provided in the 'Input Summaries' below. Do NOT add any external knowledge, facts, or details not present in these specific summaries.**

 **Input Summaries:**

 *   **Renewable Energy:**
     {renewable_energy_result}

 *   **Electric Vehicles:**
     {ev_technology_result}

 *   **Carbon Capture:**
     {carbon_capture_result}

 **Output Format:**

 ## Summary of Recent Sustainable Technology Advancements

 ### Renewable Energy Findings
 (Based on RenewableEnergyResearcher's findings)
 [Synthesize and elaborate *only* on the renewable energy input summary provided above.]

 ### Electric Vehicle Findings
 (Based on EVResearcher's findings)
 [Synthesize and elaborate *only* on the EV input summary provided above.]

 ### Carbon Capture Findings
 (Based on CarbonCaptureResearcher's findings)
 [Synthesize and elaborate *only* on the carbon capture input summary provided above.]

 ### Overall Conclusion
 [Provide a brief (1-2 sentence) concluding statement that connects *only* the findings presented above.]

 Output *only* the structured report following this format. Do not include introductory or concluding phrases outside this structure, and strictly adhere to using only the provided input summary content.
 `,
     description: "Combines research findings from parallel agents into a structured, cited report, strictly grounded on provided inputs.",
     // No tools needed for merging
     // No output_key needed here, as its direct response is the final output of the sequence
 });


 // --- 4. Create the SequentialAgent (Orchestrates the overall flow) ---
 // This is the main agent that will be run. It first executes the ParallelAgent
 // to populate the state, and then executes the MergerAgent to produce the final output.
 const rootAgent = new SequentialAgent({
     name: "ResearchAndSynthesisPipeline",
     // Run parallel research first, then merge
     subAgents: [parallelResearchAgent, mergerAgent],
     description: "Coordinates parallel research and synthesizes the results."
 });
    model, err := gemini.NewModel(ctx, modelName, &genai.ClientConfig{})
    if err != nil {
        return fmt.Errorf("failed to create model: %v", err)
    }

    // --- 1. Define Researcher Sub-Agents (to run in parallel) ---
    researcher1, err := llmagent.New(llmagent.Config{
        Name:  "RenewableEnergyResearcher",
        Model: model,
        Instruction: `You are an AI Research Assistant specializing in energy.
 Research the latest advancements in 'renewable energy sources'.
 Use the Google Search tool provided.
 Summarize your key findings concisely (1-2 sentences).
 Output *only* the summary.`,
        Description: "Researches renewable energy sources.",
        OutputKey:   "renewable_energy_result",
    })
    if err != nil {
        return err
    }
    researcher2, err := llmagent.New(llmagent.Config{
        Name:  "EVResearcher",
        Model: model,
        Instruction: `You are an AI Research Assistant specializing in transportation.
 Research the latest developments in 'electric vehicle technology'.
 Use the Google Search tool provided.
 Summarize your key findings concisely (1-2 sentences).
 Output *only* the summary.`,
        Description: "Researches electric vehicle technology.",
        OutputKey:   "ev_technology_result",
    })
    if err != nil {
        return err
    }
    researcher3, err := llmagent.New(llmagent.Config{
        Name:  "CarbonCaptureResearcher",
        Model: model,
        Instruction: `You are an AI Research Assistant specializing in climate solutions.
 Research the current state of 'carbon capture methods'.
 Use the Google Search tool provided.
 Summarize your key findings concisely (1-2 sentences).
 Output *only* the summary.`,
        Description: "Researches carbon capture methods.",
        OutputKey:   "carbon_capture_result",
    })
    if err != nil {
        return err
    }

    // --- 2. Create the ParallelAgent (Runs researchers concurrently) ---
    parallelResearchAgent, err := parallelagent.New(parallelagent.Config{
        AgentConfig: agent.Config{
            Name:        "ParallelWebResearchAgent",
            Description: "Runs multiple research agents in parallel to gather information.",
            SubAgents:   []agent.Agent{researcher1, researcher2, researcher3},
        },
    })
    if err != nil {
        return fmt.Errorf("failed to create parallel agent: %v", err)
    }

    // --- 3. Define the Merger Agent (Runs *after* the parallel agents) ---
    synthesisAgent, err := llmagent.New(llmagent.Config{
        Name:  "SynthesisAgent",
        Model: model,
        Instruction: `You are an AI Assistant responsible for combining research findings into a structured report.
 Your primary task is to synthesize the following research summaries, clearly attributing findings to their source areas. Structure your response using headings for each topic. Ensure the report is coherent and integrates the key points smoothly.
 **Crucially: Your entire response MUST be grounded *exclusively* on the information provided in the 'Input Summaries' below. Do NOT add any external knowledge, facts, or details not present in these specific summaries.**
 **Input Summaries:**

 *   **Renewable Energy:**
     {renewable_energy_result}

 *   **Electric Vehicles:**
     {ev_technology_result}

 *   **Carbon Capture:**
     {carbon_capture_result}

 **Output Format:**

 ## Summary of Recent Sustainable Technology Advancements

 ### Renewable Energy Findings
 (Based on RenewableEnergyResearcher's findings)
 [Synthesize and elaborate *only* on the renewable energy input summary provided above.]

 ### Electric Vehicle Findings
 (Based on EVResearcher's findings)
 [Synthesize and elaborate *only* on the EV input summary provided above.]

 ### Carbon Capture Findings
 (Based on CarbonCaptureResearcher's findings)
 [Synthesize and elaborate *only* on the carbon capture input summary provided above.]

 ### Overall Conclusion
 [Provide a brief (1-2 sentence) concluding statement that connects *only* the findings presented above.]

 Output *only* the structured report following this format. Do not include introductory or concluding phrases outside this structure, and strictly adhere to using only the provided input summary content.`,
        Description: "Combines research findings from parallel agents into a structured, cited report, strictly grounded on provided inputs.",
    })
    if err != nil {
        return fmt.Errorf("failed to create synthesis agent: %v", err)
    }

    // --- 4. Create the SequentialAgent (Orchestrates the overall flow) ---
    pipeline, err := sequentialagent.New(sequentialagent.Config{
        AgentConfig: agent.Config{
            Name:        "ResearchAndSynthesisPipeline",
            Description: "Coordinates parallel research and synthesizes the results.",
            SubAgents:   []agent.Agent{parallelResearchAgent, synthesisAgent},
        },
    })
    if err != nil {
        return fmt.Errorf("failed to create sequential agent pipeline: %v", err)
    }
 import com.google.adk.agents.LlmAgent;
 import com.google.adk.agents.ParallelAgent;
 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.GoogleSearchTool;
 import com.google.genai.types.Content;
 import com.google.genai.types.Part;
 import io.reactivex.rxjava3.core.Flowable;

 public class ParallelResearchPipeline {

   private static final String APP_NAME = "parallel_research_app";
   private static final String USER_ID = "research_user_01";
   private static final String GEMINI_MODEL = "gemini-2.0-flash";

   // Assume google_search is an instance of the GoogleSearchTool
   private static final GoogleSearchTool googleSearchTool = new GoogleSearchTool();

   public static void main(String[] args) {
     String query = "Summarize recent sustainable tech advancements.";
     SequentialAgent sequentialPipelineAgent = initAgent();
     runAgent(sequentialPipelineAgent, query);
   }

   public static SequentialAgent initAgent() {
     // --- 1. Define Researcher Sub-Agents (to run in parallel) ---
     // Researcher 1: Renewable Energy
     LlmAgent researcherAgent1 = LlmAgent.builder()
         .name("RenewableEnergyResearcher")
         .model(GEMINI_MODEL)
         .instruction("""
                     You are an AI Research Assistant specializing in energy.
                     Research the latest advancements in 'renewable energy sources'.
                     Use the Google Search tool provided.
                     Summarize your key findings concisely (1-2 sentences).
                     Output *only* the summary.
                     """)
         .description("Researches renewable energy sources.")
         .tools(googleSearchTool)
         .outputKey("renewable_energy_result") // Store result in state
         .build();

     // Researcher 2: Electric Vehicles
     LlmAgent researcherAgent2 = LlmAgent.builder()
         .name("EVResearcher")
         .model(GEMINI_MODEL)
         .instruction("""
                     You are an AI Research Assistant specializing in transportation.
                     Research the latest developments in 'electric vehicle technology'.
                     Use the Google Search tool provided.
                     Summarize your key findings concisely (1-2 sentences).
                     Output *only* the summary.
                     """)
         .description("Researches electric vehicle technology.")
         .tools(googleSearchTool)
         .outputKey("ev_technology_result") // Store result in state
         .build();

     // Researcher 3: Carbon Capture
     LlmAgent researcherAgent3 = LlmAgent.builder()
         .name("CarbonCaptureResearcher")
         .model(GEMINI_MODEL)
         .instruction("""
                     You are an AI Research Assistant specializing in climate solutions.
                     Research the current state of 'carbon capture methods'.
                     Use the Google Search tool provided.
                     Summarize your key findings concisely (1-2 sentences).
                     Output *only* the summary.
                     """)
         .description("Researches carbon capture methods.")
         .tools(googleSearchTool)
         .outputKey("carbon_capture_result") // Store result in state
         .build();

     // --- 2. Create the ParallelAgent (Runs researchers concurrently) ---
     // This agent orchestrates the concurrent execution of the researchers.
     // It finishes once all researchers have completed and stored their results in state.
     ParallelAgent parallelResearchAgent =
         ParallelAgent.builder()
             .name("ParallelWebResearchAgent")
             .subAgents(researcherAgent1, researcherAgent2, researcherAgent3)
             .description("Runs multiple research agents in parallel to gather information.")
             .build();

     // --- 3. Define the Merger Agent (Runs *after* the parallel agents) ---
     // This agent takes the results stored in the session state by the parallel agents
     // and synthesizes them into a single, structured response with attributions.
     LlmAgent mergerAgent =
         LlmAgent.builder()
             .name("SynthesisAgent")
             .model(GEMINI_MODEL)
             .instruction(
                 """
                       You are an AI Assistant responsible for combining research findings into a structured report.
                       Your primary task is to synthesize the following research summaries, clearly attributing findings to their source areas. Structure your response using headings for each topic. Ensure the report is coherent and integrates the key points smoothly.
                       **Crucially: Your entire response MUST be grounded *exclusively* on the information provided in the 'Input Summaries' below. Do NOT add any external knowledge, facts, or details not present in these specific summaries.**
                       **Input Summaries:**

                       *   **Renewable Energy:**
                           {renewable_energy_result}

                       *   **Electric Vehicles:**
                           {ev_technology_result}

                       *   **Carbon Capture:**
                           {carbon_capture_result}

                       **Output Format:**

                       ## Summary of Recent Sustainable Technology Advancements

                       ### Renewable Energy Findings
                       (Based on RenewableEnergyResearcher's findings)
                       [Synthesize and elaborate *only* on the renewable energy input summary provided above.]

                       ### Electric Vehicle Findings
                       (Based on EVResearcher's findings)
                       [Synthesize and elaborate *only* on the EV input summary provided above.]

                       ### Carbon Capture Findings
                       (Based on CarbonCaptureResearcher's findings)
                       [Synthesize and elaborate *only* on the carbon capture input summary provided above.]

                       ### Overall Conclusion
                       [Provide a brief (1-2 sentence) concluding statement that connects *only* the findings presented above.]

                       Output *only* the structured report following this format. Do not include introductory or concluding phrases outside this structure, and strictly adhere to using only the provided input summary content.
                       """)
             .description(
                 "Combines research findings from parallel agents into a structured, cited report, strictly grounded on provided inputs.")
             // No tools needed for merging
             // No output_key needed here, as its direct response is the final output of the sequence
             .build();

     // --- 4. Create the SequentialAgent (Orchestrates the overall flow) ---
     // This is the main agent that will be run. It first executes the ParallelAgent
     // to populate the state, and then executes the MergerAgent to produce the final output.
     SequentialAgent sequentialPipelineAgent =
         SequentialAgent.builder()
             .name("ResearchAndSynthesisPipeline")
             // Run parallel research first, then merge
             .subAgents(parallelResearchAgent, mergerAgent)
             .description("Coordinates parallel research and synthesizes the results.")
             .build();

     return sequentialPipelineAgent;
   }

   public static void runAgent(SequentialAgent sequentialPipelineAgent, String query) {
     // Create an InMemoryRunner
     InMemoryRunner runner = new InMemoryRunner(sequentialPipelineAgent, 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(query));

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

     // Stream event response
     eventStream.blockingForEach(
         event -> {
           if (event.finalResponse()) {
             System.out.printf("Event Author: %s \n Event Response: %s \n\n\n", event.author(), event.stringifyContent());
           }
         });
   }
 }
 import com.google.adk.kt.agents.Instruction
 import com.google.adk.kt.agents.LlmAgent
 import com.google.adk.kt.agents.ParallelAgent
 import com.google.adk.kt.agents.SequentialAgent
 import com.google.adk.kt.models.Gemini
 import com.google.adk.kt.tools.GoogleSearchTool

 // --- Constants ---
 const val GEMINI_MODEL = "gemini-2.5-flash"

 val googleSearch = GoogleSearchTool()

 // --- 1. Define Researcher Sub-Agents (to run in parallel) ---
 // Researcher 1: Renewable Energy
 val researcherAgent1 =
     LlmAgent(
         name = "RenewableEnergyResearcher",
         model = Gemini(name = GEMINI_MODEL),
         instruction =
             Instruction(
                 """
                 You are an AI Research Assistant specializing in energy.
                 Research the latest advancements in 'renewable energy sources'.
                 Use the Google Search tool provided.
                 Summarize your key findings concisely (1-2 sentences).
                 Output *only* the summary.
                 """.trimIndent(),
             ),
         description = "Researches renewable energy sources.",
         tools = listOf(googleSearch),
         // Store result in state for the merger agent
         outputKey = "renewable_energy_result",
     )

 // Researcher 2: Electric Vehicles
 val researcherAgent2 =
     LlmAgent(
         name = "EVResearcher",
         model = Gemini(name = GEMINI_MODEL),
         instruction =
             Instruction(
                 """
                 You are an AI Research Assistant specializing in transportation.
                 Research the latest developments in 'electric vehicle technology'.
                 Use the Google Search tool provided.
                 Summarize your key findings concisely (1-2 sentences).
                 Output *only* the summary.
                 """.trimIndent(),
             ),
         description = "Researches electric vehicle technology.",
         tools = listOf(googleSearch),
         // Store result in state for the merger agent
         outputKey = "ev_technology_result",
     )

 // Researcher 3: Carbon Capture
 val researcherAgent3 =
     LlmAgent(
         name = "CarbonCaptureResearcher",
         model = Gemini(name = GEMINI_MODEL),
         instruction =
             Instruction(
                 """
                 You are an AI Research Assistant specializing in climate solutions.
                 Research the current state of 'carbon capture methods'.
                 Use the Google Search tool provided.
                 Summarize your key findings concisely (1-2 sentences).
                 Output *only* the summary.
                 """.trimIndent(),
             ),
         description = "Researches carbon capture methods.",
         tools = listOf(googleSearch),
         // Store result in state for the merger agent
         outputKey = "carbon_capture_result",
     )

 // --- 2. Create the ParallelAgent (Runs researchers concurrently) ---
 // This agent orchestrates the concurrent execution of the researchers.
 // It finishes once all researchers have completed and stored their results in state.
 val parallelResearchAgent =
     ParallelAgent(
         name = "ParallelWebResearchAgent",
         subAgents = listOf(researcherAgent1, researcherAgent2, researcherAgent3),
         description = "Runs multiple research agents in parallel to gather information.",
     )

 // --- 3. Define the Merger Agent (Runs *after* the parallel agents) ---
 // This agent takes the results stored in the session state by the parallel agents
 // and synthesizes them into a single, structured response with attributions.
 val mergerAgent =
     LlmAgent(
         name = "SynthesisAgent",
         model = Gemini(name = GEMINI_MODEL), // Or potentially a more powerful model if needed for synthesis
         instruction =
             Instruction(
                 """
                 You are an AI Assistant responsible for combining research findings into a structured report.

                 Your primary task is to synthesize the following research summaries, clearly attributing findings to their source areas. Structure your response using headings for each topic. Ensure the report is coherent and integrates the key points smoothly.

                 **Crucially: Your entire response MUST be grounded *exclusively* on the information provided in the 'Input Summaries' below. Do NOT add any external knowledge, facts, or details not present in these specific summaries.**

                 **Input Summaries:**

                 *   **Renewable Energy:**
                     {renewable_energy_result}

                 *   **Electric Vehicles:**
                     {ev_technology_result}

                 *   **Carbon Capture:**
                     {carbon_capture_result}

                 **Output Format:**

                 ## Summary of Recent Sustainable Technology Advancements

                 ### Renewable Energy Findings
                 (Based on RenewableEnergyResearcher's findings)
                 [Synthesize and elaborate *only* on the renewable energy input summary provided above.]

                 ### Electric Vehicle Findings
                 (Based on EVResearcher's findings)
                 [Synthesize and elaborate *only* on the EV input summary provided above.]

                 ### Carbon Capture Findings
                 (Based on CarbonCaptureResearcher's findings)
                 [Synthesize and elaborate *only* on the carbon capture input summary provided above.]

                 ### Overall Conclusion
                 [Provide a brief (1-2 sentence) concluding statement that connects *only* the findings presented above.]

                 Output *only* the structured report following this format. Do not include introductory or concluding phrases outside this structure, and strictly adhere to using only the provided input summary content.
                 """.trimIndent(),
             ),
         description =
             "Combines research findings from parallel agents into a structured, cited report, " +
                 "strictly grounded on provided inputs.",
         // No tools needed for merging
         // No outputKey needed here, as its direct response is the final output of the sequence
     )

 // --- 4. Create the SequentialAgent (Orchestrates the overall flow) ---
 // This is the main agent that will be run. It first executes the ParallelAgent
 // to populate the state, and then executes the MergerAgent to produce the final output.
 val sequentialPipelineAgent =
     SequentialAgent(
         name = "ResearchAndSynthesisPipeline",
         // Run parallel research first, then merge
         subAgents = listOf(parallelResearchAgent, mergerAgent),
         description = "Coordinates parallel research and synthesizes the results.",
     )

 val rootAgent = sequentialPipelineAgent

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

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