为代理工作流程构建图形化路由(即可视化的数据传输路径)。¶
在 ADK 中,基于图的工作流程将代理逻辑表示为由执行节点和边组成的图结构。这种设计使得构建更加可靠的过程成为可能,这些过程结合了人工智能(AI)的推理能力与代码逻辑。通过这种方式,可以创建包含执行节点的逻辑路径,这些路径能够封装代码功能、由 AI 驱动的代理程序以及人类输入的数据。通过明确地规划数据传输的逻辑流程,可以在代码中定义出具体且分步骤的执行流程,从而相较于仅依赖用户输入的代理系统,显著提升系统的精确度和可靠性。
图 1. 任务图的可视化展示,以及用于实现该任务的路由代码。
ADK Go v2.0.0 为基于图的工作流程提供了以下解决方案:
图形引擎(Graph Engine) (workflowagent + workflow.Edge这是一个基于“节点与边”(node-and-edge)结构的图(graph)API,它可以直接与 Python 的相关库进行交互/集成。 Workflow(edges=[...])节点是通过以下方式定义的: workflow.NewFunctionNode, workflow.NewAgentNode或者 workflow.NewDynamicNode边的声明方式如下: []workflow.Edge整个图表被包裹在一个……(具体内容未提供)中。 workflowagent.New `call:`
edges := workflow.Concat(
workflow.Chain(workflow.Start, classifyNode),
[]workflow.Edge{
{From: classifyNode, To: responseA, Route: workflow.StringRoute("output-1")},
{From: classifyNode, To: responseB, Route: workflow.StringRoute("output-2")},
{From: classifyNode, To: responseC, Route: workflow.StringRoute("output-3")},
},
)
rootAgent, _ := workflowagent.New(workflowagent.Config{
Name: "routing_workflow",
Edges: edges,
})
使用基于图的代理工作流程的优势在于:与基于文本的代理相比,它在控制能力、可预测性和可靠性方面都有显著提升。通过将整个流程工作流程以代码的形式进行定义,你可以更好地控制任务的路由和执行方式。这种结构化的节点定义方式提高了代理的可预测性,并增强了那些需要明确步骤和流程管理的复杂任务的可靠性。
要开始在 ADK 中使用基于图形的工作流程,请查看以下内容: 基于图的代理工作流程(Graph-based agent workflows).
节点(Nodes)¶
一个图由执行节点组成。 节点(Nodes) 可以 代理(Agents), ADK 工具这些节点可以处理人类输入的任务,或者您编写的代码函数。节点可以从之前已经执行过的节点接收输入数据,并通过自身处理后输出新的数据。 事件 objects.
以下内容展示了一个简单的示例: FunctionNode 该系统用于处理文本输入,并生成相应的文本输出。
在 ADK TypeScript v2.0.0 中,主要的节点类型是……(此处应填写具体的节点类型)。 FunctionNode通过传递一个函数来创建该对象。 node()处理程序(handler)总是会接收(某些输入或请求)。
(ctx, input) 参数:ADK 并不会根据参数名称来注入相应的值。
直接返回某个值时,该值会被封装在事件对象中。 output 返回结果。 createEvent({output}) 这是显式的形式(explicit form),当你还需要同时设置其他内容时,就需要使用这种形式。 route 或者 content:
import {
createEvent,
node,
NodeContext,
Workflow,
type FunctionNodeHandler,
} from '@google/adk';
/** A bare return value: boxed into an event's `output` for you. */
const myFunctionNode: FunctionNodeHandler<string, string> = (
_ctx: NodeContext,
nodeInput: string,
) => {
const inputTextModified = nodeInput.toUpperCase();
return inputTextModified;
};
/** The explicit form — identical behaviour, useful when you also set `route`. */
const myExplicitEventNode = (_ctx: NodeContext, nodeInput: string) =>
createEvent({ output: `${nodeInput} IS AWESOME!` });
export const rootAgent = new Workflow({
name: 'function_node_pipeline',
edges: [
[
'START',
node(myFunctionNode, { name: 'my_function_node' }),
node(myExplicitEventNode, { name: 'add_suffix' }),
],
],
});
在 ADK Go v2.0.0 中,主要的节点类型是…… workflow.NewFunctionNode.
A FunctionNode 它用于封装普通的 Go 函数:该函数会返回一个具有特定类型的值,而框架会自动将其包装起来(即对其进行额外的处理或封装)。 session.Event设置 event.Output后续节点会接收这个值,并将其作为自己的类型数据(typed data)进行使用。 input 参数(Parameter):无需手动修改其状态,也不需要通过事件来对其进行更新或配置。
所需功能(Required Functionality):
// newFunctionNodePipeline demonstrates workflow.NewFunctionNode as the primary
// v2 node type. A FunctionNode wraps a plain Go function: the function returns
// a typed value, and the framework automatically wraps it in a session.Event,
// setting event.Output. The successor node receives this value as its typed
// input parameter.
//
// This is the direct Go equivalent of the Python FunctionNode:
//
// def my_function_node(node_input: str):
// return Event(output=node_input.upper())
func newFunctionNodePipeline() (agent.Agent, error) {
upperFn := func(_ agent.Context, input string) (string, error) {
return strings.ToUpper(input), nil
}
suffixFn := func(_ agent.Context, input string) (string, error) {
return input + " IS AWESOME!", nil
}
// workflow.NewFunctionNode wraps each function as a graph node.
// workflow.Chain wires them in order: START → upper → suffix.
// The output of upperFn is delivered as the typed input of suffixFn
// via event.Output — no session state writes are needed.
nodeA := workflow.NewFunctionNode("upper", upperFn, workflow.NodeConfig{})
nodeB := workflow.NewFunctionNode("suffix", suffixFn, workflow.NodeConfig{})
return workflowagent.New(workflowagent.Config{
Name: "function_node_pipeline",
Description: "Demonstrates workflow.NewFunctionNode data flow via Event.Output.",
Edges: workflow.Chain(workflow.Start, nodeA, nodeB),
})
}
在 ADK Kotlin 中, node() 工厂生产(或制造)…… FunctionNode 从一个用于“暂停”(即阻止某些操作)的代码块中获取…… (context, input) 并返回该节点的输出结果。类型参数用于指定输入端口和输出端口的类型;后续节点会接收返回的值作为其输入数据。这些工作流(workflow)API目前仍处于实验阶段,因此该文件选择使用这些API进行开发。
@file:OptIn(ExperimentalWorkflowApi::class):
import com.google.adk.kt.annotations.ExperimentalWorkflowApi
import com.google.adk.kt.workflow.Start
import com.google.adk.kt.workflow.node
import com.google.adk.kt.workflow.workflow
// The returned value becomes the node's output.
private val myFunctionNode =
node<String, String>("my_function_node") { _, nodeInput ->
val inputTextModified = nodeInput.uppercase()
inputTextModified
}
// The successor receives my_function_node's output as its typed input.
private val addSuffix =
node<String, String>("add_suffix") { _, nodeInput ->
"$nodeInput IS AWESOME!"
}
val functionNodePipeline =
workflow("function_node_pipeline") {
chain(Start, myFunctionNode, addSuffix)
}
有关在节点之间传输数据的更多信息,请参阅…… 代理工作流程中的数据处理.
工作流图的语法(Workflow graphs syntax)¶
你可以通过组合工作流代理来定义一个图(即数据流或业务流程)。本节将概述一些常见的路由模式(即数据或任务的传输路径)。
注意:工作流代理存在某些限制。
你可以添加…… LlmAgents 适用于基于图形的工作流程(graph-based workflows)。当一个代理(agent)被用作图形节点(graph node)时,其默认行为是……(此处内容缺失)。 single_turn `mode; a` chat “Mode Agent”仅允许在……之后直接使用。 START因为它使用的是对话历史记录(而非节点输入数据)来进行处理。有关代理模式的更多信息,请参阅……
组建协作型的代理团队.
路由序列(Route sequences)¶
顺序路由会按照列出的顺序,依次访问每个节点。
The edges 该数组使用了(某种功能或方法)。 START 这个关键字用于表示图形执行的开始;列表中的每个节点都会按顺序被执行。
An edges 以……开头的那一行 'START' 按顺序依次执行每个列出的节点,并将每个节点的返回值传递给下一个节点。
edges: [['START', taskANode]] // a single node
edges: [['START', taskANode, taskBNode, taskCNode]] // three, in order
产品列表(或商品列表) 'START' 如果数据被分布在多行中,系统会创建多个并行的处理路径。
有关更多信息,请参阅……
“fan out and join” 的意思是:先各自分散去做自己的事情(或完成自己的任务),然后再重新聚集在一起继续共同工作。这个表达常用于描述团队合作或项目推进的流程。.
import { node, NodeContext, Workflow } from '@google/adk';
const taskANode = node(
(_ctx: NodeContext, nodeInput: string) => `Summary: ${nodeInput.trim()}`,
{ name: 'task_A_node' },
);
const taskBNode = node(
(_ctx: NodeContext, summary: string) => summary.toUpperCase(),
{ name: 'task_B_node' },
);
const taskCNode = node(
(_ctx: NodeContext, shouted: string) => `${shouted} (done)`,
{ name: 'task_C_node' },
);
export const rootAgent = new Workflow({
name: 'sequential_workflow',
edges: [['START', taskANode, taskBNode, taskCNode]],
});
workflow.Chain(workflow.Start, nodeA, nodeB, nodeC) 将这些节点连接成一个按顺序排列的“边切片”(edge slice)。每个节点的返回值(其数据类型已确定)都会被传递给下一个节点。 event.Output — 无需写入会话状态数据:
// newSequentialNodes builds a two-step sequential workflow using the v2 graph
// engine. workflow.Chain wires the nodes in order; each node's typed return
// value is forwarded to the next node via event.Output.
//
// This is the Go equivalent of:
//
// edges=[("START", task_A_node, task_B_node)]
func newSequentialNodes() (agent.Agent, error) {
// task_A_node: transforms the user's input.
taskANode := workflow.NewFunctionNode("task_A_node",
func(_ agent.Context, input string) (string, error) {
return "Summary: " + strings.TrimSpace(input), nil
},
workflow.NodeConfig{},
)
// task_B_node: receives task A's output as its typed input and produces
// the final result. No session state reads needed.
taskBNode := workflow.NewFunctionNode("task_B_node",
func(_ agent.Context, summary string) (string, error) {
return strings.ToUpper(summary), nil
},
workflow.NodeConfig{},
)
return workflowagent.New(workflowagent.Config{
Name: "sequential_workflow",
Description: "Runs task A then task B in order via workflow.Chain.",
Edges: workflow.Chain(workflow.Start, taskANode, taskBNode),
})
}
在……的内部 workflow { } `block,` chain(Start, taskANode, taskBNode,
taskCNode) 按顺序连接各个节点; Start.then(taskANode) 该程序运行在一个单独的节点上。每个节点的输出结果会被作为输入传递给下一个节点。
import com.google.adk.kt.annotations.ExperimentalWorkflowApi
import com.google.adk.kt.workflow.Start
import com.google.adk.kt.workflow.node
import com.google.adk.kt.workflow.workflow
private val taskANode =
node<String, String>("task_A_node") { _, nodeInput ->
"Summary: ${nodeInput.trim()}"
}
private val taskBNode =
node<String, String>("task_B_node") { _, summary ->
summary.uppercase()
}
private val taskCNode =
node<String, String>("task_C_node") { _, shouted ->
"$shouted (done)"
}
val sequentialWorkflow =
workflow("sequential_workflow") {
chain(Start, taskANode, taskBNode, taskCNode)
}
路由分支与条件执行(Route branches and conditional execution)¶
在 Python 中,分支结构的处理是通过……(此处应填写具体的 Python 语法或模块名称)来实现的。 FunctionNode “that returns an” 的意思是“返回一个……的函数或方法”。
Event(route=...) “value”,即那个…… edges 字典(dict)会被分发到不同的节点上。
from google.adk import Event, Workflow
from google.adk.agents import Agent
def router(node_input: str):
"""Route to task B or C based on node_input."""
if condition(node_input):
return Event(route="RUN_TASK_C")
return Event(route="RUN_TASK_B")
task_B_node = Agent(name="task_B_agent") # An agent to execute node B
def task_C_node(node_input: str):
"""A FunctionNode to execute node C."""
return Event(output="Task C completed")
root_agent = Workflow(
name="routing_workflow",
edges=[
("START", task_A_node, router),
(router,
{
# "route value": node_to_run
"RUN_TASK_B": task_B_node,
"RUN_TASK_C": task_C_node,
},
),
],
)
分支结构需要一个能够发出某种信号的节点(即该节点需要具备特定的功能或行为)。 route 每个路由值都会被映射到负责处理该值的节点。路由值可以是字符串、数字或布尔值。此外,还包含一个“边缘行”(edge row),用于记录这些映射关系。 DEFAULT_ROUTE 当同一源节点上没有其他路由匹配时,就会使用这个设置。分支目标可以是任何类似节点的值;在这个例子中…… taskBNode 是一个 LlmAgent
和 taskCNode 这是一个函数。
import {
createEvent,
LlmAgent,
node,
NodeContext,
Workflow,
} from '@google/adk';
const taskANode = node(
(_ctx: NodeContext, nodeInput: string) => nodeInput.trim(),
{ name: 'task_A_node' },
);
/** Stands in for an application-specific branch condition. */
const condition = (nodeInput: string) => /\d/.test(nodeInput);
/** Routes to task B or C based on nodeInput. */
const router = node(
(_ctx: NodeContext, nodeInput: string) =>
condition(nodeInput)
? createEvent({ route: 'RUN_TASK_C', output: nodeInput })
: createEvent({ route: 'RUN_TASK_B', output: nodeInput }),
{ name: 'router' },
);
const taskBNode = new LlmAgent({
name: 'task_B_agent',
model: 'gemini-flash-latest',
instruction: 'Answer the user in a single short sentence.',
});
const taskCNode = node(() => 'Task C completed', { name: 'task_C_node' });
export const rootAgent = new Workflow({
name: 'routing_workflow',
edges: [
['START', taskANode, router],
[
router,
{
RUN_TASK_B: taskBNode,
RUN_TASK_C: taskCNode,
},
],
],
});
在 ADK Go v2.0.0 中,条件调度(conditional dispatch)使用了…… workflow 图形引擎(Graph Engine)。
一个节点(Node)会设置某些属性或状态。 Event.Routes 到一个或多个字符串形式的路由键(string route keys);每个(route key)……
workflow.Edge 通过某种方式来选择自己的继任者。 workflow.Route matcher:
workflow.StringRoute("category")— 匹配一个字符串值workflow.IntRoute(n)或者workflow.MultiRoute[int]{1, 2, 3}— 匹配条件(matches) 整数值(integer values)workflow.BoolRoute(true)— 用于匹配布尔值(true 或 false)。workflow.Default— 当同一源节点上没有其他路由匹配时,该路由才会被选中。
ADK Go 将路由信息作为字符串进行比较;因此,每个节点会以字符串形式输出整数和布尔值作为路由信息。例如: Routes: []string{"2"} for
workflow.IntRoute(2) 或者 []string{"true"} for workflow.BoolRoute(true).
以下代码模式是 Go 语言中实现 Python 路由器功能的等效版本:
// classifyNode emits an Event with Routes=[]string{"BUG"},
// ["CUSTOMER_SUPPORT"], or ["LOGISTICS"] based on the message.
edges := workflow.Concat(
workflow.Chain(workflow.Start, processMessage, classifyNode),
[]workflow.Edge{
{From: classifyNode, To: bugHandler, Route: workflow.StringRoute("BUG")},
{From: classifyNode, To: supportHandler, Route: workflow.StringRoute("CUSTOMER_SUPPORT")},
{From: classifyNode, To: logisticsHandler, Route: workflow.StringRoute("LOGISTICS")},
},
)
rootAgent, _ := workflowagent.New(workflowagent.Config{
Name: "routing_workflow",
Edges: edges,
})
workflow.EdgeBuilder 提供了一种更流畅的替代方案,用于完成组件的组装工作。
[]workflow.Edge 需要手动进行切片操作。这个过程是由构建工具(builder)来完成的。 Add, AddFanOut,以及
AddFanIn 这些方法以更简洁的方式表达了相同的逻辑结构(即相同的“拓扑结构”),同时减少了代码中的重复部分。
eb := workflow.NewEdgeBuilder()
eb.Add(workflow.Start, processMessage)
eb.Add(processMessage, classifyNode)
eb.AddRoute(classifyNode, bugHandler, workflow.StringRoute("BUG"))
eb.AddRoute(classifyNode, supportHandler, workflow.StringRoute("CUSTOMER_SUPPORT"))
eb.AddRoute(classifyNode, logisticsHandler, workflow.StringRoute("LOGISTICS"))
rootAgent, _ := workflowagent.New(workflowagent.Config{
Name: "routing_workflow",
Edges: eb.Build(),
})
有关完整的、可运行的路由示例,请参阅: 字符串路由(string routing), int / 多值路由(Multi-Value Routing)以及 由大型语言模型(LLM)驱动的路由系统.
预构建的代理:在状态中处理编码与路由逻辑
在使用时…… sequentialagent / parallelagent / loopagent **替代方案:**
**而不是使用图形引擎(graph engine),实际上并没有其他替代方案。** Event.Routes 通过 `dispatch` 将路由决策编码到会话状态(session state)中。 OutputKey 然后让下游的代理(agents)在他们的系统中对其进行检查(inspect it in their systems)。 Instruction 可以使用模板,或者选择其他方法。 loopagent
“with an”可以表示“使用……”或“凭借……”。例如:“He completed the project with an excellent team.”(他依靠一个优秀的团队完成了这个项目。) Escalate基于…的退出方式——请参阅相关说明。
循环处理与问题升级的示例 如下所示。
一个节点通过设置相应的参数来选择路由。 context.routes,以及一个 route { }
`block` 将每个路由值映射到负责处理该值的节点。路由值可以是字符串(string)。Route.Tag),整数(integers)Route.Num),或者是布尔值(boolean values)Route.Flag). An otherwise(node) 当同一源节点上没有其他路由能够匹配请求时,该条路由就会被选中(即该条路由被视为“匹配”的)。分支目标可以是任何节点;在这个例子中…… taskBNode 是一个 LlmAgent 和 taskCNode 这是一个函数节点(function node)。
import com.google.adk.kt.agents.Instruction
import com.google.adk.kt.agents.LlmAgent
import com.google.adk.kt.annotations.ExperimentalWorkflowApi
import com.google.adk.kt.models.Gemini
import com.google.adk.kt.workflow.Route
import com.google.adk.kt.workflow.Start
import com.google.adk.kt.workflow.node
import com.google.adk.kt.workflow.workflow
private val taskANode =
node<String, String>("task_A_node") { _, nodeInput -> nodeInput.trim() }
/** Stands in for an application-specific branch condition. */
private fun condition(nodeInput: String) = nodeInput.any { it.isDigit() }
/** Routes to task B or C based on nodeInput. */
private val router =
node<String, String>("router") { context, nodeInput ->
val route = if (condition(nodeInput)) "RUN_TASK_C" else "RUN_TASK_B"
context.routes = listOf(Route.Tag(route))
nodeInput
}
private val taskBNode =
LlmAgent(
name = "task_B_agent",
model = Gemini(name = "gemini-flash-latest"),
instruction = Instruction("Answer the user in a single short sentence."),
)
private val taskCNode =
node<Any?, String>("task_C_node") { _, _ -> "Task C completed" }
val routingWorkflow =
workflow("routing_workflow") {
chain(Start, taskANode, router).route {
// "route value" then nodeToRun
"RUN_TASK_B" then taskBNode
"RUN_TASK_C" then taskCNode
}
}
并行任务:采用分散处理(fan-out)的方式执行,然后再将处理结果汇总(join)在一起。¶
你可以创建这样的图表:这些图表能够将程序的执行过程分配到多个并行运行的节点上。通常情况下,你需要将每个节点的输出结果汇总起来,以便进行进一步的处理。这种任务执行模式分为两个阶段:首先,工作流程会启动多个并行任务;当这些任务完成后,工作流程会重新整合这些任务的结果,然后再进入下一步。
图 2. 并行任务节点的输出结果可以被收集并合并在一起,然后再将最终结果传递到下一步处理。
你通过使用某种方法来完成连接(join)操作。 JoinNode 这个对象会等待所有并行任务完成,然后将这些节点产生的输出结果集合传递给下一个节点。
A JoinNode 这是一种“扇入式”(fan-in)的同步机制。该逻辑机制会等待所有前置任务(predecessor tasks)完成,之后才会将数据传递给后续任务(successor tasks)。在传递数据时,会使用前置任务的节点名称作为键(key),从而生成一个唯一的记录(record)。
import { JoinNode, node, NodeContext, Workflow } from '@google/adk';
const parallelTaskA = node(
(_ctx: NodeContext, text: string) => text.toUpperCase(),
{ name: 'parallel_task_A' },
);
const parallelTaskB = node((_ctx: NodeContext, text: string) => text.length, {
name: 'parallel_task_B',
});
const parallelTaskC = node(
(_ctx: NodeContext, text: string) => text.split('').reverse().join(''),
{ name: 'parallel_task_C' },
);
const myJoinNode = new JoinNode({ name: 'my_join_node' });
const finalTaskD = node(
(_ctx: NodeContext, results: Record<string, unknown>) =>
[
`Uppercase: ${results['parallel_task_A']}`,
`Length: ${results['parallel_task_B']}`,
`Reversed: ${results['parallel_task_C']}`,
].join('\n'),
{ name: 'final_task_D' },
);
export const rootAgent = new Workflow({
name: 'fan_out_workflow',
edges: [
['START', parallelTaskA, myJoinNode],
['START', parallelTaskB, myJoinNode],
['START', parallelTaskC, myJoinNode],
[myJoinNode, finalTaskD],
],
});
ADK Go v2.0.0 提供了…… workflow.NewJoinNode 对于真正的“fan-in”(即从某个节点开始、并最终连接到多个其他节点的路径)来说:这些路径实际上是由该节点发出的“fan-out”(即从该节点出发、并最终连接到多个其他节点的)边所构成的。 workflow.Start (或任何共享的源代码/节点)可以并行地向“连接节点”(join node)发送数据;该连接节点会等待所有数据/节点的处理完成后,才会发出相应的信号/结果。 map[string]any 根据前一个节点的名称来确定下一个节点的连接方式。
workflow.EdgeBuilder 通过其专用设计,使得扇出(fan-out)/扇入(fan-in)布线方式更加简洁明了。 AddFanOut 和 AddFanIn helpers(如所示)
复杂的工作流程示例):
gatherNode := workflow.NewJoinNode("gather")
eb := workflow.NewEdgeBuilder()
eb.AddFanOut(workflow.Start, researchNodeA, researchNodeB, researchNodeC)
eb.AddFanIn(gatherNode, researchNodeA, researchNodeB, researchNodeC)
eb.Add(gatherNode, formatNode)
eb.Add(formatNode, synthesisNode)
rootAgent, _ := workflowagent.New(workflowagent.Config{
Name: "research_pipeline",
Edges: eb.Build(),
})
以下代码片段展示了完整的“扇出”(fan-out)/“聚合”(join)模式:
workflow.NewJoinNode 和 EdgeBuilder.AddFanOut / AddFanIn:
// newParallelFanOut builds a fan-out / join workflow using the v2 graph engine.
// Three research nodes run in parallel from Start; workflow.NewJoinNode waits
// for all of them to complete and emits a map[nodeName]output to the format
// node, which assembles the results for a synthesis node.
//
// Graph topology:
//
// START ─┬─> research_A ──┐
// ├─> research_B ──┼─> gather (JoinNode) ─> format ─> synthesis
// └─> research_C ──┘
//
// Python equivalent:
//
// edges=[
// ("START", research_A, my_join_node),
// ("START", research_B, my_join_node),
// ("START", research_C, my_join_node),
// (my_join_node, format_node),
// (format_node, synthesis_node),
// ]
func newParallelFanOut() (agent.Agent, error) {
researchA := workflow.NewFunctionNode("research_A",
func(_ agent.Context, _ any) (string, error) {
return "Fact about renewable energy.", nil
},
workflow.NodeConfig{},
)
researchB := workflow.NewFunctionNode("research_B",
func(_ agent.Context, _ any) (string, error) {
return "Fact about electric vehicles.", nil
},
workflow.NodeConfig{},
)
researchC := workflow.NewFunctionNode("research_C",
func(_ agent.Context, _ any) (string, error) {
return "Fact about carbon capture.", nil
},
workflow.NodeConfig{},
)
// workflow.NewJoinNode waits for all predecessors (research_A, research_B,
// research_C) to complete and emits a map[nodeName]output to its successor.
gatherNode := workflow.NewJoinNode("gather")
// formatNode receives map[string]any from gatherNode and assembles a
// combined prompt string.
formatNode := workflow.NewFunctionNode("format",
func(_ agent.Context, results map[string]any) (string, error) {
return fmt.Sprintf("A: %v\nB: %v\nC: %v",
results["research_A"],
results["research_B"],
results["research_C"],
), nil
},
workflow.NodeConfig{},
)
synthesisNode := workflow.NewFunctionNode("synthesis",
func(_ agent.Context, prompt string) (string, error) {
return "Combined report: " + prompt, nil
},
workflow.NodeConfig{},
)
// EdgeBuilder.AddFanOut fans workflow.Start out to all three research nodes.
// EdgeBuilder.AddFanIn routes all three research nodes into gatherNode.
eb := workflow.NewEdgeBuilder()
eb.AddFanOut(workflow.Start, researchA, researchB, researchC)
eb.AddFanIn(gatherNode, researchA, researchB, researchC)
eb.Add(gatherNode, formatNode)
eb.Add(formatNode, synthesisNode)
return workflowagent.New(workflowagent.Config{
Name: "fan_out_workflow",
Description: "Parallel research fan-out with JoinNode barrier and synthesis.",
Edges: eb.Build(),
})
}
then(a, b, c) 数据被分发到那些可以同时运行的节点上; joinTo
将这些设备连接到…… JoinNode该连接操作会等待所有前置节点(predecessors)完成它们的处理,之后会将一个映射结构(map)传递给后续节点(successor)。这个映射结构中的键(keys)是前置节点的名称(node names),而值(values)则是前置节点处理完成后产生的结果。
import com.google.adk.kt.annotations.ExperimentalWorkflowApi
import com.google.adk.kt.workflow.JoinNode
import com.google.adk.kt.workflow.Start
import com.google.adk.kt.workflow.node
import com.google.adk.kt.workflow.workflow
private val parallelTaskA =
node<String, String>("parallel_task_A") { _, text -> text.uppercase() }
private val parallelTaskB =
node<String, Int>("parallel_task_B") { _, text -> text.length }
private val parallelTaskC =
node<String, String>("parallel_task_C") { _, text -> text.reversed() }
private val myJoinNode = JoinNode("my_join_node")
private val finalTaskD =
node<Map<String, Any?>, String>("final_task_D") { _, results ->
listOf(
"Uppercase: ${results["parallel_task_A"]}",
"Length: ${results["parallel_task_B"]}",
"Reversed: ${results["parallel_task_C"]}",
).joinToString("\n")
}
val fanOutWorkflow =
workflow("fan_out_workflow") {
Start.then(parallelTaskA, parallelTaskB, parallelTaskC)
.joinTo(myJoinNode)
.then(finalTaskD)
}
注意:为 `JoinNode` 提供输入数据的节点必须能够生成相应的输出结果。
A JoinNode 只有在所有前置节点(即该节点的父节点)完成处理后,该节点才会被释放。
请确保每个用于执行连接操作的节点都有自己的输出结果,并将其正确地连接到后续处理流程中。
重试配置 任何都可能发生故障的节点都可能受到影响。如果某个前置节点在完成处理后没有输出结果,那么该分支对应的计算结果就会为空;这种故障会“向下传播”(即影响到后续的处理步骤),而不会影响到导致该故障的节点本身。
嵌套的工作流程(Nested workflows)¶
在构建更复杂的工作流程时,您可能希望将特定任务的功能封装到可重用的工作流程中。为此,可以在一个工作流程代理内部使用一个或多个工作流程代理作为子代理来完成任务。
图 3. 嵌套的工作流代理可以作为子代理存在于父工作流中。
from google.adk import Workflow
root_agent = Workflow(
name="parent_workflow",
edges=[
("START", task_A1, router),
(router, {
"RUN_WORKFLOW_B": workflow_B,
"RUN_WORKFLOW_C": workflow_C,
},
),
],
)
嵌套工作流的数据输出¶
对于嵌套的工作流对象(nested Workflow objects),其数据输出方式与单个节点(individual nodes)略有不同。当嵌套的工作流完成其中一个节点的任务后,它会将数据传输给该工作流图中的下一个节点。 和 系统会将该节点的相关事件信息传递给父工作流,以便实现流程的可追溯性(即追踪流程的执行过程)。当嵌套工作流完成其流程中的最后一个节点时,父节点会从最后一个节点中提取数据,并将这些数据作为嵌套工作流的输出结果进行发布。
一个工作流程最多只能包含……(具体数量未在文档中明确)。 one 生成输出的终端节点。如果两个或多个终端节点同时生成输出(例如,两个并行分支的末端同时生成输出),则工作流程会失败,并出现相应的错误或异常。 ValueError将这些分支合并到一个分支中。 JoinNode 因此,该图以一个单独的终端(即图形的最后一个节点)作为结束。
A Workflow 它本身也是一个节点,因此你可以将多个节点嵌套在一起使用。
工作流(workflow)的边(edges)可以用来封装那些可重复使用的子流程(sub-processes)。
import { createEvent, node, NodeContext, Workflow } from '@google/adk';
const taskA1 = node(
(_ctx: NodeContext, nodeInput: string) => nodeInput.trim(),
{
name: 'task_A1',
},
);
const router = node(
(_ctx: NodeContext, text: string) =>
createEvent({
route: text === text.toUpperCase() ? 'RUN_WORKFLOW_C' : 'RUN_WORKFLOW_B',
output: text,
}),
{ name: 'router' },
);
/**
* Upper-cases the first letter of each word.
*
* Unicode-aware on purpose: `\b\w` is ASCII-only, so `ü` never matches — and
* the word boundary it creates before the *next* ASCII letter upper-cases that
* one instead ("strässe" -> "SträSse"). A letter whose uppercase form is more
* than one code point (German `ß` -> "SS") is left alone rather than mangled.
*/
const titleCase = (text: string) =>
text.replace(/(^|\P{L})(\p{L})/gu, (_match, sep: string, ch: string) => {
const upper = ch.toUpperCase();
return sep + ([...upper].length === 1 ? upper : ch);
});
const workflowB = new Workflow({
name: 'workflow_B',
edges: [
[
'START',
node((_ctx: NodeContext, text: string) => titleCase(text), {
name: 'b_title_case',
}),
node((_ctx: NodeContext, text: string) => `[B] ${text}`, {
name: 'b_frame',
}),
],
],
});
const workflowC = new Workflow({
name: 'workflow_C',
edges: [
[
'START',
node((_ctx: NodeContext, text: string) => text.toLowerCase(), {
name: 'c_lower_case',
}),
node((_ctx: NodeContext, text: string) => `[C] ${text}`, {
name: 'c_frame',
}),
],
],
});
export const rootAgent = new Workflow({
name: 'parent_workflow',
edges: [
['START', taskA1, router],
[
router,
{
RUN_WORKFLOW_B: workflowB,
RUN_WORKFLOW_C: workflowC,
},
],
],
});
嵌套工作流的数据输出结果。 当内部工作流正在运行时,其每个节点的事件都会被上报给父节点,以便进行追踪(即确保整个流程的可追溯性)。当内部工作流完成后,其终端节点的输出结果将成为整个嵌套工作流的最终输出结果。
ADK Go v2.0.0 通过两种互补的方式支持嵌套的工作流程:
图形引擎(Graph Engine) (workflowagent + workflow.Edge): A workflowagent
使用以下工具/技术创建: workflowagent.New 它本身就是一个…… agent.Agent因此,它可以被包装(或:可以用某种方式处理)起来。 workflow.NewAgentNode 并且被用作另一个工作流(workflow)中的节点。 edges 从外部图的角度来看,内部工作流程作为一个单独的节点被执行完毕;其最终输出结果会作为该节点的输出数据,被显示在外部图的相应边上。
innerNode, _ := workflow.NewAgentNode(innerWorkflowAgent, workflow.NodeConfig{})
outerEdges := workflow.Chain(workflow.Start, outerStepNode, innerNode, finalNode)
rootAgent, _ := workflowagent.New(workflowagent.Config{
Name: "parent_workflow",
Edges: outerEdges,
})
以下代码片段展示了内部图和外部图的构建过程。
workflow.NewAgentNode “wraps the inner” 的意思是“包裹住内部的部分”。 workflowagent 因此,它可以被放置在外部图的结构中。 workflow.Chain:
// newNestedWorkflows shows how to nest one workflowagent inside another using
// the v2 graph engine. The inner workflowagent is wrapped with
// workflow.NewAgentNode and placed as a node in the outer graph's edge slice.
// From the outer graph's perspective the inner workflow is a single node that
// runs to completion before the edge to finalNode is followed.
//
// Python equivalent:
//
// root_agent = Workflow(
// name="parent_workflow",
// edges=[("START", task_A1, workflow_B, final_node)],
// )
func newNestedWorkflows() (agent.Agent, error) {
// --- Inner workflow B ---
innerStep1 := workflow.NewFunctionNode("inner_step_1",
func(_ agent.Context, input string) (string, error) {
return "[ES] " + input, nil // simulate translation to Spanish
},
workflow.NodeConfig{},
)
innerStep2 := workflow.NewFunctionNode("inner_step_2",
func(_ agent.Context, spanish string) (string, error) {
return "[EN] " + spanish, nil // simulate translation back to English
},
workflow.NodeConfig{},
)
// workflowB is a self-contained inner graph.
workflowB, err := workflowagent.New(workflowagent.Config{
Name: "workflow_B",
Description: "Translates input to Spanish then back to English.",
Edges: workflow.Chain(workflow.Start, innerStep1, innerStep2),
})
if err != nil {
return nil, fmt.Errorf("workflowB: %w", err)
}
// --- Outer graph ---
taskA1 := workflow.NewFunctionNode("task_A1",
func(_ agent.Context, input string) (string, error) {
return "Summary: " + strings.TrimSpace(input), nil
},
workflow.NodeConfig{},
)
finalNode := workflow.NewFunctionNode("final_node",
func(_ agent.Context, result string) (string, error) {
return "Final: " + result, nil
},
workflow.NodeConfig{},
)
// workflow.NewAgentNode wraps workflowB so it can be placed as a node
// in the outer graph's edges slice.
innerNode, err := workflow.NewAgentNode(workflowB, workflow.NodeConfig{})
if err != nil {
return nil, fmt.Errorf("NewAgentNode(workflowB): %w", err)
}
return workflowagent.New(workflowagent.Config{
Name: "parent_workflow",
Description: "Runs task_A1 then the nested workflow_B then final_node.",
Edges: workflow.Chain(workflow.Start, taskA1, innerNode, finalNode),
SubAgents: []agent.Agent{workflowB},
})
}
如果要嵌套一个图(graph),而不需要将其包装在一个代理(agent)中,可以直接创建相应的节点(node)。 workflow.NewWorkflowNode它的输出就是内部图单个终端节点的输出;如果多个终端节点都产生了输出,那么工作流程就会失败。 workflow.ErrMultipleOutputs):
A Workflow 该工作流本身也是一个节点,因此你可以将一个工作流嵌套在另一个工作流内部。通过这种方式,可以利用工作流的“边”(edges)来封装可重用的子流程。当嵌套的工作流完成时,其终端节点的输出结果就会成为整个嵌套工作流的输出结果。
import com.google.adk.kt.annotations.ExperimentalWorkflowApi
import com.google.adk.kt.workflow.Route
import com.google.adk.kt.workflow.Start
import com.google.adk.kt.workflow.node
import com.google.adk.kt.workflow.workflow
private val taskA1 =
node<String, String>("task_A1") { _, nodeInput -> nodeInput.trim() }
private val router =
node<String, String>("router") { context, text ->
val route = if (text == text.uppercase()) "RUN_WORKFLOW_C" else "RUN_WORKFLOW_B"
context.routes = listOf(Route.Tag(route))
text
}
/** Upper-cases the first letter of each word. */
private fun titleCase(text: String) =
text.split(" ").joinToString(" ") { word -> word.replaceFirstChar { it.titlecase() } }
private val workflowB =
workflow("workflow_B") {
chain(
Start,
node<String, String>("b_title_case") { _, text -> titleCase(text) },
node<String, String>("b_frame") { _, text -> "[B] $text" },
)
}
private val workflowC =
workflow("workflow_C") {
chain(
Start,
node<String, String>("c_lower_case") { _, text -> text.lowercase() },
node<String, String>("c_frame") { _, text -> "[C] $text" },
)
}
val parentWorkflow =
workflow("parent_workflow") {
chain(Start, taskA1, router).route {
"RUN_WORKFLOW_B" then workflowB
"RUN_WORKFLOW_C" then workflowC
}
}
循环处理机制与问题升级流程(用于解决复杂问题)¶
循环会重复执行一组操作,直到满足某个终止条件。在 Python 中,这种机制被称为“后向循环”(back-edge loop)。 edges 该图会引导数据流返回到某个较早的节点。在 ADK Go v2.0.0 版本中,图引擎直接支持这种模式:可以从下游节点向较早的节点添加一条边,并设置相应的路由条件;每次迭代时,引擎都会重新激活目标节点,并为其分配一个新的生命周期(即新的状态或配置)。
from google.adk import Event, Workflow
def router(node_input: str):
"""Exit the loop when the task is done, otherwise iterate again."""
if condition(node_input):
return Event(route="DONE")
return Event(route="RETRY")
root_agent = Workflow(
name="looping_workflow",
edges=[
("START", task_A_node, router),
(router,
{
# Back-edge: re-runs task_A_node for another iteration.
"RETRY": task_A_node,
"DONE": final_task_node,
},
),
],
)
一个循环必须至少包含一条“已路由”(routed)或“条件性”(conditional)边。如果一个循环仅由“无条件性”(unconditional)边组成,则会被拒绝。 Workflow 该系统(或产品)是基于某种技术或框架构建的。
循环是一种“回溯”机制:下游节点会重新连接到上游节点(即循环的起始节点),并且每次迭代时,系统会为该节点重新启动一个新的生命周期(即重新分配资源、重新设置状态等)。当路由器选择循环的“终止分支”时,循环就会结束。
import { createEvent, node, NodeContext, Workflow } from '@google/adk';
interface Draft {
topic: string;
bullets: string[];
}
/** The critic is satisfied once the draft has at least this many bullets. */
const REQUIRED_BULLETS = 3;
const seedDraft = node(
(_ctx: NodeContext, topic: string): Draft => ({
topic: topic.trim(),
bullets: [`${topic.trim()} — point 1`],
}),
{ name: 'seed_draft' },
);
const critic = node(
(_ctx: NodeContext, draft: Draft) =>
createEvent({
route: draft.bullets.length >= REQUIRED_BULLETS ? 'DONE' : 'REVISE',
output: draft,
}),
{ name: 'critic' },
);
const refine = node(
(_ctx: NodeContext, draft: Draft): Draft => ({
...draft,
bullets: [
...draft.bullets,
`${draft.topic} — point ${draft.bullets.length + 1}`,
],
}),
{ name: 'refine' },
);
const finalize = node(
(_ctx: NodeContext, draft: Draft) =>
`Approved after ${draft.bullets.length} bullets:\n` +
draft.bullets.map((b) => ` • ${b}`).join('\n'),
{ name: 'finalize' },
);
export const rootAgent = new Workflow({
name: 'loop_workflow',
edges: [
['START', seedDraft, critic],
[critic, { REVISE: refine, DONE: finalize }],
[refine, critic],
],
});
以下示例使用了图形引擎(graph engine)。 workflow.EdgeBuilder评论节点会返回一个评价结果,而路由节点则会根据这个结果进行相应的处理(例如:选择最佳的路径或执行其他操作)。 Event.Routes从精炼者到批评者的这一反馈循环构成了整个系统的基础。当批评者对结果感到满意时,系统会将信息传递到最终用户(即终端用户)。 done “node instead”:
// draft carries the working document through the refinement loop.
type draft struct {
Text string `json:"text"`
}
// criticResult is emitted by the critic node with the review verdict and
// optional suggestions. The router reads Verdict to set Event.Routes.
type criticResult struct {
Verdict string `json:"verdict"` // "REFINE" or "DONE"
Suggestions string `json:"suggestions"` // non-empty when Verdict == "REFINE"
}
// writeDraft is the initial writer node: produces the first draft from the
// user's topic. Its typed return value becomes the input to the critic node
// via Event.Output — no session state writes needed.
func writeDraft(_ agent.Context, topic string) (draft, error) {
// In a real workflow this would call an LLM; here we return a stub.
return draft{Text: "Draft about " + topic + ": placeholder content."}, nil
}
// reviewDraft is the critic node: inspects the draft and returns a verdict.
// "DONE" exits the loop; "REFINE" triggers a back-edge to the refiner.
func reviewDraft(_ agent.Context, d draft) (criticResult, error) {
// Simulate a critic: approve once the draft contains "improved".
if strings.Contains(d.Text, "improved") {
return criticResult{Verdict: "DONE"}, nil
}
return criticResult{
Verdict: "REFINE",
Suggestions: "Add more detail and mark the text as improved.",
}, nil
}
// routeVerdict reads the critic's verdict and sets Event.Routes so the
// graph engine dispatches to either the refiner or the done node.
// Returning nil suppresses the automatic terminal event.
func routeVerdict(ctx agent.Context, r criticResult, emit func(*session.Event) error) (any, error) {
ev := session.NewEvent(ctx, ctx.InvocationID())
ev.Routes = []string{r.Verdict}
ev.Output = r // forward the full result to the chosen successor
if err := emit(ev); err != nil {
return nil, err
}
return nil, nil
}
// refineDraft applies the critic's suggestions and returns the improved draft.
// Its output feeds back to the critic node via the back-edge.
func refineDraft(_ agent.Context, r criticResult) (draft, error) {
return draft{Text: "improved draft incorporating: " + r.Suggestions}, nil
}
// reportDone is the terminal node, reached only when the critic is satisfied.
func reportDone(_ agent.Context, r criticResult) (string, error) {
return "Refinement complete. Final verdict: " + r.Verdict, nil
}
// newLoopEscalate builds an iterative document-refinement workflow using the
// graph engine. The critic node emits a route ("REFINE" or "DONE") and the
// engine dispatches to either the refiner (which loops back to the critic via
// a back-edge) or the terminal done node.
//
// Graph topology:
//
// START → writer → critic → router ─┬─ "REFINE" → refiner ──┐
// └─ "DONE" → done │
// ▲_______________________________┘ (back-edge)
//
// Python equivalent:
//
// edges=[
// ("START", writer_node, critic_node, router),
// (router, {"REFINE": refiner_node, "DONE": done_node}),
// (refiner_node, critic_node), # back-edge creates the loop
// ]
func newLoopEscalate() (agent.Agent, error) {
writerNode := workflow.NewFunctionNode("writer", writeDraft, workflow.NodeConfig{})
criticNode := workflow.NewFunctionNode("critic", reviewDraft, workflow.NodeConfig{})
routerNode := workflow.NewEmittingFunctionNode("router", routeVerdict, workflow.NodeConfig{})
refinerNode := workflow.NewFunctionNode("refiner", refineDraft, workflow.NodeConfig{})
doneNode := workflow.NewFunctionNode("done", reportDone, workflow.NodeConfig{})
// Build the edges. The back-edge from refinerNode to criticNode creates
// the loop; the graph engine re-activates criticNode with a fresh
// lifecycle on each iteration.
eb := workflow.NewEdgeBuilder()
eb.Add(workflow.Start, writerNode)
eb.Add(writerNode, criticNode)
eb.Add(criticNode, routerNode)
eb.AddRoute(routerNode, refinerNode, workflow.StringRoute("REFINE"))
eb.AddRoute(routerNode, doneNode, workflow.StringRoute("DONE"))
eb.AddRoute(refinerNode, criticNode, workflow.Default) // back-edge: loop back for another review
return workflowagent.New(workflowagent.Config{
Name: "iterative_writer",
Description: "Writes then iteratively refines a document using a critic/refiner loop.",
Edges: eb.Build(),
})
}
循环是一种“回退机制”(back-edge mechanism): refine.then(critic) 该机制会将下游节点重新路由回之前的状态;每次迭代时,引擎都会重新激活该节点,并为其分配一个新的生命周期(即新的运行状态)。当“评论者”(critic)做出最终选择时,这个循环才会终止。
DONE route:
import com.google.adk.kt.annotations.ExperimentalWorkflowApi
import com.google.adk.kt.workflow.Route
import com.google.adk.kt.workflow.Start
import com.google.adk.kt.workflow.node
import com.google.adk.kt.workflow.workflow
/** The critic is satisfied once the draft has at least this many bullets. */
private const val REQUIRED_BULLETS = 3
// The draft is its list of bullets; the topic is kept in session state.
private val seedDraft =
node<String, List<String>>("seed_draft") { context, topic ->
context.updateState("topic", topic.trim())
listOf("${topic.trim()} — point 1")
}
private val critic =
node<List<String>, List<String>>("critic") { context, bullets ->
val route = if (bullets.size >= REQUIRED_BULLETS) "DONE" else "REVISE"
context.routes = listOf(Route.Tag(route))
bullets
}
private val refine =
node<List<String>, List<String>>("refine") { context, bullets ->
bullets + "${context.state["topic"]} — point ${bullets.size + 1}"
}
private val finalize =
node<List<String>, String>("finalize") { _, bullets ->
"Approved after ${bullets.size} bullets:\n" +
bullets.joinToString("\n") { " • $it" }
}
val loopWorkflow =
workflow("loop_workflow") {
chain(Start, seedDraft, critic).route {
"REVISE" then refine
"DONE" then finalize
}
refine.then(critic) // back-edge: loop back for another review
}
注意:无界图中的循环结构可能导致程序出现异常或错误。
图中的循环并不会自动终止(即不会自动“结束”)。请确保退出条件最终能够成立(即程序能够正常结束);否则,就需要将迭代过程明确地表示出来(即通过代码逻辑来控制迭代的终止)。 动态工作流程循环在您自己的代码中执行,您可以控制其执行的范围(即循环的边界)。