多智能体工作流模式(Multi-agent workflow patterns)¶
本指南提供了一些代理模式(agent patterns),您可以使用代理开发工具包(Agent Development Kit, ADK)来实现这些模式,并附有相应的代码示例。这些模式适用于多种应用程序;在正式实施之前,建议您根据您的项目需求对这些模式进行评估和测试。
Python 和 TypeScript:模板工作流代理(template workflow agents)已被弃用。
在 Python 和 TypeScript 中, SequentialAgent, ParallelAgent,以及
LoopAgent 这些功能已被弃用:使用它们会生成弃用警告(deprecation warning),并且这些类计划在未来的版本中被移除。下面的示例仍然可以正常运行。对于新的代码,请使用其他方式来实现相同的功能。 基于图的工作流程(graph-based workflow)请注意:
Workflow 目前还不能将其用作…… LlmAgent 子代理(sub-agent)。
协调者与调度器¶
- 结构: 一个核心的……
LlmAgent(协调员)负责管理多个专业团队/部门。sub_agents. - 目标: 将传入的请求路由到相应的专业代理。
- 使用的 ADK 原语(ADK Primitives):
- 层次结构(Hierarchy): 协调员已将相关专家的信息列在……中。
sub_agents. - **交互方式:** 主要用途是(Primarily uses)…… 基于大型语言模型(LLM)的委托机制(LLM-Driven Delegation) (需要明确的说明/指导……)
description关于次级代理人(sub-agents)的相关事宜及适当的处理方式……instruction(在协调器上)或 显式调用(Explicit Invocation)AgentTool) (协调员包括……)AgentTool将那些“被包装起来”的专家(即那些被某种方式“隐藏”或“伪装”起来的专家)纳入其中……tools).
- 层次结构(Hierarchy): 协调员已将相关专家的信息列在……中。
# Conceptual Code: Coordinator using LLM Transfer
from google.adk.agents import LlmAgent
billing_agent = LlmAgent(name="Billing", description="Handles billing inquiries.")
support_agent = LlmAgent(name="Support", description="Handles technical support requests.")
coordinator = LlmAgent(
name="HelpDeskCoordinator",
model="gemini-flash-latest",
instruction="Route user requests: Use Billing agent for payment issues, Support agent for technical problems.",
description="Main help desk router.",
# allow_transfer=True is often implicit with sub_agents in AutoFlow
sub_agents=[billing_agent, support_agent]
)
# User asks "My payment failed" -> Coordinator's LLM should call transfer_to_agent(agent_name='Billing')
# User asks "I can't log in" -> Coordinator's LLM should call transfer_to_agent(agent_name='Support')
// Conceptual Code: Coordinator using LLM Transfer
import { LlmAgent } from '@google/adk';
const billingAgent = new LlmAgent({name: 'Billing', description: 'Handles billing inquiries.'});
const supportAgent = new LlmAgent({name: 'Support', description: 'Handles technical support requests.'});
const coordinator = new LlmAgent({
name: 'HelpDeskCoordinator',
model: 'gemini-flash-latest',
instruction: 'Route user requests: Use Billing agent for payment issues, Support agent for technical problems.',
description: 'Main help desk router.',
// allowTransfer=true is often implicit with subAgents in AutoFlow
subAgents: [billingAgent, supportAgent]
});
// User asks "My payment failed" -> Coordinator's LLM should call {functionCall: {name: 'transfer_to_agent', args: {agent_name: 'Billing'}}}
// User asks "I can't log in" -> Coordinator's LLM should call {functionCall: {name: 'transfer_to_agent', args: {agent_name: 'Support'}}}
import (
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/agent/llmagent"
)
// Conceptual Code: Coordinator using LLM Transfer
billingAgent, _ := llmagent.New(llmagent.Config{Name: "Billing", Description: "Handles billing inquiries.", Model: m})
supportAgent, _ := llmagent.New(llmagent.Config{Name: "Support", Description: "Handles technical support requests.", Model: m})
coordinator, _ := llmagent.New(llmagent.Config{
Name: "HelpDeskCoordinator",
Model: m,
Instruction: "Route user requests: Use Billing agent for payment issues, Support agent for technical problems.",
Description: "Main help desk router.",
SubAgents: []agent.Agent{billingAgent, supportAgent},
})
// User asks "My payment failed" -> Coordinator's LLM should call transfer_to_agent(agent_name='Billing')
// User asks "I can't log in" -> Coordinator's LLM should call transfer_to_agent(agent_name='Support')
// Conceptual Code: Coordinator using LLM Transfer
import com.google.adk.agents.LlmAgent;
LlmAgent billingAgent = LlmAgent.builder()
.name("Billing")
.description("Handles billing inquiries and payment issues.")
.build();
LlmAgent supportAgent = LlmAgent.builder()
.name("Support")
.description("Handles technical support requests and login problems.")
.build();
LlmAgent coordinator = LlmAgent.builder()
.name("HelpDeskCoordinator")
.model("gemini-flash-latest")
.instruction("Route user requests: Use Billing agent for payment issues, Support agent for technical problems.")
.description("Main help desk router.")
.subAgents(billingAgent, supportAgent)
// Agent transfer is implicit with sub agents in the Autoflow, unless specified
// using .disallowTransferToParent or disallowTransferToPeers
.build();
// User asks "My payment failed" -> Coordinator's LLM should call
// transferToAgent(agentName='Billing')
// User asks "I can't log in" -> Coordinator's LLM should call
// transferToAgent(agentName='Support')
val billingAgent =
LlmAgent(name = "Billing", model = model, description = "Handles billing inquiries.")
val supportAgent =
LlmAgent(
name = "Support",
model = model,
description = "Handles technical support requests.",
)
val helpDesk =
LlmAgent(
name = "HelpDeskCoordinator",
model = model,
instruction =
Instruction(
"Route user requests: Use Billing agent for payment issues, Support agent for technical problems.",
),
description = "Main help desk router.",
subAgents = listOf(billingAgent, supportAgent),
)
顺序处理流程(Sequential Pipeline)¶
- 结构: A
SequentialAgent包含;含有sub_agents这些操作会按照固定的顺序依次执行。 - 目标: 实现一个多步骤流程,其中每个步骤的输出都会作为下一个步骤的输入。
- 使用的 ADK 原语(ADK Primitives):
- 工作流程(Workflow):
SequentialAgent定义了执行顺序。 - **沟通(Communication):** 主要用途是(Primarily uses)…… 共享会话状态(Shared Session State)早期的代理程序会直接将处理结果写入文件(通常是通过某种特定的方式或接口)。
output_key后来,代理程序从这些存储的位置中读取了相应的结果。context.state.
- 工作流程(Workflow):
# Conceptual Code: Sequential Data Pipeline
from google.adk.agents import SequentialAgent, LlmAgent
validator = LlmAgent(name="ValidateInput", instruction="Validate the input.", output_key="validation_status")
processor = LlmAgent(name="ProcessData", instruction="Process data if {validation_status} is 'valid'.", output_key="result")
reporter = LlmAgent(name="ReportResult", instruction="Report the result from {result}.")
data_pipeline = SequentialAgent(
name="DataPipeline",
sub_agents=[validator, processor, reporter]
)
# validator runs -> saves to state['validation_status']
# processor runs -> reads state['validation_status'], saves to state['result']
# reporter runs -> reads state['result']
// Conceptual Code: Sequential Data Pipeline
import { SequentialAgent, LlmAgent } from '@google/adk';
const validator = new LlmAgent({name: 'ValidateInput', instruction: 'Validate the input.', outputKey: 'validation_status'});
const processor = new LlmAgent({name: 'ProcessData', instruction: 'Process data if {validation_status} is "valid".', outputKey: 'result'});
const reporter = new LlmAgent({name: 'ReportResult', instruction: 'Report the result from {result}.'});
const dataPipeline = new SequentialAgent({
name: 'DataPipeline',
subAgents: [validator, processor, reporter]
});
// validator runs -> saves to state['validation_status']
// processor runs -> reads state['validation_status'], saves to state['result']
// reporter runs -> reads state['result']
import (
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/agent/workflowagents/sequentialagent"
)
// Conceptual Code: Sequential Data Pipeline
validator, _ := llmagent.New(llmagent.Config{Name: "ValidateInput", Instruction: "Validate the input.", OutputKey: "validation_status", Model: m})
processor, _ := llmagent.New(llmagent.Config{Name: "ProcessData", Instruction: "Process data if {validation_status} is 'valid'.", OutputKey: "result", Model: m})
reporter, _ := llmagent.New(llmagent.Config{Name: "ReportResult", Instruction: "Report the result from {result}.", Model: m})
dataPipeline, _ := sequentialagent.New(sequentialagent.Config{
AgentConfig: agent.Config{Name: "DataPipeline", SubAgents: []agent.Agent{validator, processor, reporter}},
})
// validator runs -> saves to state["validation_status"]
// processor runs -> reads state["validation_status"], saves to state["result"]
// reporter runs -> reads state["result"]
// Conceptual Code: Sequential Data Pipeline
import com.google.adk.agents.SequentialAgent;
LlmAgent validator = LlmAgent.builder()
.name("ValidateInput")
.instruction("Validate the input")
.outputKey("validation_status") // Saves its main text output to session.state["validation_status"]
.build();
LlmAgent processor = LlmAgent.builder()
.name("ProcessData")
.instruction("Process data if {validation_status} is 'valid'")
.outputKey("result") // Saves its main text output to session.state["result"]
.build();
LlmAgent reporter = LlmAgent.builder()
.name("ReportResult")
.instruction("Report the result from {result}")
.build();
SequentialAgent dataPipeline = SequentialAgent.builder()
.name("DataPipeline")
.subAgents(validator, processor, reporter)
.build();
// validator runs -> saves to state['validation_status']
// processor runs -> reads state['validation_status'], saves to state['result']
// reporter runs -> reads state['result']
val validator =
LlmAgent(
name = "ValidateInput",
model = model,
instruction = Instruction("Validate the input."),
)
val processor =
LlmAgent(
name = "ProcessData",
model = model,
instruction = Instruction("Process data if validation is successful."),
)
val reporter =
LlmAgent(
name = "ReportResult",
model = model,
instruction = Instruction("Report the result."),
)
val dataPipeline =
SequentialAgent(
name = "DataPipeline",
subAgents = listOf(validator, processor, reporter),
)
并行式的“扇出”(fan-out)与“聚合”(gather)操作¶
- 结构: A
ParallelAgent可以同时运行多个(程序或任务)。sub_agents同时,通常会由另一个代理(在后续阶段)来继续处理该任务。SequentialAgent)该工具用于汇总各种结果。 - 目标: 同时执行独立的任务以减少延迟,之后再将这些任务的输出结果合并在一起。
- 使用的 ADK 原语(ADK Primitives):
- 工作流程(Workflow):
ParallelAgent用于并发执行(即“Fan-Out”模式)。通常会嵌套在其他结构中。SequentialAgent用于处理后续的聚合步骤(即数据收集/整合)。 - **沟通(Communication):** 子代理将结果写入不同的键中(即:每个子代理将结果存储在对应的键中)。 共享会话状态(Shared Session State)随后的“Gather”代理会读取多个状态键(state keys)。
- 工作流程(Workflow):
# Conceptual Code: Parallel Information Gathering
from google.adk.agents import SequentialAgent, ParallelAgent, LlmAgent
fetch_api1 = LlmAgent(name="API1Fetcher", instruction="Fetch data from API 1.", output_key="api1_data")
fetch_api2 = LlmAgent(name="API2Fetcher", instruction="Fetch data from API 2.", output_key="api2_data")
gather_concurrently = ParallelAgent(
name="ConcurrentFetch",
sub_agents=[fetch_api1, fetch_api2]
)
synthesizer = LlmAgent(
name="Synthesizer",
instruction="Combine results from {api1_data} and {api2_data}."
)
overall_workflow = SequentialAgent(
name="FetchAndSynthesize",
sub_agents=[gather_concurrently, synthesizer] # Run parallel fetch, then synthesize
)
# fetch_api1 and fetch_api2 run concurrently, saving to state.
# synthesizer runs afterwards, reading state['api1_data'] and state['api2_data'].
// Conceptual Code: Parallel Information Gathering
import { SequentialAgent, ParallelAgent, LlmAgent } from '@google/adk';
const fetchApi1 = new LlmAgent({name: 'API1Fetcher', instruction: 'Fetch data from API 1.', outputKey: 'api1_data'});
const fetchApi2 = new LlmAgent({name: 'API2Fetcher', instruction: 'Fetch data from API 2.', outputKey: 'api2_data'});
const gatherConcurrently = new ParallelAgent({
name: 'ConcurrentFetch',
subAgents: [fetchApi1, fetchApi2]
});
const synthesizer = new LlmAgent({
name: 'Synthesizer',
instruction: 'Combine results from {api1_data} and {api2_data}.'
});
const overallWorkflow = new SequentialAgent({
name: 'FetchAndSynthesize',
subAgents: [gatherConcurrently, synthesizer] // Run parallel fetch, then synthesize
});
// fetchApi1 and fetchApi2 run concurrently, saving to state.
// synthesizer runs afterwards, reading state['api1_data'] and state['api2_data'].
import (
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/agent/workflowagents/parallelagent"
"google.golang.org/adk/v2/agent/workflowagents/sequentialagent"
)
// Conceptual Code: Parallel Information Gathering
fetchAPI1, _ := llmagent.New(llmagent.Config{Name: "API1Fetcher", Instruction: "Fetch data from API 1.", OutputKey: "api1_data", Model: m})
fetchAPI2, _ := llmagent.New(llmagent.Config{Name: "API2Fetcher", Instruction: "Fetch data from API 2.", OutputKey: "api2_data", Model: m})
gatherConcurrently, _ := parallelagent.New(parallelagent.Config{
AgentConfig: agent.Config{Name: "ConcurrentFetch", SubAgents: []agent.Agent{fetchAPI1, fetchAPI2}},
})
synthesizer, _ := llmagent.New(llmagent.Config{Name: "Synthesizer", Instruction: "Combine results from {api1_data} and {api2_data}.", Model: m})
overallWorkflow, _ := sequentialagent.New(sequentialagent.Config{
AgentConfig: agent.Config{Name: "FetchAndSynthesize", SubAgents: []agent.Agent{gatherConcurrently, synthesizer}},
})
// fetch_api1 and fetch_api2 run concurrently, saving to state.
// synthesizer runs afterwards, reading state["api1_data"] and state["api2_data"].
// Conceptual Code: Parallel Information Gathering
import com.google.adk.agents.LlmAgent;
import com.google.adk.agents.ParallelAgent;
import com.google.adk.agents.SequentialAgent;
LlmAgent fetchApi1 = LlmAgent.builder()
.name("API1Fetcher")
.instruction("Fetch data from API 1.")
.outputKey("api1_data")
.build();
LlmAgent fetchApi2 = LlmAgent.builder()
.name("API2Fetcher")
.instruction("Fetch data from API 2.")
.outputKey("api2_data")
.build();
ParallelAgent gatherConcurrently = ParallelAgent.builder()
.name("ConcurrentFetcher")
.subAgents(fetchApi2, fetchApi1)
.build();
LlmAgent synthesizer = LlmAgent.builder()
.name("Synthesizer")
.instruction("Combine results from {api1_data} and {api2_data}.")
.build();
SequentialAgent overallWorfklow = SequentialAgent.builder()
.name("FetchAndSynthesize") // Run parallel fetch, then synthesize
.subAgents(gatherConcurrently, synthesizer)
.build();
// fetch_api1 and fetch_api2 run concurrently, saving to state.
// synthesizer runs afterwards, reading state['api1_data'] and state['api2_data'].
val fetchApi1 =
LlmAgent(
name = "API1Fetcher",
model = model,
instruction = Instruction("Fetch data from API 1."),
)
val fetchApi2 =
LlmAgent(
name = "API2Fetcher",
model = model,
instruction = Instruction("Fetch data from API 2."),
)
val gatherConcurrently =
ParallelAgent(
name = "ConcurrentFetch",
subAgents = listOf(fetchApi1, fetchApi2),
)
val synthesizer =
LlmAgent(
name = "Synthesizer",
model = model,
instruction = Instruction("Combine results from state."),
)
val overallWorkflow =
SequentialAgent(
name = "FetchAndSynthesize",
subAgents = listOf(gatherConcurrently, synthesizer),
)
分层任务分解(Hierarchical Task Decomposition)¶
- 结构: 这是一个由代理组成的多层次结构:高层代理负责分解复杂的目标,并将子任务分配给低层代理。
- 目标: 通过递归地将复杂问题分解为更简单、更易于执行的步骤来解决这些问题。
- 使用的 ADK 原语(ADK Primitives):
- 层次结构(Hierarchy): 多级(结构)
parent_agent/sub_agentsstructure. - **交互方式:** 主要地;首要地 基于大型语言模型(LLM)的委托机制(LLM-Driven Delegation) 或者 显式调用(Explicit Invocation)
AgentTool) 由上级代理(parent agents)用于向下级代理(subagents)分配任务。任务执行的结果会通过工具响应(tool responses)或状态变化(state changes)的方式逐级向上级代理反馈。
- 层次结构(Hierarchy): 多级(结构)
# Conceptual Code: Hierarchical Research Task
from google.adk.agents import LlmAgent
from google.adk.tools import agent_tool
# Low-level tool-like agents
web_searcher = LlmAgent(name="WebSearch", description="Performs web searches for facts.")
summarizer = LlmAgent(name="Summarizer", description="Summarizes text.")
# Mid-level agent combining tools
research_assistant = LlmAgent(
name="ResearchAssistant",
model="gemini-flash-latest",
description="Finds and summarizes information on a topic.",
tools=[agent_tool.AgentTool(agent=web_searcher), agent_tool.AgentTool(agent=summarizer)]
)
# High-level agent delegating research
report_writer = LlmAgent(
name="ReportWriter",
model="gemini-flash-latest",
instruction="Write a report on topic X. Use the ResearchAssistant to gather information.",
tools=[agent_tool.AgentTool(agent=research_assistant)]
# Alternatively, could use LLM Transfer if research_assistant is a sub_agent
)
# User interacts with ReportWriter.
# ReportWriter calls ResearchAssistant tool.
# ResearchAssistant calls WebSearch and Summarizer tools.
# Results flow back up.
// Conceptual Code: Hierarchical Research Task
import { LlmAgent, AgentTool } from '@google/adk';
// Low-level tool-like agents
const webSearcher = new LlmAgent({name: 'WebSearch', description: 'Performs web searches for facts.'});
const summarizer = new LlmAgent({name: 'Summarizer', description: 'Summarizes text.'});
// Mid-level agent combining tools
const researchAssistant = new LlmAgent({
name: 'ResearchAssistant',
model: 'gemini-flash-latest',
description: 'Finds and summarizes information on a topic.',
tools: [new AgentTool({agent: webSearcher}), new AgentTool({agent: summarizer})]
});
// High-level agent delegating research
const reportWriter = new LlmAgent({
name: 'ReportWriter',
model: 'gemini-flash-latest',
instruction: 'Write a report on topic X. Use the ResearchAssistant to gather information.',
tools: [new AgentTool({agent: researchAssistant})]
// Alternatively, could use LLM Transfer if researchAssistant is a subAgent
});
// User interacts with ReportWriter.
// ReportWriter calls ResearchAssistant tool.
// ResearchAssistant calls WebSearch and Summarizer tools.
// Results flow back up.
import (
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/tool"
"google.golang.org/adk/v2/tool/agenttool"
)
// Conceptual Code: Hierarchical Research Task
// Low-level tool-like agents
webSearcher, _ := llmagent.New(llmagent.Config{Name: "WebSearch", Description: "Performs web searches for facts.", Model: m})
summarizer, _ := llmagent.New(llmagent.Config{Name: "Summarizer", Description: "Summarizes text.", Model: m})
// Mid-level agent combining tools
webSearcherTool := agenttool.New(webSearcher, nil)
summarizerTool := agenttool.New(summarizer, nil)
researchAssistant, _ := llmagent.New(llmagent.Config{
Name: "ResearchAssistant",
Model: m,
Description: "Finds and summarizes information on a topic.",
Tools: []tool.Tool{webSearcherTool, summarizerTool},
})
// High-level agent delegating research
researchAssistantTool := agenttool.New(researchAssistant, nil)
reportWriter, _ := llmagent.New(llmagent.Config{
Name: "ReportWriter",
Model: m,
Instruction: "Write a report on topic X. Use the ResearchAssistant to gather information.",
Tools: []tool.Tool{researchAssistantTool},
})
// User interacts with ReportWriter.
// ReportWriter calls ResearchAssistant tool.
// ResearchAssistant calls WebSearch and Summarizer tools.
// Results flow back up.
// Conceptual Code: Hierarchical Research Task
import com.google.adk.agents.LlmAgent;
import com.google.adk.tools.AgentTool;
// Low-level tool-like agents
LlmAgent webSearcher = LlmAgent.builder()
.name("WebSearch")
.description("Performs web searches for facts.")
.build();
LlmAgent summarizer = LlmAgent.builder()
.name("Summarizer")
.description("Summarizes text.")
.build();
// Mid-level agent combining tools
LlmAgent researchAssistant = LlmAgent.builder()
.name("ResearchAssistant")
.model("gemini-flash-latest")
.description("Finds and summarizes information on a topic.")
.tools(AgentTool.create(webSearcher), AgentTool.create(summarizer))
.build();
// High-level agent delegating research
LlmAgent reportWriter = LlmAgent.builder()
.name("ReportWriter")
.model("gemini-flash-latest")
.instruction("Write a report on topic X. Use the ResearchAssistant to gather information.")
.tools(AgentTool.create(researchAssistant))
// Alternatively, could use LLM Transfer if research_assistant is a subAgent
.build();
// User interacts with ReportWriter.
// ReportWriter calls ResearchAssistant tool.
// ResearchAssistant calls WebSearch and Summarizer tools.
// Results flow back up.
val webSearcher =
LlmAgent(
name = "WebSearch",
model = model,
description = "Performs web searches for facts.",
)
val summarizer = LlmAgent(name = "Summarizer", model = model, description = "Summarizes text.")
val researchAssistant =
LlmAgent(
name = "ResearchAssistant",
model = model,
description = "Finds and summarizes information on a topic.",
subAgents = listOf(webSearcher, summarizer),
)
val reportWriter =
LlmAgent(
name = "ReportWriter",
model = model,
instruction =
Instruction(
"Write a report on topic X. Use the ResearchAssistant to gather information.",
),
subAgents = listOf(researchAssistant),
)
生成并审查相关模式(pattern)。¶
- 结构: 通常涉及两个代理人(agents)在某个系统或流程中共同完成某项任务。
SequentialAgent:一个生成器代理(generator agent)和一个评论者代理(critic reviewer agent)。 - 目标: 通过指派专门的审核人员来审查生成的输出内容,可以提高其质量或有效性。
- 使用的 ADK 原语(ADK Primitives):
- 工作流程(Workflow):
SequentialAgent确保在评审之前完成生成过程。 - **沟通(Communication):** 共享会话状态(Shared Session State) (生成器使用了……)
output_key为了节省输出内容,审核者会读取该状态键(Reviewer reads that state key)。审核者可能会将其反馈信息保存到另一个状态键中,以供后续步骤使用。
- 工作流程(Workflow):
# Conceptual Code: Generator-Critic
from google.adk.agents import SequentialAgent, LlmAgent
generator = LlmAgent(
name="DraftWriter",
instruction="Write a short paragraph about subject X.",
output_key="draft_text"
)
reviewer = LlmAgent(
name="FactChecker",
instruction="Review the text in {draft_text} for factual accuracy. Output 'valid' or 'invalid' with reasons.",
output_key="review_status"
)
# Optional: Further steps based on review_status
review_pipeline = SequentialAgent(
name="WriteAndReview",
sub_agents=[generator, reviewer]
)
# generator runs -> saves draft to state['draft_text']
# reviewer runs -> reads state['draft_text'], saves status to state['review_status']
// Conceptual Code: Generator-Critic
import { SequentialAgent, LlmAgent } from '@google/adk';
const generator = new LlmAgent({
name: 'DraftWriter',
instruction: 'Write a short paragraph about subject X.',
outputKey: 'draft_text'
});
const reviewer = new LlmAgent({
name: 'FactChecker',
instruction: 'Review the text in {draft_text} for factual accuracy. Output "valid" or "invalid" with reasons.',
outputKey: 'review_status'
});
// Optional: Further steps based on review_status
const reviewPipeline = new SequentialAgent({
name: 'WriteAndReview',
subAgents: [generator, reviewer]
});
// generator runs -> saves draft to state['draft_text']
// reviewer runs -> reads state['draft_text'], saves status to state['review_status']
import (
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/agent/workflowagents/sequentialagent"
)
// Conceptual Code: Generator-Critic
generator, _ := llmagent.New(llmagent.Config{
Name: "DraftWriter",
Instruction: "Write a short paragraph about subject X.",
OutputKey: "draft_text",
Model: m,
})
reviewer, _ := llmagent.New(llmagent.Config{
Name: "FactChecker",
Instruction: "Review the text in {draft_text} for factual accuracy. Output 'valid' or 'invalid' with reasons.",
OutputKey: "review_status",
Model: m,
})
reviewPipeline, _ := sequentialagent.New(sequentialagent.Config{
AgentConfig: agent.Config{Name: "WriteAndReview", SubAgents: []agent.Agent{generator, reviewer}},
})
// generator runs -> saves draft to state["draft_text"]
// reviewer runs -> reads state["draft_text"], saves status to state["review_status"]
// Conceptual Code: Generator-Critic
import com.google.adk.agents.LlmAgent;
import com.google.adk.agents.SequentialAgent;
LlmAgent generator = LlmAgent.builder()
.name("DraftWriter")
.instruction("Write a short paragraph about subject X.")
.outputKey("draft_text")
.build();
LlmAgent reviewer = LlmAgent.builder()
.name("FactChecker")
.instruction("Review the text in {draft_text} for factual accuracy. Output 'valid' or 'invalid' with reasons.")
.outputKey("review_status")
.build();
// Optional: Further steps based on review_status
SequentialAgent reviewPipeline = SequentialAgent.builder()
.name("WriteAndReview")
.subAgents(generator, reviewer)
.build();
// generator runs -> saves draft to state['draft_text']
// reviewer runs -> reads state['draft_text'], saves status to state['review_status']
val generator =
LlmAgent(
name = "DraftWriter",
model = model,
instruction = Instruction("Write a short paragraph about subject X."),
)
val reviewer =
LlmAgent(
name = "FactChecker",
model = model,
instruction =
Instruction(
"Review the generated text for factual accuracy. Output 'valid' or 'invalid' with reasons.",
),
)
val reviewPipeline =
SequentialAgent(
name = "WriteAndReview",
subAgents = listOf(generator, reviewer),
)
迭代优化(Iterative refinement)¶
- 结构: 使用(某种方法或工具)
LoopAgent该系统包含一个或多个代理(agents),这些代理会在多次迭代过程中执行某项任务。 - 目标: 逐步改进存储在会话状态中的结果(例如代码、文本或计划),直到达到质量阈值或迭代次数达到上限为止。
- 使用的 ADK 原语(ADK Primitives):
- 工作流程(Workflow):
LoopAgent负责管理重复内容的处理(即防止内容被重复显示或重复发送)。 - **沟通(Communication):** 共享会话状态(Shared Session State) 对于代理来说,阅读上一次迭代的输出结果并保存经过修改后的版本是至关重要的。
- 终止: 循环通常会根据某个条件来结束。
max_iterations或者是由专门的支票处理机构来处理这些事务。escalate=True在……里面;在……期间Event Actions当结果令人满意时。
- 工作流程(Workflow):
# Conceptual Code: Iterative Code Refinement
from google.adk.agents import LoopAgent, LlmAgent, BaseAgent
from google.adk.events import Event, EventActions
from google.adk.agents.invocation_context import InvocationContext
from typing import AsyncGenerator
# Agent to generate/refine code based on state['current_code'] and state['requirements']
code_refiner = LlmAgent(
name="CodeRefiner",
instruction="Read state['current_code'] (if exists) and state['requirements']. Generate/refine Python code to meet requirements. Save to state['current_code'].",
output_key="current_code" # Overwrites previous code in state
)
# Agent to check if the code meets quality standards
quality_checker = LlmAgent(
name="QualityChecker",
instruction="Evaluate the code in state['current_code'] against state['requirements']. Output 'pass' or 'fail'.",
output_key="quality_status"
)
# Custom agent to check the status and escalate if 'pass'
class CheckStatusAndEscalate(BaseAgent):
async def _run_async_impl(self, ctx: InvocationContext) -> AsyncGenerator[Event, None]:
status = ctx.session.state.get("quality_status", "fail")
should_stop = (status == "pass")
yield Event(author=self.name, actions=EventActions(escalate=should_stop))
refinement_loop = LoopAgent(
name="CodeRefinementLoop",
max_iterations=5,
sub_agents=[code_refiner, quality_checker, CheckStatusAndEscalate(name="StopChecker")]
)
# Loop runs: Refiner -> Checker -> StopChecker
# State['current_code'] is updated each iteration.
# Loop stops if QualityChecker outputs 'pass' (leading to StopChecker escalating) or after 5 iterations.
// Conceptual Code: Iterative Code Refinement
import { LoopAgent, LlmAgent, BaseAgent, InvocationContext } from '@google/adk';
import type { Event, createEvent, createEventActions } from '@google/genai';
// Agent to generate/refine code based on state['current_code'] and state['requirements']
const codeRefiner = new LlmAgent({
name: 'CodeRefiner',
instruction: 'Read state["current_code"] (if exists) and state["requirements"]. Generate/refine TypeScript code to meet requirements. Save to state["current_code"].',
outputKey: 'current_code' // Overwrites previous code in state
});
// Agent to check if the code meets quality standards
const qualityChecker = new LlmAgent({
name: 'QualityChecker',
instruction: 'Evaluate the code in state["current_code"] against state["requirements"]. Output "pass" or "fail".',
outputKey: 'quality_status'
});
// Custom agent to check the status and escalate if 'pass'
class CheckStatusAndEscalate extends BaseAgent {
async *runAsyncImpl(ctx: InvocationContext): AsyncGenerator<Event> {
const status = ctx.session.state.quality_status;
const shouldStop = status === 'pass';
if (shouldStop) {
yield createEvent({
author: 'StopChecker',
actions: createEventActions(),
});
}
}
async *runLiveImpl(ctx: InvocationContext): AsyncGenerator<Event> {
// This agent doesn't have a live implementation
yield createEvent({ author: 'StopChecker' });
}
}
// Loop runs: Refiner -> Checker -> StopChecker
// State['current_code'] is updated each iteration.
// Loop stops if QualityChecker outputs 'pass' (leading to StopChecker escalating) or after 5 iterations.
const refinementLoop = new LoopAgent({
name: 'CodeRefinementLoop',
maxIterations: 5,
subAgents: [codeRefiner, qualityChecker, new CheckStatusAndEscalate({name: 'StopChecker'})]
});
import (
"iter"
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/agent/workflowagents/loopagent"
"google.golang.org/adk/v2/session"
)
// Conceptual Code: Iterative Code Refinement
codeRefiner, _ := llmagent.New(llmagent.Config{
Name: "CodeRefiner",
Instruction: "Read state['current_code'] (if exists) and state['requirements']. Generate/refine Python code to meet requirements. Save to state['current_code'].",
OutputKey: "current_code",
Model: m,
})
qualityChecker, _ := llmagent.New(llmagent.Config{
Name: "QualityChecker",
Instruction: "Evaluate the code in state['current_code'] against state['requirements']. Output 'pass' or 'fail'.",
OutputKey: "quality_status",
Model: m,
})
checkStatusAndEscalate, _ := agent.New(agent.Config{
Name: "StopChecker",
Run: func(ctx agent.InvocationContext) iter.Seq2[*session.Event, error] {
return func(yield func(*session.Event, error) bool) {
status, _ := ctx.Session().State().Get("quality_status")
shouldStop := status == "pass"
yield(&session.Event{Author: "StopChecker", Actions: session.EventActions{Escalate: shouldStop}}, nil)
}
},
})
refinementLoop, _ := loopagent.New(loopagent.Config{
MaxIterations: 5,
AgentConfig: agent.Config{Name: "CodeRefinementLoop", SubAgents: []agent.Agent{codeRefiner, qualityChecker, checkStatusAndEscalate}},
})
// Loop runs: Refiner -> Checker -> StopChecker
// State["current_code"] is updated each iteration.
// Loop stops if QualityChecker outputs 'pass' (leading to StopChecker escalating) or after 5 iterations.
// Conceptual Code: Iterative Code Refinement
import com.google.adk.agents.BaseAgent;
import com.google.adk.agents.LlmAgent;
import com.google.adk.agents.LoopAgent;
import com.google.adk.events.Event;
import com.google.adk.events.EventActions;
import com.google.adk.agents.InvocationContext;
import io.reactivex.rxjava3.core.Flowable;
import java.util.List;
// Agent to generate/refine code based on state['current_code'] and state['requirements']
LlmAgent codeRefiner = LlmAgent.builder()
.name("CodeRefiner")
.instruction("Read state['current_code'] (if exists) and state['requirements']. Generate/refine Java code to meet requirements. Save to state['current_code'].")
.outputKey("current_code") // Overwrites previous code in state
.build();
// Agent to check if the code meets quality standards
LlmAgent qualityChecker = LlmAgent.builder()
.name("QualityChecker")
.instruction("Evaluate the code in state['current_code'] against state['requirements']. Output 'pass' or 'fail'.")
.outputKey("quality_status")
.build();
BaseAgent checkStatusAndEscalate = new BaseAgent(
"StopChecker","Checks quality_status and escalates if 'pass'.", List.of(), null, null) {
@Override
protected Flowable<Event> runAsyncImpl(InvocationContext invocationContext) {
String status = (String) invocationContext.session().state().getOrDefault("quality_status", "fail");
boolean shouldStop = "pass".equals(status);
EventActions actions = EventActions.builder().escalate(shouldStop).build();
Event event = Event.builder()
.author(this.name())
.actions(actions)
.build();
return Flowable.just(event);
}
};
LoopAgent refinementLoop = LoopAgent.builder()
.name("CodeRefinementLoop")
.maxIterations(5)
.subAgents(codeRefiner, qualityChecker, checkStatusAndEscalate)
.build();
// Loop runs: Refiner -> Checker -> StopChecker
// State['current_code'] is updated each iteration.
// Loop stops if QualityChecker outputs 'pass' (leading to StopChecker escalating) or after 5
// iterations.
val codeRefiner =
LlmAgent(
name = "CodeRefiner",
model = model,
instruction =
Instruction(
"Read current code (if exists) and requirements from state. Generate/refine Kotlin code to meet requirements.",
),
)
val qualityChecker =
LlmAgent(
name = "QualityChecker",
model = model,
instruction =
Instruction(
"Evaluate the code in state against requirements. Output 'pass' or 'fail'.",
),
)
val stopChecker = CheckConditionAgent(name = "StopChecker") // Checks quality_status
val refinementLoop =
LoopAgent(
name = "CodeRefinementLoop",
maxIterations = 5,
subAgents = listOf(codeRefiner, qualityChecker, stopChecker),
)
“人在回路中”(Human-in-the-loop)是一种人工智能(AI)系统设计方法,强调在AI系统做出决策或执行任务时,需要人类的参与和监督。这种方法认为,尽管AI在某些方面可能具有很高的效率和准确性,但人类的判断力、创造力以及对情境的理解能力仍然是不可或缺的。通过人在回路中的机制,可以确保AI系统的决策符合人类的价值观、道德标准和社会需求,同时也可以及时发现和纠正AI可能产生的错误或偏差。¶
- 结构: 将人工干预环节整合到代理的工作流程中。
- 目标: 需要考虑人工监督、审批、纠正等工作,因为这些是人工智能无法完成的。
- 使用的 ADK 原语(概念性说明):
- **交互方式:** 可以使用自定义的方法来实现。 工具 该功能会暂停程序的执行,并向外部系统(例如用户界面或工单管理系统)发送请求,以等待用户的输入。之后,该工具会将用户的回复发送给处理该请求的代理。
- 工作流程(Workflow): “Could use” 的意思是“需要(或希望)某样东西”。例如:“We could use some more time to finish this project.”(我们需要更多时间来完成这个项目。) 基于大型语言模型(LLM)的委托机制(LLM-Driven Delegation) (
transfer_to_agent)该方案针对的是一个概念性的“人类代理”(Human Agent),该代理负责触发外部工作流程;或者也可以在系统内部直接使用自定义工具。LlmAgent. - 状态/回调函数(State/Callbacks): “State”(状态)可以存储供人类使用的任务详细信息;“Callbacks”(回调函数)则可以管理交互流程。
- 注意: ADK 没有……(“没有”后面的内容在原文本中没有提供。) 人类代理(Human Agent) 代理类型(agent type),但你无需自己实现暂停功能(pause function):只需调用 `yield` 即可。
RequestInput来自某个事件的…… 图工作流节点(Graph Workflow Node)或者启用它。 工具确认(Tool Confirmation) 在……的时候;当……的情况下FunctionTool用于获取“是/否”的审批结果。如需提供自定义提示或收集结构化数据,请使用…… 高级确认功能 该工具内部提供了相应功能;有关每种语言的支持信息,请参阅相关页面。
# Conceptual Code: Using a Tool for Human Approval
from google.adk.agents import LlmAgent, SequentialAgent
from google.adk.tools import FunctionTool
# --- Assume external_approval_tool exists ---
# This tool would:
# 1. Take details (e.g., request_id, amount, reason).
# 2. Send these details to a human review system (e.g., via API).
# 3. Poll or wait for the human response (approved/rejected).
# 4. Return the human's decision.
# async def external_approval_tool(amount: float, reason: str) -> str: ...
approval_tool = FunctionTool(func=external_approval_tool)
# Agent that prepares the request
prepare_request = LlmAgent(
name="PrepareApproval",
instruction="Prepare the approval request details based on user input. Store amount and reason in state.",
# ... likely sets state['approval_amount'] and state['approval_reason'] ...
)
# Agent that calls the human approval tool
request_approval = LlmAgent(
name="RequestHumanApproval",
instruction="Use the external_approval_tool with amount from state['approval_amount'] and reason from state['approval_reason'].",
tools=[approval_tool],
output_key="human_decision"
)
# Agent that proceeds based on human decision
process_decision = LlmAgent(
name="ProcessDecision",
instruction="Check {human_decision}. If 'approved', proceed. If 'rejected', inform user."
)
approval_workflow = SequentialAgent(
name="HumanApprovalWorkflow",
sub_agents=[prepare_request, request_approval, process_decision]
)
// Conceptual Code: Using a Tool for Human Approval
import { LlmAgent, SequentialAgent, FunctionTool } from '@google/adk';
import { z } from 'zod';
// --- Assume externalApprovalTool exists ---
// This tool would:
// 1. Take details (e.g., request_id, amount, reason).
// 2. Send these details to a human review system (e.g., via API).
// 3. Poll or wait for the human response (approved/rejected).
// 4. Return the human's decision.
async function externalApprovalTool(params: {amount: number, reason: string}): Promise<{decision: string}> {
// ... implementation to call external system
return {decision: 'approved'}; // or 'rejected'
}
const approvalTool = new FunctionTool({
name: 'external_approval_tool',
description: 'Sends a request for human approval.',
parameters: z.object({
amount: z.number(),
reason: z.string(),
}),
execute: externalApprovalTool,
});
// Agent that prepares the request
const prepareRequest = new LlmAgent({
name: 'PrepareApproval',
instruction: 'Prepare the approval request details based on user input. Store amount and reason in state.',
// ... likely sets state['approval_amount'] and state['approval_reason'] ...
});
// Agent that calls the human approval tool
const requestApproval = new LlmAgent({
name: 'RequestHumanApproval',
instruction: 'Use the external_approval_tool with amount from state["approval_amount"] and reason from state["approval_reason"].',
tools: [approvalTool],
outputKey: 'human_decision'
});
// Agent that proceeds based on human decision
const processDecision = new LlmAgent({
name: 'ProcessDecision',
instruction: 'Check {human_decision}. If "approved", proceed. If "rejected", inform user.'
});
const approvalWorkflow = new SequentialAgent({
name: 'HumanApprovalWorkflow',
subAgents: [prepareRequest, requestApproval, processDecision]
});
import (
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/agent/workflowagents/sequentialagent"
"google.golang.org/adk/v2/tool"
)
// Conceptual Code: Using a Tool for Human Approval
// --- Assume externalApprovalTool exists ---
// func externalApprovalTool(amount float64, reason string) (string, error) { ... }
type externalApprovalToolArgs struct {
Amount float64 `json:"amount" jsonschema:"The amount for which approval is requested."`
Reason string `json:"reason" jsonschema:"The reason for the approval request."`
}
var externalApprovalTool func(agent.Context, externalApprovalToolArgs) (string, error)
approvalTool, _ := functiontool.New(
functiontool.Config{
Name: "external_approval_tool",
Description: "Sends a request for human approval.",
},
externalApprovalTool,
)
prepareRequest, _ := llmagent.New(llmagent.Config{
Name: "PrepareApproval",
Instruction: "Prepare the approval request details based on user input. Store amount and reason in state.",
Model: m,
})
requestApproval, _ := llmagent.New(llmagent.Config{
Name: "RequestHumanApproval",
Instruction: "Use the external_approval_tool with amount from state['approval_amount'] and reason from state['approval_reason'].",
Tools: []tool.Tool{approvalTool},
OutputKey: "human_decision",
Model: m,
})
processDecision, _ := llmagent.New(llmagent.Config{
Name: "ProcessDecision",
Instruction: "Check {human_decision}. If 'approved', proceed. If 'rejected', inform user.",
Model: m,
})
approvalWorkflow, _ := sequentialagent.New(sequentialagent.Config{
AgentConfig: agent.Config{Name: "HumanApprovalWorkflow", SubAgents: []agent.Agent{prepareRequest, requestApproval, processDecision}},
})
// Conceptual Code: Using a Tool for Human Approval
import com.google.adk.agents.LlmAgent;
import com.google.adk.agents.SequentialAgent;
import com.google.adk.tools.FunctionTool;
// --- Assume external_approval_tool exists ---
// This tool would:
// 1. Take details (e.g., request_id, amount, reason).
// 2. Send these details to a human review system (e.g., via API).
// 3. Poll or wait for the human response (approved/rejected).
// 4. Return the human's decision.
// public boolean externalApprovalTool(float amount, String reason) { ... }
FunctionTool approvalTool = FunctionTool.create(externalApprovalTool);
// Agent that prepares the request
LlmAgent prepareRequest = LlmAgent.builder()
.name("PrepareApproval")
.instruction("Prepare the approval request details based on user input. Store amount and reason in state.")
// ... likely sets state['approval_amount'] and state['approval_reason'] ...
.build();
// Agent that calls the human approval tool
LlmAgent requestApproval = LlmAgent.builder()
.name("RequestHumanApproval")
.instruction("Use the external_approval_tool with amount from state['approval_amount'] and reason from state['approval_reason'].")
.tools(approvalTool)
.outputKey("human_decision")
.build();
// Agent that proceeds based on human decision
LlmAgent processDecision = LlmAgent.builder()
.name("ProcessDecision")
.instruction("Check {human_decision}. If 'approved', proceed. If 'rejected', inform user.")
.build();
SequentialAgent approvalWorkflow = SequentialAgent.builder()
.name("HumanApprovalWorkflow")
.subAgents(prepareRequest, requestApproval, processDecision)
.build();
val approvalTool = ExternalApprovalTool()
val prepareRequest =
LlmAgent(
name = "PrepareApproval",
model = model,
instruction =
Instruction(
"Prepare the approval request details based on user input. Store amount and reason in state.",
),
)
val requestApproval =
LlmAgent(
name = "RequestHumanApproval",
model = model,
instruction =
Instruction(
"Use the external_approval_tool to get approval for the request in state.",
),
tools = listOf(approvalTool),
)
val processDecision =
LlmAgent(
name = "ProcessDecision",
model = model,
instruction =
Instruction(
"Check the human decision in state. If 'approved', proceed. If 'rejected', inform user.",
),
)
val approvalWorkflow =
SequentialAgent(
name = "HumanApprovalWorkflow",
subAgents = listOf(prepareRequest, requestApproval, processDecision),
)
“人在决策过程中发挥作用”(Human in the decision-making process)¶
一种更先进、更结构化的方法来实现“人在回路中”(Human-in-the-Loop)机制,就是使用…… PolicyEngine这种方法允许你定义一些策略,这些策略可以在工具执行之前触发用户的确认操作。 SecurityPlugin 拦截某个工具调用(tool call),然后查询相关数据。 PolicyEngine如果政策有相应规定,系统会自动请求用户的确认。这种机制在实施治理规则和安全策略方面更为可靠(即更加有效)。
其工作原理如下:
SecurityPlugin您需要将此插件添加到您的系统中。Runner它充当所有工具调用的拦截器(即会在这些调用发生之前对其进行拦截和处理)。BasePolicyEngine你需要创建一个自定义类,该类实现这个接口。evaluate()该方法包含了用于判断某个工具调用是否需要确认的逻辑。PolicyOutcome.CONFIRM:当你的……evaluate()该方法返回此结果。SecurityPlugin该功能会暂停工具的执行,并生成一个特殊的文件/数据(具体内容取决于应用程序的设计)。FunctionCallusinggetAskUserConfirmationFunctionCalls.- 应用程序处理(Application Handling)您的应用程序代码会接收到这个特殊的函数调用,并向用户显示确认请求。
- 用户确认(User Confirmation):一旦用户确认,您的应用程序就会发送一条消息。
FunctionResponse“返回到代理(agent)”这一操作允许……SecurityPlugin继续执行原始工具(即原来的程序或命令)。
TypeScript 推荐的模式(Recommended Pattern)
基于策略(Policy-based)的模式是用于在 TypeScript 中实现“人在循环中”(Human-in-the-Loop)工作流程的推荐方法。其他 ADK 语言对该模式的支持计划将在未来的版本中提供。
这是一个关于如何使用该工具的概念性示例。 CustomPolicyEngine 如下所示:在执行任何工具之前,系统会要求用户进行确认。
const rootAgent = new LlmAgent({
name: 'weather_time_agent',
model: 'gemini-flash-latest',
description:
'Agent to answer questions about the time and weather in a city.',
instruction:
'You are a helpful agent who can answer user questions about the time and weather in a city.',
tools: [getWeatherTool],
});
class CustomPolicyEngine implements BasePolicyEngine {
async evaluate(_context: ToolCallPolicyContext): Promise<PolicyCheckResult> {
// Default permissive implementation
return Promise.resolve({
outcome: PolicyOutcome.CONFIRM,
reason: 'Needs confirmation for tool call',
});
}
}
const runner = new InMemoryRunner({
agent: rootAgent,
appName,
plugins: [new SecurityPlugin({policyEngine: new CustomPolicyEngine()})]
});
有关完整的实现方式,请参阅…… 代码示例.