动态代理工作流程(Dynamic Agent Workflows)¶
ADK框架提供了一种编程方式,用于定义工作流程。这种方式比传统的方法更加灵活、功能也更强大。 基于图的工作流程(graph-based workflows)使用基于图的方法可以方便地构建包含工作流节点的多步骤、静态流程结构。然而,如果工作流的逻辑路径较为复杂(例如包含迭代循环或复杂的分支逻辑),那么基于图的方法可能无法满足您的需求,或者会变得难以管理。
在 ADK 中,动态工作流功能允许你放弃基于图的结构来构建工作流,而是充分利用所选编程语言的全部功能。通过动态工作流,你可以使用简单的装饰器(如 Python)或构造函数(如 Go)来创建工作流;可以将工作流节点作为函数来调用,并构建复杂的路由逻辑。以下是 ADK 中动态工作流的一些优势:
- 灵活的控制流程(Flexible Control Flow): 通过循环、条件语句和递归来动态地确定执行顺序;这些逻辑结构在静态图中很难(甚至无法)被准确表示出来。
- “Programmatic Experience”(程序化体验):
这个术语指的是通过编程或自动化的方式来创建、管理和优化用户体验的过程。在数字产品和服务中,程序化体验变得越来越重要,因为它能够提高效率、提升用户体验的个性化程度,并实现更快速的市场响应。例如,通过程序化技术,网站可以根据用户的浏览历史和行为习惯自动推荐相关内容;广告系统也可以根据用户的兴趣和偏好精准投放广告。总之,程序化体验的核心在于利用技术手段来优化用户体验和业务效果。 使用熟悉的编程结构(如循环、条件语句等)。
while循环 以及async/await(Python)或者for循环与……workflow.RunNode(继续) 与其使用基于图的路由机制,不如采用其他方法。 - 自动检查点功能: 动态工作流会跟踪每个节点的执行情况。在恢复工作流时,已成功完成的子节点会自动被跳过,这使得复杂的逻辑结构具有更好的稳定性和可恢复性(即:即使工作流中断,这些子节点也能在后续执行中继续被正确处理)。
- 封装(Encapsulation): 将业务逻辑封装到……中。 parent 这些节点在内部由更低级别的节点组成,从而确保整个工作流程的清晰性和可管理性。
立即开始使用吧!¶
以下动态工作流代码示例展示了如何定义一个基本的工作流,该工作流包含一个带有特定功能的节点:
from google.adk import Context
from google.adk import Workflow
from google.adk.workflow import node
from typing import Any
@node(name="hello_node")
def my_node(node_input: Any):
return "Hello World"
# define a dynamic workflow node
@node(rerun_on_resume=True)
async def my_workflow(ctx: Context, node_input: str) -> str:
# run_node executes a node and returns its output
result = await ctx.run_node(my_node, node_input="hello")
return result
# Run the workflow
root_agent = Workflow(
name="root_agent",
edges=[("START", my_workflow)],
)
这个示例使用了…… @node 添加这些注释是为了方便阅读,并使代码尽可能简洁。这些注释会生成相应的“包装器”(wrapper),使得代码能够在 ADK 动态工作流的框架下正常运行。
TypeScript 没有……(此处应填写 TypeScript 缺乏的功能或特性)。 @node **装饰器:请使用该装饰器。** node(fn, options) 应该使用 `function` 而不是 `factory`。 ctx.runNode() 该方法相当于(method is the equivalent of...)
ctx.run_node():
import { node, NodeContext, Workflow } from '@google/adk';
const myNode = node(() => 'Hello World', { name: 'hello_node' });
const myWorkflow = node(
async (ctx: NodeContext, _nodeInput: string) => {
const result = await ctx.runNode(myNode, 'hello');
return result.output;
},
{ name: 'my_workflow', rerunOnResume: true },
);
export const rootAgent = new Workflow({
name: 'root_agent',
edges: [['START', myWorkflow]],
});
在编写编排器节点(orchestration node)时,有两个细节会影响到结果数据的读取方式,以及工作流程在暂停后的运行行为:
- The
ctx.runNode()该方法返回的是一个节点结果(node result),而不是输出值(output value)。请仔细阅读相关说明。.output用于获取值的属性。 - 一个用于调用其他组件的协调器(orchestrator)。
ctx.runNode()必须设置rerunOnResume: true此设置会导致节点主体在恢复运行时重新执行;因此,那些已经完成执行的子节点会从它们的检查点状态继续执行,而不会被再次执行。
在 Go 语言中, workflow.NewFunctionNode 替换(replaces the) @node 装饰器(decorator)和
workflow.NewDynamicNode 替换(replaces the) @node(rerun_on_resume=True) `async`
`orchestrator.` workflow.RunNode 相当于……(直接对应的关系)
ctx.run_node(). workflowagent.New 使用(with) workflow.Chain 替换
Workflow(edges=[...]).
在人工干预(即“人在回路”中的操作)导致的暂停之后,系统行为的恢复是由以下机制控制的:
NodeConfig.RerunOnResume — 请参阅 节点(Nodes) 详情请参见下文。
// helloNode is a simple FunctionNode that returns "Hello World".
// In Python this would be written as:
//
// @node(name="hello_node")
// def my_node(node_input: Any):
// return "Hello World"
//
// In Go, workflow.NewFunctionNode wraps the same logic with the
// required node interface, inferring input and output types from
// the generic parameters.
var helloNode = workflow.NewFunctionNode("hello_node",
func(_ agent.Context, _ string) (string, error) {
return "Hello World", nil
},
workflow.NodeConfig{},
)
// myWorkflow is a dynamic orchestrator node. It calls workflow.RunNode
// to schedule helloNode as a child and returns its output.
// In Python this would be:
//
// @node(rerun_on_resume=True)
// async def my_workflow(ctx: Context, node_input: str) -> str:
// result = await ctx.run_node(my_node, node_input="hello")
// return result
//
// workflow.NewDynamicNode defaults RerunOnResume to &true, matching the
// Python @node(rerun_on_resume=True) behaviour.
var myWorkflow = workflow.NewDynamicNode[string, string]("my_workflow",
func(ctx agent.Context, _ string, _ func(*session.Event) error) (string, error) {
return workflow.RunNode[string](ctx, helloNode, "hello")
},
workflow.NodeConfig{},
)
func runGetStarted() error {
ctx := context.Background()
// workflowagent.New creates an agent.Agent backed by the workflow engine.
// workflow.Chain(workflow.Start, myWorkflow) produces the edges slice
// equivalent to Python's edges=[("START", my_workflow)].
wa, err := workflowagent.New(workflowagent.Config{
Name: "root_agent",
Description: "A minimal dynamic workflow.",
Edges: workflow.Chain(workflow.Start, myWorkflow),
})
if err != nil {
return fmt.Errorf("workflowagent.New: %w", err)
}
l := full.NewLauncher()
return l.Execute(ctx, &launcher.Config{
AgentLoader: agent.NewSingleLoader(wa),
}, os.Args[1:])
}
构建模块:节点(Nodes)与工作流(Workflows)¶
节点(Nodes)和工作流程(Workflows)是 ADK 动态工作流程(Dynamic Workflows)的基本构建模块。这些类型和功能提供了所需的功能,使得您的代码能够被封装起来,并集成到 ADK 中基于代码的工作流程中。
节点(Nodes)¶
在 ADK 中,一个动态的工作流程由以下部分组成: 节点(Nodes)这是一个简单的工作流节点实现:它将一个普通的函数封装起来,并添加了该函数在工作流中运行所需的所有元数据。
在 Python 中, @node 注释会生成节点包装器(node wrapper),同时将样板代码(boilerplate code)的使用量降至最低。
以下代码片段展示了等效的实现方式。 没有;缺乏 the @node `annotation:`
from typing import Any
from google.adk.workflow import FunctionNode
# base function
def hello_world(node_input: Any):
return "Hello World"
# FunctionNode wrapper with options
my_function_node = FunctionNode(
func=hello_world,
name="hello_node",
)
如果你需要封装来自外部库的函数、需要使用同一个函数创建多个具有不同配置的节点,或者需要在注册表中管理节点引用以实现更复杂的协调控制(即高级的流程编排),那么自己编写节点封装代码会非常有用。
有两种方法可以构建一个节点: node(fn, options) 工厂(factory)、函数(function)以及那些明确表述的内容(the explicit parts)。 new FunctionNode(name, fn, config)
**构造函数(Constructor)**:
当您需要封装来自其他库的函数、从一个函数中获取多个配置不同的节点,或者将节点引用存储在注册表中以实现更复杂的协调控制时,请使用构造函数。
import { FunctionNode, node, NodeContext, Workflow } from '@google/adk';
/** The plain function both node forms wrap. */
function myFunctionNode(_ctx: NodeContext, nodeInput: unknown): string {
return `Hello ${nodeInput ?? 'World'}`;
}
const helloNode = node(myFunctionNode, { name: 'hello_node' });
const successNode = new FunctionNode('hello', myFunctionNode, {
rerunOnResume: true,
});
在这个代码示例中,最重要的选项是…… rerunOnResume这个功能用于控制工作流程在经过人工干预(即暂停)后重新启动时的行为。
true(重新进入系统): 节点体将从顶部开始重新执行。请将此设置应用于所有调用该功能的编排器(orchestration tool)。ctx.runNode()主体部分(body)会重新执行相关操作;那些已经完成处理的子任务(child activations)会被自动跳过。false(Handoff:即“责任转移”;Leaf Default:即“默认值/默认状态”) 简历数据(resume payload)会被作为输入传递给该节点的后续处理节点(successor node),从而绕过出现故障(interrupted)的节点。
在 Go 语言中, workflow.NewFunctionNode[IN, OUT] 该功能可以将一个普通的函数包装成一个工作流(workflow)节点,并根据该函数的参数类型自动推断其输入和输出数据的类型。
该功能没有专门的装饰器语法;你需要将该节点作为一个值(value)传递给其他工作流节点,以便将其纳入工作流流程中。 workflow.RunNode 在一个动态的编排器(dynamic orchestrator)内部:
// myFunctionNode demonstrates the explicit NewFunctionNode constructor —
// equivalent to wrapping a function in a FunctionNode manually in Python:
//
// success_node = FunctionNode(my_function_node, name="hello", rerun_on_resume=True)
//
// Creating the node directly (rather than via @node) is useful when you
// need multiple nodes from the same function with different configurations,
// or when wrapping functions from an external library.
var myFunctionNode = workflow.NewFunctionNode("hello",
func(_ agent.Context, _ any) (string, error) {
return "Hello World", nil
},
workflow.NodeConfig{},
)
// myFormattingNode is a second function node that the dynamic orchestrator
// calls in sequence, mirroring:
//
// result_formatted = await ctx.run_node(my_formatting_node, node_input=result)
var myFormattingNode = workflow.NewFunctionNode("format",
func(_ agent.Context, in string) (string, error) {
return fmt.Sprintf("[formatted] %s", in), nil
},
workflow.NodeConfig{},
)
NodeConfig 具有与 Python 相同的选项。 @node `arguments`。其中最重要的字段是…… RerunOnResume *bool该设置用于控制工作流程在经过人工干预(即暂停)后重新启动时会发生什么。
&true(重新进入模式)被中断的节点会在恢复运行时从头开始重新执行。这种方法适用于那些需要动态调度的节点(即那些需要根据实际情况来调整执行顺序的节点)。workflow.RunNode在循环中:循环体会重新执行代码;那些已经完成执行的子节点(即那些已经被激活的子节点)会被自动跳过(系统会进行“检查点”处理)。这种机制与 Python 的实现方式是一致的。@node(rerun_on_resume=True).&false(交接模式)简历数据(resume payload)会直接被发送到该节点的后续处理节点(successor node)作为输入数据,从而完全绕过了出现故障的节点。这种方法适用于那些仅负责发送“暂停事件”(pause event)的叶子节点(leaf nodes);这些节点会等待用户的响应,之后流程才会继续进行到下一步。nil默认值取决于节点的类型。workflow.NewDynamicNode自动设置nil → &true(重新进入模式):因为在恢复执行时必须重新加载协调器的主体部分(orchestrator body),以便能够获取之前缓存好的子任务结果(cached child results)。workflow.NewFunctionNode以及其他叶节点(leaf node)的构造函数 leavenil“按现状”(as-is);引擎会将这种情况视为数据交接(handoff)过程。&false显式的(Explicit)&false在任何类型的节点上,该规则始终都会被遵守(即:该规则始终会被执行)。
// NewDynamicNode: nil RerunOnResume is automatically set to &true.
// Passing &rerun explicitly is equivalent and makes the intent clear.
rerun := true
orchestratorNode := workflow.NewDynamicNode[string, string]("my_workflow",
myOrchestratorfn,
workflow.NodeConfig{RerunOnResume: &rerun}, // re-entry: node body re-runs on resume
)
// NewFunctionNode: nil RerunOnResume stays nil → engine treats as handoff.
handoffNode := workflow.NewFunctionNode("leaf_node",
myLeafFn,
workflow.NodeConfig{}, // nil RerunOnResume → handoff for FunctionNode
)
工作流程(Workflows)¶
在 ADK 的动态工作流中,您会使用一个动态节点作为所有节点的主要协调者。该动态节点负责管理正在运行的子节点,以及这些节点的执行逻辑(执行顺序和执行路径)。
@node(rerun_on_resume=True)
async def my_workflow(ctx):
# run_node executes a node and returns its output
result = await ctx.run_node(my_function_node, node_input="Hello")
result_formatted = await ctx.run_node(my_formatting_node, node_input=result)
return result_formatted
# Run the workflow
root_agent = Workflow(
name="root_agent",
edges=[("START", my_workflow)],
)
这个“协调器”是一个异步函数(async function),它会等待某个事件或条件的发生。 ctx.runNode() 对于每个子步骤(child step),将其封装成一个节点(node)。 rerunOnResume: true 并将其作为该图唯一的边来使用。
const myFormattingNode = node(
(_ctx: NodeContext, nodeInput: string) => `>> ${nodeInput.trim()} <<`,
{ name: 'my_formatting_node' },
);
const myWorkflow = node(
async (ctx: NodeContext, nodeInput: unknown) => {
const greeted = await ctx.runNode(helloNode, nodeInput);
const again = await ctx.runNode(successNode, greeted.output);
const formatted = await ctx.runNode(myFormattingNode, again.output);
return formatted.output;
},
{ name: 'my_workflow', rerunOnResume: true },
);
export const rootAgent = new Workflow({
name: 'root_agent',
edges: [['START', myWorkflow]],
});
workflow.NewDynamicNode 创建一个编排器(orchestator),该编排器的主体部分会调用其他组件或函数。
workflow.RunNode 对于每个子步骤(child step)来说…… workflowagent.New 使用(with)
workflow.Chain(workflow.Start, myWorkflow) 相当于
Workflow(edges=[("START", my_workflow)]):
// orchestratorWorkflow is a dynamic node that schedules two children in
// sequence via workflow.RunNode, equivalent to:
//
// @node(rerun_on_resume=True)
// async def my_workflow(ctx):
// result = await ctx.run_node(my_function_node, node_input="Hello")
// result_formatted = await ctx.run_node(my_formatting_node, node_input=result)
// return result_formatted
var orchestratorWorkflow = workflow.NewDynamicNode[string, string]("my_workflow",
func(ctx agent.Context, _ string, _ func(*session.Event) error) (string, error) {
result, err := workflow.RunNode[string](ctx, myFunctionNode, "Hello")
if err != nil {
return "", err
}
return workflow.RunNode[string](ctx, myFormattingNode, result)
},
workflow.NodeConfig{},
)
数据处理¶
在使用 ADK 的动态工作流时,传递数据比以前更加简单了。 基于图的工作流程(graph-based workflows) 因为运行一个子节点会直接将该节点的输出结果返回给调用者,从而无需手动读取和写入用于数据传输的会话状态键。
from google.adk import Context
from google.adk.workflow import node
@node(rerun_on_resume=True)
async def editorial_workflow(ctx: Context, node_input: str):
# Agent Node generates output
raw_draft = await ctx.run_node(draft_agent, node_input)
# Function Node formats text
formatted_text = await ctx.run_node(format_function_node, raw_draft)
return formatted_text
您还可以使用自定义的类来传递特定的数据结构,并配置输入和输出的数据结构,这与基于图的工作流节点的实现方式类似。
from google.adk import Agent
from google.adk import Context
from google.adk.workflow import node
from pydantic import BaseModel
class CityTime(BaseModel):
time_info: str # time information
city: str # city name
@node
def city_time_function(node_input: str):
"""Simulate returning the current time in a specified city."""
return CityTime(time_info="10:10 AM", city=node_input)
city_report_agent = Agent(
name="city_report_agent",
model="gemini-flash-latest",
input_schema=CityTime,
instruction="""output the data provided by the previous node.""",
)
@node(rerun_on_resume=True) # workflow node
async def city_workflow(ctx: Context):
city_time = await ctx.run_node(city_time_function, "Paris")
report_text = await ctx.run_node(city_report_agent, city_time)
return report_text
The ctx.runNode() 该函数会直接返回子节点的结果,因此无需使用会话状态(session state)来读取或写入数据,从而实现数据在系统中的传递。该函数可以接受任何类似节点(node-like)的数据类型,包括……(此处可补充具体数据类型)。
LlmAgent(直接使用该字符串,无需将其包裹在任何标签或括号中) node() first:
import { LlmAgent, node, NodeContext, Workflow } from '@google/adk';
const draftAgent = new LlmAgent({
name: 'draft_agent',
model: 'gemini-flash-latest',
instruction: 'Write a short draft for the user request.',
});
const formatFunctionNode = node(
(_ctx: NodeContext, rawDraft: string) =>
rawDraft
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
.map((line) => `| ${line}`)
.join('\n'),
{ name: 'format_function_node' },
);
const editorialWorkflow = node(
async (ctx: NodeContext, userRequest: string) => {
const rawDraft = await ctx.runNode(draftAgent, userRequest);
const formattedText = await ctx.runNode(
formatFunctionNode,
rawDraft.output,
);
return formattedText.output;
},
{ name: 'editorial_workflow', rerunOnResume: true },
);
export const rootAgent = new Workflow({
name: 'root_agent',
edges: [['START', editorialWorkflow]],
});
这些模式的工作原理与图论中的模式相同。你需要将它们连接到你运行的节点上,具体方法如下所示: 序列路由(Sequence Route) section.
在 Go 语言中, workflow.NewAgentNode “wraps an” 的意思是“将……包裹起来”或“用……覆盖”。例如:
- “This function wraps the input data in a protective layer before processing it.”(这个函数在处理数据之前,会先将数据包裹在一个保护层中。)
- “The software uses a special material to wrap the wires to prevent damage.”(该软件使用特殊材料来包裹电线,以防止损坏。) agent.Agent 这样就可以通过……来调用它了。 workflow.RunNode 在一个动态的编排系统中(即一个能够根据实时需求自动调整资源分配和任务执行的系统),每个任务的输出结果都会被记录下来。 RunNode 调用返回的结果是一个类型化的值(即具体的数据类型),不涉及任何会话状态(session state)。
需要执行读取操作(reads)来获取这些数据。
// newDataHandlingWorkflow demonstrates how to pass data between a dynamic
// orchestrator and an LlmAgent-backed node. workflow.NewAgentNode wraps an
// agent.Agent so it can be invoked via workflow.RunNode.
//
// In Python this mirrors:
//
// city_report_agent = Agent(name="city_report_agent", ...)
// @node
// async def city_workflow(ctx: Context):
// city_time = await ctx.run_node(city_time_function, "Paris")
// report_text = await ctx.run_node(city_report_agent, city_time)
// return report_text
func newDataHandlingWorkflow(ctx context.Context) (agent.Agent, error) {
model, err := gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
if err != nil {
return nil, fmt.Errorf("gemini.NewModel: %w", err)
}
// cityTimeNode is a FunctionNode that returns a formatted city-time string.
cityTimeNode := workflow.NewFunctionNode("city_time_function",
func(_ agent.Context, city string) (string, error) {
return fmt.Sprintf("10:10 AM in %s", city), nil
},
workflow.NodeConfig{},
)
// cityReportAgent is an LlmAgent that receives the city-time string and
// produces a human-friendly report.
cityReportAgent, err := llmagent.New(llmagent.Config{
Name: "city_report_agent",
Model: model,
Description: "Reports city time information.",
Instruction: "Output the data provided by the previous node in a friendly sentence.",
})
if err != nil {
return nil, fmt.Errorf("llmagent.New (cityReport): %w", err)
}
// workflow.NewAgentNode wraps cityReportAgent so it can be called from
// inside a dynamic node via workflow.RunNode.
cityReportNode, err := workflow.NewAgentNode(cityReportAgent, workflow.NodeConfig{})
if err != nil {
return nil, fmt.Errorf("workflow.NewAgentNode: %w", err)
}
cityWorkflow := workflow.NewDynamicNode[string, string]("city_workflow",
func(ctx agent.Context, _ string, _ func(*session.Event) error) (string, error) {
cityTime, err := workflow.RunNode[string](ctx, cityTimeNode, "Paris")
if err != nil {
return "", err
}
return workflow.RunNode[string](ctx, cityReportNode, cityTime)
},
workflow.NodeConfig{},
)
return workflowagent.New(workflowagent.Config{
Name: "data_handling_workflow",
SubAgents: []agent.Agent{cityReportAgent},
Edges: workflow.Chain(workflow.Start, cityWorkflow),
})
}
有关工作流节点之间数据处理的更多信息,请参阅…… 代理工作流程中的数据处理.
工作流程路由(Workflow Routes)¶
与传统的系统相比,ADK(Active Directory Kinematics)中的动态工作流程在路由逻辑方面提供了更大的灵活性。 基于图的工作流程(graph-based workflows)包括迭代循环或更复杂的分支逻辑。本节介绍了一些可用于路由(routing)的技术。
序列路由(Sequence Route)¶
在 ADK 中,你可以使用动态工作流来实现顺序任务处理;这与使用基于图形的工作流的方式完全相同。
以下代码片段展示了一个动态的工作流程,其中包含一个代理(agent)、一个函数节点(function node),以及另一个代理。
一条顺序性的路线正在等待被执行(或:一条需要按特定顺序被访问的路径正在等待被使用)。 ctx.runNode() 这些函数会依次被调用。每个函数的执行都会在下一个函数开始之前完成。
import { LlmAgent, node, NodeContext, Workflow } from '@google/adk';
import { z } from 'zod';
const cityTimeSchema = z.object({
timeInfo: z.string().describe('Time information.'),
city: z.string().describe('City name.'),
});
type CityTime = z.infer<typeof cityTimeSchema>;
const cityGeneratorAgent = new LlmAgent({
name: 'city_generator_agent',
model: 'gemini-flash-latest',
instruction: 'Return the name of a random city. Return only the name.',
});
/** Simulates returning the current time in a specified city. */
const cityTimeFunction = node(
(_ctx: NodeContext, city: string): CityTime => ({
timeInfo: '10:10 AM',
city: city.trim(),
}),
{ name: 'city_time_function', outputSchema: cityTimeSchema },
);
const cityReportAgent = node(
new LlmAgent({
name: 'city_report_agent',
model: 'gemini-flash-latest',
instruction: 'Output the data provided by the previous node as a sentence.',
}),
{ inputSchema: cityTimeSchema },
);
const cityWorkflow = node(
async (ctx: NodeContext) => {
const city = await ctx.runNode(cityGeneratorAgent);
const cityTime = await ctx.runNode(cityTimeFunction, city.output);
const reportText = await ctx.runNode(cityReportAgent, cityTime.output);
return reportText.output;
},
{ name: 'city_workflow', rerunOnResume: true },
);
export const rootAgent = new Workflow({
name: 'root_agent',
edges: [['START', cityWorkflow]],
});
调用 workflow.RunNode 依次在……内部 NewDynamicNode `body` —
每次调用都会等待当前子任务完成,才会开始下一次调用。
上面的示例展示了数据处理的流程。 这正好证明了这一点。
模式(Pattern): cityWorkflow 调用(functions/methods) workflow.RunNode for cityTimeNode 然后 cityReportNode 按照顺序处理每个节点的输出结果,并将每个节点的输出结果传递给下一个节点。
循环路由(Loop route)¶
对于那些需要使用迭代循环来执行任务的工作流程来说,动态工作流程在定义所需的路由逻辑方面提供了更大的灵活性。
以下代码示例展示了如何使用动态工作流来构建一个用于生成、审查和更新代码的工作流循环:
from google.adk import Context
from google.adk import Event
from google.adk.agents import LlmAgent
from google.adk.workflow import node
coder_agent = LlmAgent(
name="generator_agent",
model="gemini-flash-latest",
instruction="Write python code for user request.",
)
@node(name="lint_reviewer")
async def compile_lint_check(ctx: Context, node_input: str):
# Simulate API call or lint check
class Response:
findings = ""
return Response()
fixer_agent = LlmAgent(
name="fixer_agent",
model="gemini-flash-latest",
instruction="""Refactor current code {code}.
Based on compile & lint review: {findings}""",
)
@node(rerun_on_resume=True) # workflow node
async def code_workflow(ctx: Context, node_input: str):
code = await ctx.run_node(coder_agent, node_input)
check_resp = await ctx.run_node(compile_lint_check, code)
while check_resp.findings:
yield Event(state={"code": code, "findings": check_resp.findings})
code = await ctx.run_node(fixer_agent, {"code": code, "findings": check_resp.findings})
check_resp = await ctx.run_node(compile_lint_check, code)
yield Event(output=code)
动态工作流可以通过将迭代过程定义为一个普通的循环(而不是图中的“回边”),从而帮助保持工作流逻辑的简洁性。相关数据存储在局部变量中,状态信息仅在被代理程序的指令模板需要读取时才会被写入相应的位置。与图中的循环不同,这种普通循环受到其循环条件的限制(即循环会在满足条件后终止)。
import { LlmAgent, node, NodeContext, Workflow } from '@google/adk';
/** Safety bound on the refine loop. */
const MAX_FIX_ROUNDS = 3;
const coderAgent = new LlmAgent({
name: 'generator_agent',
model: 'gemini-flash-latest',
instruction: 'Write TypeScript code for the user request. Output code only.',
});
/** Simulates a compile / lint pass. Empty findings means "clean". */
const compileLintCheck = node(
(_ctx: NodeContext, code: string) => {
const findings: string[] = [];
if (!/\/\*\*/.test(code)) {
findings.push('every function needs a JSDoc comment');
}
if (!/\)\s*:\s*\w/.test(code)) {
findings.push('add return type annotations');
}
return { findings: findings.join('; ') };
},
{ name: 'lint_reviewer' },
);
const fixerAgent = new LlmAgent({
name: 'fixer_agent',
model: 'gemini-flash-latest',
instruction: `Refactor current code {code}.
Based on compile & lint review: {findings}
Output code only.`,
});
const codeWorkflow = node(
async (ctx: NodeContext, userRequest: string) => {
let code = (await ctx.runNode(coderAgent, userRequest)).output as string;
let checkResp = (await ctx.runNode(compileLintCheck, code)).output as {
findings: string;
};
for (let round = 0; checkResp.findings && round < MAX_FIX_ROUNDS; round++) {
ctx.state.set('code', code);
ctx.state.set('findings', checkResp.findings);
code = (
await ctx.runNode(fixerAgent, { code, findings: checkResp.findings })
).output as string;
checkResp = (await ctx.runNode(compileLintCheck, code)).output as {
findings: string;
};
}
return code;
},
{ name: 'code_workflow', rerunOnResume: true },
);
export const rootAgent = new Workflow({
name: 'root_agent',
edges: [['START', codeWorkflow]],
});
在 Go 语言中,循环结构非常简单(即语法简洁、易于理解)。 for 在动态节点的体内执行循环。当 lint 检查节点没有发现任何问题时,它会返回一个空字符串,这个信号会促使循环终止。
// newLoopWorkflow demonstrates an iterative loop inside a dynamic node.
// The orchestrator body uses a plain Go for loop to keep calling the
// lintCheckNode until there are no findings — equivalent to Python's:
//
// @node
// async def code_workflow(ctx: Context, user_request: str):
// code = await ctx.run_node(coder_agent, user_request)
// check_resp = await ctx.run_node(compile_lint_check, code)
// while check_resp.findings:
// code = await ctx.run_node(fixer_agent, ...)
// check_resp = await ctx.run_node(compile_lint_check, code)
// return code
func newLoopWorkflow(ctx context.Context) (agent.Agent, error) {
model, err := gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
if err != nil {
return nil, fmt.Errorf("gemini.NewModel: %w", err)
}
coderAgent, err := llmagent.New(llmagent.Config{
Name: "generator_agent",
Model: model,
Description: "Writes Go code for the user request.",
Instruction: "Write Go code for the user request. Output only the code.",
OutputKey: "generated_code",
})
if err != nil {
return nil, fmt.Errorf("llmagent.New (coder): %w", err)
}
coderNode, err := workflow.NewAgentNode(coderAgent, workflow.NodeConfig{})
if err != nil {
return nil, fmt.Errorf("workflow.NewAgentNode (coder): %w", err)
}
// lintCheckNode simulates a lint/compile check. It returns an empty
// string when there are no findings, signalling the loop to exit.
lintCheckNode := workflow.NewFunctionNode("lint_reviewer",
func(_ agent.Context, code string) (string, error) {
// Simulate a lint check: return findings or empty string when clean.
if len(code) < 50 {
return "Code is too short; add error handling.", nil
}
return "", nil // no findings — loop exits
},
workflow.NodeConfig{},
)
fixerAgent, err := llmagent.New(llmagent.Config{
Name: "fixer_agent",
Model: model,
Description: "Refactors code based on lint findings.",
Instruction: "Refactor the provided code to address the review findings. Output only the improved code.",
})
if err != nil {
return nil, fmt.Errorf("llmagent.New (fixer): %w", err)
}
fixerNode, err := workflow.NewAgentNode(fixerAgent, workflow.NodeConfig{})
if err != nil {
return nil, fmt.Errorf("workflow.NewAgentNode (fixer): %w", err)
}
codeWorkflow := workflow.NewDynamicNode[string, string]("code_workflow",
func(ctx agent.Context, userRequest string, _ func(*session.Event) error) (string, error) {
code, err := workflow.RunNode[string](ctx, coderNode, userRequest)
if err != nil {
return "", err
}
findings, err := workflow.RunNode[string](ctx, lintCheckNode, code)
if err != nil {
return "", err
}
// Loop until the lint check reports no findings.
for findings != "" {
code, err = workflow.RunNode[string](ctx, fixerNode, code)
if err != nil {
return "", err
}
findings, err = workflow.RunNode[string](ctx, lintCheckNode, code)
if err != nil {
return "", err
}
}
return code, nil
},
workflow.NodeConfig{},
)
return workflowagent.New(workflowagent.Config{
Name: "code_pipeline",
SubAgents: []agent.Agent{coderAgent, fixerAgent},
Edges: workflow.Chain(workflow.Start, codeWorkflow),
})
}
并行执行路径(Parallel execution routes)¶
ADK(Active Directory Domain Services)中的动态工作流支持并行执行。
在 Python 中,你可以使用…… asyncio.gather 为了实现并行执行:
import asyncio
from typing import Any
from google.adk import Context
from google.adk.workflow import node
@node
def worker_node(node_input: Any):
"""Processes a single item."""
return f"done {node_input}"
@node(rerun_on_resume=True)
async def parallel_supervisor(ctx: Context, node_input: list[Any]):
"""Runs worker_node in parallel for each item in the input list."""
tasks = []
for item in node_input:
# ctx.run_node returns a coroutine. Append instead of awaiting
# immediately, and use a sub-branch to isolate each run's events.
tasks.append(ctx.run_node(worker_node, item, use_sub_branch=True))
# Collect all results in parallel
results = await asyncio.gather(*tasks)
return results
提示:恢复并行节点的运行状态
该工作流框架确保:如果动态工作流被重新启动,那么只有那些失败或被中断的 worker 节点(包括并行执行的 worker 节点)才会被重新执行。
The ctx.runNode() 该方法返回一个 `Promise` 对象;因此,在等待任何一个子任务的结果之前,所有子任务都会被同时启动(即它们会并行执行)。
Promise.all 收集结果。运行 ID 是按照调用顺序分配的;因此,需要通过同步循环来执行子任务,以确保在恢复执行(resume)过程中这些 ID 的分配顺序始终是确定的(即不会发生变化)。
import { node, NodeContext, Workflow } from '@google/adk';
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
/** The worker run once per list item. */
const realNode = node(
async (_ctx: NodeContext, item: string) => {
await sleep(200);
return { item, length: item.length };
},
{ name: 'analyze_item' },
);
const parallelSupervisor = node(
async (ctx: NodeContext, nodeInput: string) => {
const items = nodeInput
.split(',')
.map((item) => item.trim())
.filter(Boolean);
const tasks = items.map((item) => ctx.runNode(realNode, item));
const results = await Promise.all(tasks);
return results.map((result) => result.output);
},
{ name: 'parallel_supervisor', rerunOnResume: true },
);
const summarize = node(
(_ctx: NodeContext, results: Array<{ item: string; length: number }>) =>
results.map((r) => `${r.item}: ${r.length} chars`).join('\n'),
{ name: 'summarize' },
);
export const rootAgent = new Workflow({
name: 'root_agent',
edges: [['START', parallelSupervisor, summarize]],
});
提示:建议使用内置的并行处理工具(即内置的并行工作者)。
要针对列表中的每个元素分别运行一个节点,请使用以下方法:
node(worker, {parallelWorker: true, maxParallelWorkers: 4})此选项用于控制任务的并发执行数量(默认值为 8)。当您需要自定义任务调度机制或处理部分任务失败的情况时,请使用上述手动配置方法。在任务重新开始时,只有那些失败或被中断的任务才会被重新执行。
在 Go 语言中, workflow.NewParallelWorker 该函数会为列表中的每个元素分别创建一个子节点,并同时执行这些子节点;最终将所有结果收集到一个输出切片中。 maxConcurrency 该参数决定了可以同时运行的并发激活(concurrent activations)的数量。 0 这意味着“数量是无限的”(即没有限制)。
// newParallelWorkflow demonstrates parallel execution using
// workflow.NewParallelWorker. The worker node runs a wrapped child node
// concurrently for each element in a list input, collecting results.
//
// This is the Go equivalent of using asyncio.gather in Python:
//
// @node(rerun_on_resume=True)
// async def parallel_supervisor(ctx, node_input, real_node):
// tasks = [ctx.run_node(real_node, item) for item in node_input]
// results = await asyncio.gather(*tasks)
// return results
func newParallelWorkflow() (agent.Agent, error) {
// workerNode processes a single item. NewParallelWorker will call it
// once per element of the list input, concurrently.
workerNode := workflow.NewFunctionNode("worker",
func(_ agent.Context, item string) (string, error) {
return fmt.Sprintf("processed: %s", item), nil
},
workflow.NodeConfig{},
)
// NewParallelWorker wraps workerNode so it runs concurrently for each
// element of a []string input. maxConcurrency=0 means unlimited.
parallelWorker, err := workflow.NewParallelWorker(
"parallel_supervisor",
workerNode,
0, // maxConcurrency: 0 = unlimited
workflow.NodeConfig{},
)
if err != nil {
return nil, fmt.Errorf("workflow.NewParallelWorker: %w", err)
}
return workflowagent.New(workflowagent.Config{
Name: "parallel_workflow",
Description: "Runs a worker node in parallel for each item in the input list.",
Edges: workflow.Chain(workflow.Start, parallelWorker),
})
}
提示:恢复并行节点的运行状态
该工作流框架确保:如果动态工作流被重新启动,那么只有那些失败或被中断的 worker 节点才会被重新执行(包括那些由该框架管理的并行 worker 节点)。 NewParallelWorker.
人工输入(Human input)¶
在 ADK 中,动态工作流程也可以包含人工输入或需要人工参与的步骤(即“Human Input or Human In the Loop”步骤)。
你可以通过提供人类输入的内容,将这些输入整合到工作流程中。 RequestInput 从一个节点开始,该节点会暂停工作流程并等待用户输入。以下代码示例展示了如何创建一个用于接收用户输入的节点,并将其集成到工作流程中:
from typing import Any
from google.adk import Context
from google.adk.events import RequestInput
from google.adk.workflow import node
@node(rerun_on_resume=False)
async def get_user_approval(ctx: Context, node_input: Any):
"""Yields a RequestInput to pause the workflow and wait for user input."""
yield RequestInput(message="Please approve this request (Yes/No)")
@node(rerun_on_resume=True)
async def handle_process(ctx: Context, node_input: Any):
"""The orchestrator calling the interactive step."""
user_response = await ctx.run_node(get_user_approval)
if user_response.lower() == "yes":
return "Approved"
return "Denied"
重要提示:具有以下属性的父节点…… ctx.run_node
在动态工作流中,会调用这些父节点的代码。 ctx.run_node 必须设置
rerun_on_resume=True 为了正确处理各种中断情况(即那些可能打断正常流程的事件)。
叶节点返回一个值(或结果)。 RequestInput 要暂停工作流程,并保持默认设置。 rerunOnResume: false 因此,回复结果就成为了该函数的输出。调用该函数的协调器(orchestrator)必须进行相应的设置。 rerunOnResume: true:
import { node, NodeContext, RequestInput, Workflow } from '@google/adk';
/**
* Pauses the workflow and waits for user input.
*
* `rerunOnResume: false` (the default, spelled out here because it is the
* point) is what makes this a one-liner: the reply is handed to the node as
* its output instead of the body running a second time to collect it.
*/
const getUserApproval = node(
() => new RequestInput({ message: 'Please approve this request (Yes/No)' }),
{ name: 'get_user_approval', rerunOnResume: false },
);
/** The orchestrator calling the interactive step. */
const handleProcess = node(
async (ctx: NodeContext, nodeInput: unknown) => {
const approval = await ctx.runNode(getUserApproval, nodeInput);
if (approval.interruptIds.length > 0) {
return undefined;
}
const userResponse = String(approval.output ?? '')
.trim()
.toLowerCase();
if (userResponse === 'yes') {
return 'Approved';
}
return 'Denied';
},
{ name: 'handle_process', rerunOnResume: true },
);
export const rootAgent = new Workflow({
name: 'root_agent',
edges: [['START', handleProcess]],
});
重要提示:请务必进行检查。 interruptIds 在做出决定之前
The ctx.runNode() 该方法确实可以执行相应的操作。 不;并非 当某个子节点(child node)中断执行时,会抛出一个错误。不过程序本身会正常继续执行(即返回结果)。 interruptIds
结果的属性已被填充(即结果中的相关数据已被设置或计算完成)。 output 该属性仍然有效(或未被修改)。
undefined. 检查 interruptIds 在使用结果之前,请务必进行相应的检查。如果某个协调器(orchestration tool)跳过了这一检查步骤,它就会将缺失的输出数据视为有效的“答案”,并继续使用用户从未提供的值(即空值或默认值)。
在 Go 语言中,可以使用……(请填写具体的函数或方法名称)。 workflow.NewEmittingFunctionNode 使用(with)
workflow.ResumeOrRequestInput 为了实现“重新进入”(re-entry)模式(HITL pattern),在第一次尝试时…… ResumeOrRequestInput “emits a” 的意思是“发出某种信号、声音或辐射”。例如:
- “The light bulb emits a bright white light”(灯泡发出明亮的白光。)
- “The machine emits a low noise during operation”(机器在运行时发出轻微的噪音。) session.RequestInput
事件处理与返回结果 ErrNodeInterrupted工作流程会暂停。在收到人类的回复后,该节点会从开始处重新执行(即从头开始再次运行)。RerunOnResume: &true)以及 ResumeOrRequestInput 直接返回人类的回复:
// newHITLWorkflow demonstrates the re-entry HITL pattern using
// workflow.ResumeOrRequestInput. On the first pass the node emits a
// RequestInput event and returns ErrNodeInterrupted (pausing the workflow).
// After the human replies, the same node is re-run from the top
// (RerunOnResume=&true) and ResumeOrRequestInput returns the human's reply.
//
// In Python this is equivalent to:
//
// @node(rerun_on_resume=True)
// async def get_user_approval(ctx, node_input):
// yield RequestInput(message="Please approve this request (Yes/No)")
//
// @node(rerun_on_resume=True)
// async def handle_process(ctx, node_input):
// user_response = await ctx.run_node(get_user_approval)
// if user_response.lower() == "yes":
// return "Approved"
// return "Denied"
func newHITLWorkflow() (agent.Agent, error) {
rerun := true
// approvalNode pauses on the first pass to ask the user for a Yes/No
// approval, then resolves their decision on resume.
// workflow.ResumeOrRequestInput handles both phases.
approvalNode := workflow.NewEmittingFunctionNode[any, any]("get_user_approval",
func(nc agent.Context, _ any, emit func(*session.Event) error) (any, error) {
// ResumeOrRequestInput: on first pass, emits the prompt and
// returns ErrNodeInterrupted. On re-run after the human replies,
// it returns the reply payload directly.
reply, err := workflow.ResumeOrRequestInput(nc, emit, session.RequestInput{
InterruptID: "user_approval",
Message: "Please approve this request (Yes/No)",
})
if err != nil {
return nil, err
}
response, _ := reply.(string)
if response == "" {
response = "No"
}
if response == "yes" || response == "Yes" {
return "Approved", nil
}
return "Denied", nil
},
workflow.NodeConfig{RerunOnResume: &rerun},
)
return workflowagent.New(workflowagent.Config{
Name: "hitl_workflow",
Description: "Pauses for user approval before completing a task.",
Edges: workflow.Chain(workflow.Start, approvalNode),
})
}
高级功能¶
动态工作流提供了一些高级功能,旨在应对更复杂的开发场景。这些功能使得对执行过程的控制更加精细,并能够更好地与现有的技术基础设施集成。
执行ID(Execution IDs)¶
ADK框架会根据父节点的ID以及一个计数器,为子节点的执行生成一个唯一的标识符(ID)。ADK工作流会为每个被调度执行的节点使用这样的唯一标识符,以便识别之前的执行结果。这些标识符是根据节点的执行顺序生成的,用于在需要恢复或重新执行工作流时,确保任务能够按照正确的顺序被重新运行。
自定义执行ID¶
在某些罕见的情况下,你可能需要使用稳定的标识符(例如在处理可重新排序的列表时)。不过通常应避免这样做,因为这可能会影响工作流程中任务的重试机制以及流程的继续执行。这些标识符主要用于检查节点的状态;如果某个节点已经被执行过,系统会跳过对该节点的再次执行。如果你提供了自定义的标识符,请确保这些标识符在重新执行工作流程时具有确定性(即每次执行时都能得到相同的标识符),并且对于相同的输入数据,这些标识符在逻辑上应保持不变。
警告:自定义的执行ID
请避免创建自定义的执行 ID。由于执行 ID 用于确定节点的执行顺序,因此如果系统尝试重新运行工作流中的这些节点时,自定义的执行 ID 可能会导致问题。
from google.adk import Context
from google.adk.workflow import node
from pydantic import BaseModel
from typing import Any
import asyncio
class Product(BaseModel):
sku: str
quantity: int
class Order(BaseModel):
order_id: str
cart_items: list[Product]
async def get_orders() -> list[Order]:
"""Fetch the orders to process from your own data source."""
...
@node
async def process_order(node_input: Order):
"""Processes a single order."""
return f"processed {node_input.order_id}"
@node(rerun_on_resume=True)
async def process_all_orders(ctx: Context, node_input: Any):
orders = await get_orders()
process_tasks = []
for order in orders:
# Use run_id to provide a custom identifier.
# Custom run_ids must contain at least one non-numeric character
# to avoid collision with auto-generated sequential numeric IDs.
task = ctx.run_node(process_order, order, run_id=f"order-{order.order_id}")
process_tasks.append(task)
results = await asyncio.gather(*process_tasks)
return results
默认情况下,自动生成的运行 ID 是从某个固定值开始、按顺序递增的整数。
"1" (以字符串的形式表示)。自定义。 run_id 这些值必须至少包含一个非数字字符,以避免与这些自动生成的 ID 发生冲突。
传递一个…… runId 作为最后一个选项(用于指定命令的结束位置) ctx.runNode()该 ID 必须至少包含一个非数字字符,以避免与系统自动生成的连续 ID 发生冲突。
import { node, NodeContext, Workflow } from '@google/adk';
interface Order {
orderId: string;
cartItems: string[];
}
/** Stands in for loading orders from a database. */
async function getOrders(): Promise<Order[]> {
return [
{ orderId: 'a91', cartItems: ['keyboard', 'mouse'] },
{ orderId: 'b02', cartItems: ['monitor'] },
{ orderId: 'c73', cartItems: ['dock', 'cable', 'hub'] },
];
}
const processOrder = node(
(_ctx: NodeContext, order: Order) =>
`order ${order.orderId}: ${order.cartItems.length} item(s) shipped`,
{ name: 'process_order' },
);
const processAllOrders = node(
async (ctx: NodeContext) => {
const orders = await getOrders();
const processTasks = orders.map((order) =>
ctx.runNode(processOrder, order, { runId: `order-${order.orderId}` }),
);
const results = await Promise.all(processTasks);
return results.map((result) => result.output).join('\n');
},
{ name: 'process_all_orders', rerunOnResume: true },
);
export const rootAgent = new Workflow({
name: 'root_agent',
edges: [['START', processAllOrders]],
});
在 Go 语言中,传递参数的方式如下: workflow.WithRunID("order-x") 作为最后一个选项(用于指定命令的结束位置)
workflow.RunNode该 ID 必须至少包含一个非数字字符,以避免与系统自动生成的顺序计数器 ID 发生冲突。
// newCustomIDWorkflow demonstrates supplying stable custom run IDs via
// workflow.WithRunID — equivalent to Python's:
//
// task = ctx.run_node(process_order, order, run_id=f"order-{order.order_id}")
//
// Custom run IDs must contain at least one non-numeric character to avoid
// collision with auto-generated sequential integer IDs.
func newCustomIDWorkflow() (agent.Agent, error) {
processOrderNode := workflow.NewFunctionNode("process_order",
func(_ agent.Context, orderID string) (string, error) {
return fmt.Sprintf("processed order %s", orderID), nil
},
workflow.NodeConfig{},
)
orders := []string{"ord-001", "ord-002", "ord-003"}
processAllOrders := workflow.NewDynamicNode[any, []string]("process_all_orders",
func(ctx agent.Context, _ any, _ func(*session.Event) error) ([]string, error) {
results := make([]string, 0, len(orders))
for _, orderID := range orders {
// WithRunID supplies a stable, deterministic identifier for
// each child invocation. IDs must contain at least one
// non-numeric character to avoid collision with the
// auto-generated sequential counter IDs.
result, err := workflow.RunNode[string](
ctx,
processOrderNode,
orderID,
workflow.WithRunID(fmt.Sprintf("order-%s", orderID)),
)
if err != nil {
return nil, fmt.Errorf("process order %s: %w", orderID, err)
}
results = append(results, result)
}
return results, nil
},
workflow.NodeConfig{},
)
return workflowagent.New(workflowagent.Config{
Name: "custom_id_workflow",
Description: "Processes orders with stable per-order execution IDs.",
Edges: workflow.Chain(workflow.Start, processAllOrders),
})
}