ADK并行模板工作流代理的并发执行机制
ADK的ParallelAgent属于模板工作流代理,会并发执行其子代理,适合可独立完成的多任务场景。其执行由代理对象而非AI模型控制,因此子代理调度具有确定性。
## 并行模板工作流程代理[¶](<https://adk.dev/agents/workflow-agents/parallel-agents/#parallel-template-workflow-agent>) 在ADKPython v0.1.0TypeScript v0.2.0Go v0.1.0Java v0.2.0Kotlin v0.1.0中支持 互联网档案馆的存檔,存档日期2011-09-02. 那个... ***ParallelAgent*** 类为 a [模板工作流程](<https://adk.dev/agents/workflow-agents/>) 此执行策略可以显著加快工作流程, 工作流程可以独立执行两个或两个以上的任务。 对于优先执行速度和涉及独立、资源密集型任务的情景, 此模板工作流程可以促进并行执行, 这可以大大缩短总体处理时间 。在使用这种工作流程类型时,每个子代理能够运行而不取决于其他子代理,这个工作流程类型对于多源数据检索或重计算等操作特别有利,在这些操作中,并行化产生大量的性能收益. 与其他模板工作流程一样,执行一个 ***ParallelAgent*** 对象不受AI模型控制,在如何执行子代理上具有决定性. 并行执行集中指定的子代理可能使用或可能不使用AI模型,但这些子代理的整体执行最终由该子代理管理. ***ParallelAgent*** 您定义的对象。 折旧:使用基于图表的工作流程 在ADK Python,TypeScript,Go,和Kotlin中,模板工作流程已被更灵活的工作流程结构所取代,包括: [基于图表的工作流程](<https://adk.dev/graphs/>) 财务报告和财务报告 [动态工作流程](<https://adk.dev/graphs/dynamic/>). ### 如何运作[¶](<https://adk.dev/agents/workflow-agents/parallel-agents/#how-it-works>) 当 `ParallelAgent`'s `run_async()` 方法称为: 1. **同时执行 :** 它启动 `run_async()` 方法 *每一个* 显示于 `sub_agents` 列表 *同时*。这意味着所有特工在同一时间(大约)开始运行。 2. **独立分支:** 每个副代理在自己的执行分支中运作,并且有 ***无* 这些分支之间对话历史的自动共享** 。一个子代理只查看自己分支上的事件。会话状态是共享的:所有分支运行于同一会话中,所以一个子代理写着一个值,例如通过 `output_key`,在其他分支和后来的代理人中可见. 3. **结果收藏 :** 那个... `ParallelAgent` 将子代理的事件流合并, 并按生成时生成每个事件; 它不会将结果收集到您以后可以读取的列表中。 由于分支间断, 事件顺序不是决定性的 。 要使用子代理的结果, 请从共享会话状态读取, 例如它通过 。 `output_key`. ### 独立执行和国家管理[¶](<https://adk.dev/agents/workflow-agents/parallel-agents/#independent-execution-and-state-management>) 这是 *关键* 以了解在下列条件下的子代理人: `ParallelAgent` 独立运行。如果你 *需求* 这些代理人之间的沟通或数据共享,必须明确执行。 - **共享会话状态 :** 所有分支都与同一会话相对应 所以给每个副代理 `output_key` 并读取后代理指令中的密钥。由于分支同时运行,所以不要依赖一个分支读取另一个分支仍在写入密钥。 - **外部国家管理:** 使用外部数据库,消息队列,或其他机制来管理共享状态,并促进代理商之间的沟通. - **处理后:** 收集每个分支的结果,然后执行逻辑来协调数据。  ### 完整示例:平行网络研究[¶](<https://adk.dev/agents/workflow-agents/parallel-agents/#full-example-parallel-web-research>) 设想同时研究多个主题: 1. **研究人员特工1:** 一个 `LlmAgent` 研究“可再生能源” 2. **研究人员特工2:** 一个 `LlmAgent` 研究"电力车辆技术" 3. **研究人员特工3:** 一个 `LlmAgent` 研究"碳捕获方法"。 ``` ParallelAgent(name="ParallelWebResearchAgent", sub_agents=[ResearcherAgent1, ResearcherAgent2, ResearcherAgent3]) ``` 这些研究任务是独立的。 `ParallelAgent` 允许它们同时运行,与顺序运行相比,可能大大缩短研究总时间。 `output_key` 并且从会话状态读出密钥。 完整代码 PythonTypeScriptGoJavaKotlin ``` 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 键](<https://github.com/google/adk-python/blob/main/src/google/adk/plugins/global_instruction_plugin.py>), [TypeScript](<https://github.com/google/adk-js/blob/main/core/src/plugins/global_instruction_plugin.ts>), [爪哇语](<https://github.com/google/adk-java/blob/main/core/src/main/java/com/google/adk/plugins/GlobalInstructionPlugin.java>))或为: `GlobalInstruction` 在您的代理服务器上的参数( E)[滚开](<https://github.com/google/adk-go/blob/main/agent/llmagent/llmagent.go>)).
查看原始来源