跳转到内容

代理工作流程中的数据处理

在 ADK 中得到支持。Python v2.0.0TypeScript v2.0.0Go v2.0.0

在代理(agents)与基于图的节点(graph-based nodes)之间对数据进行结构化处理和管理至关重要,因为这有助于利用 ADK 构建可靠的业务流程。本指南详细介绍了基于图的工作流程(graph-based workflows)及协作代理(collaboration agents)中的数据处理机制,包括信息在图节点(graph nodes)之间的传输方式。内容涵盖了传递数据、内容及状态所需的关键参数,并说明了如何通过数据格式规范(data format schemas)及特定的指令语法(specific instruction syntax)来实现功能节点(function nodes)与代理节点(agent nodes)之间的结构化数据传输。

工作流程数据流

在基于图的工作流中,节点通过“事件”将数据传递给下游步骤。某个步骤将其输出写入一个具有名称的事件字段中,而下一个步骤则会将该数据作为输入接收。

在 Python 中,数据是通过特定的方式在图节点之间进行交换的。 事件处理节点数据的关键参数包括:

  • output:用于在系统组件之间传递信息的参数。 节点(Nodes).
  • message:作为对用户请求的响应而提供的数据。
  • state数据会通过自动机制在各个节点之间进行持久化(即数据会被保存并在需要时从各个节点中重新获取)。 事件 在整个 ADK 会话期间(throughout an ADK session)。

在 ADK TypeScript v2.0.0 中,节点通过事件来交换数据。处理节点数据的关键字段包括:

  • output:传递给下一个节点的值。可以直接返回该值;ADK 会将该值封装到一个事件中;或者也可以通过显式的方式设置相关字段。 createEvent({output}).
  • content:这是一条发给用户的消息。运行时系统会显示这个字段的内容,但图谱(graph)并不会将该消息传递给下一个节点。
  • route这些路由键用于确定应该选择哪条“条件性边”(即根据特定条件来决定路径的边)。

会话状态(Session state)与事件(Event)是相互独立的。节点(Node)通过特定的方式来读取和写入会话状态数据。 ctx.state累积的“delta”值会被附加到该节点的事件中。状态键(State keys)可以携带一个前缀,该前缀用于控制它们的生命周期和作用范围。

前缀 范围(Scope)
app: 该功能在应用程序的所有用户和会话中都是共享的。
user: 与用户绑定,并在用户的所有会话中保持同步(即数据会在用户的不同会话之间共享)。
temp: 在当前调用结束后会被丢弃。
(无) 该设置会在会话的整个生命周期内保持有效(即会话关闭之前,该设置不会被重置)。

在 ADK Go v2.0.0 中,数据传递的机制取决于您使用的代理类型(agent style)。

`workflow` 包 (FunctionNode, AgentNode, DynamicNode这些节点通过某种方式(未具体说明)进行通信。 session.Event 这些字段的设计方式与 Python 非常相似:

  • Event.Output节点的返回值由框架在特定情况下自动设置。 FunctionNode 返回一个非……(“non-”表示该值不属于某种预定义的类型或类别)。*genai.Content 值(Value)。 后续节点会接收这个值,并将其视为自己的输入数据(即该节点的输入类型)。 input parameter.
  • Event.Routes路由键(routing keys)是由发送数据(emitting node)明确设置的,用于选择应遵循的特定路径(conditional edge);这相当于 Python 中的相应机制。 Event(route=...).
  • Event.NodeInfo: 调度器元数据(Scheduler Metadata)path, MessageAsOutput, OutputFor该属性由工作流引擎设置;节点本身无法直接修改该属性。

预先构建的工作流代理(Prebuilt workflow agents) (sequentialagent, parallelagent, loopagent这些代理通过会话状态(session state)进行通信。

  • OutputKey 在……的时候;当……发生时 llmagent.Config:该框架会将代理程序生成的最终文本响应写入到…… state[OutputKey] 每轮结束后。
  • ctx.Session().State().Set / .Get:可以在自定义代码中随意读取或写入状态的值。
  • {key} 在……里面;处于……状态 Instruction:该框架会进行替换(即用新的内容或功能替换原有的内容或功能)。 state["key"] 在调用模型之前,需要将这些内容输入到相应的提示框(prompt)中。

状态键(State keys)可能带有前缀,这些前缀用于控制它们的生命周期(lifetime)和作用范围(scope)。

前缀常量(Prefix constant) 前缀字符串 范围(Scope)
session.KeyPrefixApp "app:" 该功能在应用程序的所有用户和会话中都是共享的。
session.KeyPrefixUser "user:" 与用户绑定,并在用户的所有会话中保持同步(即数据会在用户的不同会话之间共享)。
session.KeyPrefixTemp "temp:" 在当前调用结束后会被丢弃。
(无) — 该设置会在会话的整个生命周期内保持有效(即会话关闭之前,该设置不会被重置)。

Node.js 的输出结果

工作流程中的每个步骤都会为其后续步骤生成相应的输出结果。

使用 return 或者 `yield` 用于将数据传递给下一个节点的语法:

from google.adk import Event

def my_function_node(node_input: str):
    output_value = node_input.upper()
    return Event(output=output_value) # "THE RESULT"

使用 return 输出时的语法格式 事件 这些数据不需要额外的处理。当需要发送需要额外处理的数据时,或者如果你生成了多个数据项,你可以使用多个(相应的处理方法或工具)。 `yield` 每个命令(command)都需要单独处理。 `yield` `call` 会发出一个单独的(信号/消息等)。 事件但是,这些事件中只有一个可能会触发相应的结果(或:只有其中一个事件会带来预期的效果)。 output这个单一值会被图中的下一个节点接收。 return 或者 `yield` 没有参数的命令会传递一个默认值(或空值)。 None 将数据值传递给下一个节点。

有三种等效的方法可以生成节点的输出:直接返回一个值,或者通过其他方式来生成输出结果。 createEvent({output})或者,可以从异步生成器(async generator)中获取“完成事件”(yield events),以便在显示结果的同时,也能实时显示任务的执行进度。

import { createEvent, node, NodeContext, Workflow } from '@google/adk';

const returnRawValue = node(
  (_ctx: NodeContext, nodeInput: string) => nodeInput.toUpperCase(),
  { name: 'return_raw_value' },
);

const returnEventOutput = node(
  (_ctx: NodeContext, nodeInput: string) =>
    createEvent({ output: `${nodeInput}!` }),
  { name: 'return_event_output' },
);

const yieldProgressThenOutput = node(
  async function* (_ctx: NodeContext, nodeInput: string) {
    yield createEvent({
      content: { role: 'model', parts: [{ text: 'Working on it...' }] },
    });
    yield createEvent({ output: `<<${nodeInput}>>` });
  },
  { name: 'yield_progress_then_output' },
);

export const rootAgent = new Workflow({
  name: 'node_output_workflow',
  edges: [
    ['START', returnRawValue, returnEventOutput, yieldProgressThenOutput],
  ],
});

注意:请执行“emit”操作。 output 每次执行时只触发一个事件。

一个节点可以生成任意数量的事件(events)。 output在这种情况下,ADK 不会引发任何错误。每个事件都会覆盖前一个事件的结果,因此后续节点只会接收到最终的结果值。请使用这种方法。 content 改为显示进度信息(progress messages)吧。

`workflow` 包: a FunctionNode 它只是返回一个 Go 语言类型的数据。 该框架会自动将返回值包装在一个适当的结构体或对象中。 session.Event 并设置(相关值) Event.Output后续节点会接收这个值,并将其作为自己的类型数据(typed data)进行使用。 input 参数——无需手动构建事件:

// newEventOutputPipeline demonstrates the primary data-passing mechanism for
// workflow package nodes: a FunctionNode returns a typed Go value, and the
// framework automatically sets event.Output to that value. The successor node
// receives it as its typed `input` parameter.
//
// This mirrors the Python pattern exactly:
//
//  def my_function_node(node_input: str):
//      return Event(output=node_input.upper())
//
// In Go, the function simply returns the value — no Event construction needed.
func newEventOutputPipeline() (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
    }

    nodeA := workflow.NewFunctionNode("upper", upperFn, workflow.NodeConfig{})
    nodeB := workflow.NewFunctionNode("suffix", suffixFn, workflow.NodeConfig{})

    // workflow.Chain wires START → nodeA → nodeB. The output of nodeA is
    // delivered as the typed input of nodeB via event.Output.
    return workflowagent.New(workflowagent.Config{
        Name:        "event_output_pipeline",
        Description: "Demonstrates Event.Output data flow between FunctionNodes.",
        Edges:       workflow.Chain(workflow.Start, nodeA, nodeB),
    })
}

预先构建的工作流代理(Prebuilt workflow agents): 使用 OutputKey 在……的时候;当……发生时 llmagent.Config 要将代理的文本响应保存到会话状态中,之后可以通过该会话状态来引用该文本响应。 {key} 在下游代理中(in downstream agents’) Instruction templates:

// newOutputKeyPipeline demonstrates the OutputKey mechanism for the prebuilt
// sequentialagent. When OutputKey is set on an llmagent.Config, the framework
// automatically writes the agent's final text response to session state under
// that key. Downstream agents read it by referencing {key} in their Instruction.
//
// This pattern applies to sequentialagent / parallelagent / loopagent.
// For the workflow package (FunctionNode / AgentNode), use Event.Output instead.
func newOutputKeyPipeline(ctx context.Context, geminiModel model.LLM) (agent.Agent, error) {
    step1, err := llmagent.New(llmagent.Config{
        Name:        "step_1",
        Model:       geminiModel,
        Description: "Transforms the user's text.",
        Instruction: "Convert the user's message to uppercase. Output only the transformed text.",
        OutputKey:   "upper_result",
    })
    if err != nil {
        return nil, fmt.Errorf("step1: %w", err)
    }

    step2, err := llmagent.New(llmagent.Config{
        Name:        "step_2",
        Model:       geminiModel,
        Description: "Reports the transformed text.",
        Instruction: "The transformed text is: {upper_result}. Report it to the user.",
    })
    if err != nil {
        return nil, fmt.Errorf("step2: %w", err)
    }

    return sequentialagent.New(sequentialagent.Config{
        AgentConfig: agent.Config{
            Name:      "output_key_pipeline",
            SubAgents: []agent.Agent{step1, step2},
        },
    })
}

Node.js 的输出结果:正在传递结构化数据。

您可以使用可序列化的格式传递更长、结构更复杂的数据。

def my_function_node_3():
    yield Event(
        output={
            "city_name": "Paris",
            "city_time": "10:10 AM",
        },
    )

注意:Event.output 的输出数据量存在限制。

节点仅被允许发出一个信号(或数据)。 Event.output 每次执行时,数据负载(data payload)的容量是有限的。这一限制意味着:虽然你可以使用多个(data payloads),但每个数据负载的容量仍然不能超过规定的上限。 `yield` 在一个节点中,包含两个或更多的元素(或部分)。 `yield` 带有……的命令 Event.output 这会导致运行时错误(runtime error)。

The output 该字段不仅限于文本格式;任何可序列化的值都可以被传递给下一个节点。下一个节点会将该值作为类型化的对象接收,而无需进行 JSON 解析或读取任何状态信息。 outputSchema 发送到生产节点(producing node),或者一个…… inputSchema 该信息会被发送到消费节点(即执行合约的节点),从而使合约的内容变得明确无误,并在运行时对其进行验证(即确保合约按照预期的方式执行)。

import { createEvent, node, NodeContext, Workflow } from '@google/adk';
import { z } from 'zod';

const cityInfoSchema = z.object({
  cityName: z.string(),
  cityTime: z.string(),
});
type CityInfo = z.infer<typeof cityInfoSchema>;

const emitStructuredOutput = node(
  async function* () {
    yield createEvent({
      output: { cityName: 'Paris', cityTime: '10:10 AM' } satisfies CityInfo,
    });
  },
  { name: 'emit_structured_output', outputSchema: cityInfoSchema },
);

const consumeStructuredOutput = node(
  (_ctx: NodeContext, cityInfo: CityInfo) =>
    `It is ${cityInfo.cityTime} in ${cityInfo.cityName} right now.`,
  { name: 'consume_structured_output', inputSchema: cityInfoSchema },
);

export const rootAgent = new Workflow({
  name: 'structured_output_workflow',
  edges: [['START', emitStructuredOutput, consumeStructuredOutput]],
});

`workflow` 包: a FunctionNode 可以返回任何能够被 JSON 序列化的 Go 结构体(struct)。该框架会将该结构体序列化为 JSON 格式。 Event.Output 然后将其反序列化为后续节点的类型化数据(即将其转换回适合后续节点处理的数据格式)。 input 该参数没有关于数据载荷类型的限制;每个节点都恰好返回一个具有明确数据类型的值。

// newStructuredOutputPipeline shows how to pass a struct from one FunctionNode
// to another. The framework serialises the return value into event.Output and
// deserialises it back into the successor's typed input parameter.
//
// This is the Go equivalent of:
//
//  class CityTime(BaseModel):
//      time_info: str
//      city: str
//
//  def lookup_time_function(city: str):
//      return Event(output=CityTime(time_info="10:10 AM", city=city))
//
//  def city_report(node_input: CityTime):
//      return Event(output=f"It is {node_input.time_info} in {node_input.city}.")
type CityTime struct {
    TimeInfo string `json:"time_info"`
    City     string `json:"city"`
}

func newStructuredOutputPipeline(ctx context.Context, geminiModel model.LLM) (agent.Agent, error) {
    lookupTimeFn := func(_ agent.Context, city string) (CityTime, error) {
        // Simulate looking up the current time in the city.
        return CityTime{TimeInfo: "10:10 AM", City: city}, nil
    }

    cityReportAgent, err := llmagent.New(llmagent.Config{
        Name:        "city_report_agent",
        Model:       geminiModel,
        Description: "Reports the city and current time from the previous node's output.",
        // When wrapped as an AgentNode, the predecessor's event.Output
        // is delivered as the agent's user content. The {key} template
        // syntax is not required — the struct fields are provided inline.
        Instruction: "Report the city time information you received in a friendly sentence.",
    })
    if err != nil {
        return nil, fmt.Errorf("cityReportAgent: %w", err)
    }

    lookupTimeNode := workflow.NewFunctionNode("lookup_time", lookupTimeFn, workflow.NodeConfig{})
    cityReportNode, err := workflow.NewAgentNode(cityReportAgent, workflow.NodeConfig{})
    if err != nil {
        return nil, fmt.Errorf("NewAgentNode: %w", err)
    }

    return workflowagent.New(workflowagent.Config{
        Name:      "city_time_pipeline",
        Edges:     workflow.Chain(workflow.Start, lookupTimeNode, cityReportNode),
        SubAgents: []agent.Agent{cityReportAgent},
    })
}

预先构建的工作流代理(Prebuilt workflow agents):可以使用多个(选项或方法) OutputKey 每个代理都有一个对应的值(value),用于存储会话状态中的各个字段。下游代理可以通过各自的机制独立地读取每个字段。 {key} 在他们的……中;属于他们的…… Instruction.

路由输出(Routing output)

使用 route 某个对象的参数 事件 用于驱动条件性边缘处理(conditional edge processing); 调度(dispatch):

def router(node_input: str):
    return Event(route="BUG")

The route 该值是独立的(即其取值不受其他因素的影响)。 output因此,一个事件可以同时完成以下两件事:选择某个分支(branch),并将数据(payload)发送到该分支。 DEFAULT_ROUTE `setting` 会捕获任何其他分支都没有匹配到的值。

import {
  createEvent,
  DEFAULT_ROUTE,
  node,
  NodeContext,
  Workflow,
} from '@google/adk';

const router = node(
  (_ctx: NodeContext, nodeInput: string) =>
    createEvent({
      route: /bug|crash|error/i.test(nodeInput) ? 'BUG' : 'OTHER',
      output: nodeInput,
    }),
  { name: 'router' },
);

const handleBug = node(
  (_ctx: NodeContext, nodeInput: string) => `Filed a bug for: ${nodeInput}`,
  { name: 'handle_bug' },
);

const handleAnythingElse = node(
  (_ctx: NodeContext, nodeInput: string) => `No bug detected in: ${nodeInput}`,
  { name: 'handle_anything_else' },
);

export const rootAgent = new Workflow({
  name: 'routing_output_workflow',
  edges: [
    ['START', router],
    [
      router,
      {
        BUG: handleBug,
        [DEFAULT_ROUTE]: handleAnythingElse,
      },
    ],
  ],
});

`workflow` 包:一个会释放某种物质(或能量)的装置/物体 FunctionNode 构建一个 session.Event 直接设置(相关值)。 Event.Routes 将数据发送到所需的路由键(route keys)处,并进行相应的设置(sets)。 Event.Output 需要将数据(即“payload”)转发给后续的处理者(即“successor”)。工作流引擎(workflow engine)会读取相关的数据并进行处理。 Event.Routes 在调度时,选择与需求相匹配的边(即:在系统开始执行任务时,选择能够满足特定条件的边)。

// classifyAndRoute shows how to set event.Routes alongside event.Output from
// an emitting FunctionNode. The function constructs a session.Event directly,
// sets Routes to select the conditional edge, and sets Output to forward the
// payload to the successor node.
//
// This mirrors the Python pattern:
//
//  def router(node_input: str):
//      return Event(route="BUG")
func classifyAndRoute(ctx agent.Context, msg string, emit func(*session.Event) error) (any, error) {
    category := classifyMessage(msg)

    ev := session.NewEvent(ctx, ctx.InvocationID())
    ev.Routes = []string{category} // drives edge dispatch
    ev.Output = msg                // forwarded as typed input to the successor
    if err := emit(ev); err != nil {
        return nil, err
    }
    return nil, nil // nil suppresses the automatic terminal event
}

func classifyMessage(msg string) string {
    switch {
    case strings.Contains(strings.ToLower(msg), "bug"):
        return "BUG"
    case strings.Contains(strings.ToLower(msg), "help"):
        return "CUSTOMER_SUPPORT"
    default:
        return "LOGISTICS"
    }
}

func newRoutingPipeline() (agent.Agent, error) {
    classifyNode := workflow.NewEmittingFunctionNode("classify", classifyAndRoute, workflow.NodeConfig{})

    bugHandler := workflow.NewFunctionNode("bug_handler",
        func(_ agent.Context, msg string) (string, error) {
            return "Handling bug: " + msg, nil
        }, workflow.NodeConfig{})

    supportHandler := workflow.NewFunctionNode("support_handler",
        func(_ agent.Context, msg string) (string, error) {
            return "Handling support: " + msg, nil
        }, workflow.NodeConfig{})

    logisticsHandler := workflow.NewFunctionNode("logistics_handler",
        func(_ agent.Context, msg string) (string, error) {
            return "Handling logistics: " + msg, nil
        }, workflow.NodeConfig{})

    edges := workflow.Concat(
        workflow.Chain(workflow.Start, 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")},
        },
    )
    return workflowagent.New(workflowagent.Config{
        Name:        "routing_pipeline",
        Description: "Classifies and routes a message using Event.Routes.",
        Edges:       edges,
    })
}

面向用户的消息

使用 message 某个对象的参数 事件 目的是向用户发送响应,而不是将数据传递给下一个处理节点。

async def user_message(node_input: str):
  """Tell user research process is starting."""
  yield Event(message="Beginning research process...")

一条发送给用户的消息属于该事件的(相关内容/信息)。 content `field`:运行时(runtime)会对其进行渲染(renders)。 content但是,该图并不会将数据传递给下一个节点。请使用(相应的方法或工具)来处理这个问题。 content 为了用户…… output 对于下一个节点来说,一个节点可以通过发送两个事件来“发出”某些信息;其中只有一个事件会包含实际需要传递的数据。 output:

import { createEvent, node, NodeContext, Workflow } from '@google/adk';

/** Emits a user-facing message: `content`, with no `output`. */
const message = (text: string) =>
  createEvent({ content: { role: 'model', parts: [{ text }] } });

const userMessage = node(
  async function* (_ctx: NodeContext, nodeInput: string) {
    yield message(`Beginning research process for "${nodeInput}"...`);
  },
  { name: 'user_message' },
);

const research = node(
  async function* (_ctx: NodeContext) {
    yield message('Gathering sources...');
    yield createEvent({ output: ['source-a', 'source-b', 'source-c'] });
  },
  { name: 'research' },
);

const report = node(
  (_ctx: NodeContext, sources: string[]) =>
    `Research complete. ${sources.length} sources: ${sources.join(', ')}.`,
  { name: 'report' },
);

export const rootAgent = new Workflow({
  name: 'user_message_workflow',
  edges: [['START', userMessage, research, report]],
});

`workflow` 包:要显示一条对用户可见的消息,同时不推进节点的已输入内容(即不显示节点已输入的文本),请设置…… Event.Content 在某个中间事件(intermediate event)发生时;该事件是通过某种方式(via the …)被触发的/发出的。 emit 回调函数(callback function)在……中 EmittingFunctionNode终端的返回值(或 nil) 控制功能 Event.Output.

预先构建的工作流代理(Prebuilt workflow agents):任意 llmagent `step` 会自动将其模型生成的响应作为面向用户的事件(user-facing event)进行输出。对于非大型语言模型(LLM)相关的步骤,需要编写自定义代码来实现相应的逻辑。 Run `function on an` agent.Agent 这会产生一些事件(events),这些事件的特性(properties)是……(“whose”后面应该接描述事件特性的内容)。 LLMResponse.Content 该内容包含指定的文本。

会话状态(Session state)及状态作用域(State scopes)

会话状态(Session state)能够在会话期间的不同阶段(turns)中持续保存数据。它是预构建的工作流代理(prebuilt workflow agents)之间进行数据共享的主要机制;无论你使用哪种代理类型,该机制同样也适用于各种工具(tools)和回调函数(callbacks)中。

使用 状态 某个对象的参数 事件 为了在各个节点之间保持数据的一致性(即确保所有节点上的数据值都是相同的),需要采取相应的措施。虽然节点可以修改自身的状态值,但这些被修改后的状态值也会被下游节点所获取。

async def init_state_node(attempts: int = 0):
  yield Event(
      state={
          "attempts": attempts,
      },
  )

async def task_attempt_node(node_input, attempts: int):
  yield Event(
      state={
          "attempts": attempts + 1,
      },
  )

async def read_state_node(ctx: Context):
  print(f"attempts state: {ctx.state['attempts']}") # attempts state: 1

root_agent = Workflow(
    name="root_agent",
    edges=[("START", init_state_node, task_attempt_node, read_state_node)],
)

注意: state 属性数据的限制(Property Data Limitations)

`state` 参数 不应被用于存储大量数据。 在各个节点之间传输数据时,可以使用工件(artifacts)或其他数据持久化机制(如数据库工具)来确保大型数据资源在整个工作流(Workflow)的生命周期内得到妥善保存。

通过某种方式将状态信息写入(或传输到)目标系统/设备中。 ctx.state 与其返回该数据,不如直接将其写入磁盘。这种写入操作对同一运行过程中的所有后续节点都是可见的,并且会与写入操作的节点所发生的其他事件一起被持久化(即被存储到磁盘中)。

import { node, NodeContext, Workflow } from '@google/adk';

const initStateNode = node(
  (ctx: NodeContext, nodeInput: string) => {
    ctx.state.set('topic', nodeInput.trim());
    ctx.state.set('temp:started_at', new Date().toISOString());
    ctx.state.set('attempts', 0);
  },
  { name: 'init_state_node' },
);

const taskAttemptNode = node(
  (ctx: NodeContext) => {
    const attempts = ctx.state.get<number>('attempts') ?? 0;
    ctx.state.set('attempts', attempts + 1);
  },
  { name: 'task_attempt_node' },
);

const readStateNode = node(
  (ctx: NodeContext) =>
    `attempts state: ${ctx.state.get('attempts')} ` +
    `(topic: ${ctx.state.get('topic')}, ` +
    `started: ${ctx.state.get('temp:started_at')})`,
  { name: 'read_state_node' },
);

export const rootAgent = new Workflow({
  name: 'session_state_workflow',
  edges: [['START', initStateNode, taskAttemptNode, readStateNode]],
});

注意: state 数据限制(data limitations)

会话状态(Session state)是一种轻量级的键值存储机制。请不要使用它来在节点之间传输大量数据(即“大型数据负载”);应改用其他方式(例如专门的传输工具或数据库)。只有当前处理的节点需要某个值时,才需要将该值通过通信渠道(即“边缘”)传递给下一个节点。 output当某个值需要在应用程序运行结束后仍然保持有效(即其生命周期需要超过应用程序的运行时间),或者需要被某个工具、回调函数等读取时,应使用状态管理(state management)机制来存储该值。 {key} 指令模板化(Instruction Templating)。

“State”这个词是用某种特定的方式(或格式)来书写的。 ctx.Session().State().Set(key, value) 并阅读 与……一起 .Get(key). The session 该包定义了一些前缀常量(prefix constants),这些常量的作用范围与 Python 中的 `state` 参数相同。这种设计模式既适用于预先构建的工作流代理(prebuilt workflow agents),也适用于任何类型的代理(agent)中的工具(tools)和回调函数(callbacks)。

// stateScopes shows how session-state key prefixes control the lifetime and
// visibility of stored values. This pattern applies to the prebuilt workflow
// agents (sequentialagent / parallelagent / loopagent) and to tools and
// callbacks. For the workflow package (FunctionNode / AgentNode), prefer
// returning values directly via Event.Output.
//
// Available prefixes:
//
//  session.KeyPrefixApp  ("app:")  – shared across all users and sessions
//  session.KeyPrefixUser ("user:") – tied to the user, shared across sessions
//  session.KeyPrefixTemp ("temp:") – discarded after the current invocation
//
// Keys with no prefix persist for the lifetime of the session.
func stateScopes(ctx agent.Context) error {
    st := ctx.Session().State()

    // Session-scoped (no prefix) — persists for the life of this session.
    if err := st.Set("attempts", 0); err != nil {
        return fmt.Errorf("state.Set attempts: %w", err)
    }

    // App-scoped — shared across all users and sessions for this app.
    if err := st.Set(session.KeyPrefixApp+"global_counter", 42); err != nil {
        return fmt.Errorf("state.Set app:global_counter: %w", err)
    }

    // User-scoped — shared across all sessions belonging to this user.
    if err := st.Set(session.KeyPrefixUser+"login_count", 1); err != nil {
        return fmt.Errorf("state.Set user:login_count: %w", err)
    }

    // Temp-scoped — discarded after this invocation ends.
    if err := st.Set(session.KeyPrefixTemp+"scratch", "ephemeral"); err != nil {
        return fmt.Errorf("state.Set temp:scratch: %w", err)
    }

    return nil
}

注意:州级数据存在某些限制。

会话状态(Session state)是一个轻量级的键值存储系统(key-value store)。请不要使用它来存储大型数据(如文件内容或二进制数据);应改用 ADK 工具(ADK artifacts)或外部存储工具(external storage tools)来处理这类数据。

工作流包(Workflow Package):优先使用 `Event.Output` 而不是 `state`。

对于…… workflow `package (FunctionNode, AgentNode, DynamicNode框架通过返回具有特定数据类型的值来实现节点之间的数据传递。 Event.Output **仅可自动使用。** State().Set 当您需要将某些价值观(或数据)共享给工具、回调函数或代理程序时…… Instruction templates.

使用模式(schemas)来约束节点数据。

您可以设置输入数据和输出数据的结构(即数据模式),以限制任何代理节点所接受和生成的数据格式。

使用 input_schema 和 output_schema 使用一个继承自某个类的类(class)来实现该功能。 BaseModel 为了限制任何代理的输入和输出行为:

from datetime import date

from google.adk import Agent
from pydantic import BaseModel

class FlightSearchInput(BaseModel):
    origin: str           # Airport code "SFO"
    destination: str      # Airport code "CDG"
    departure_date: date  # date(2026, 3, 15)
    passengers: int = 1   # Number of passengers

class Flight(BaseModel):
    carrier: str
    price: float

def search_flights_api(
    origin: str, destination: str, departure_date: date, passengers: int
) -> list[dict]:
    """Look up flights with your own flight-search provider."""
    ...

class FlightSearchOutput(BaseModel):
    flights: list[Flight]
    cheapest_price: float

flight_searcher = Agent(
    name="flight_searcher",
    instruction="Search for available flights.",
    input_schema=FlightSearchInput,
    output_schema=FlightSearchOutput,
    tools=[search_flights_api],
    mode="single_turn",
    ...
)

assistant = Agent(
    name="assistant",
    instruction="You help users plan trips.",
    sub_agents=[flight_searcher],
    ...
)

这些模式(schemas)是 Zod 对象,或者属于 genai 类型。 Schema模式(schema)的位置决定了它的作用(即模式对系统或数据的影响)。

  • The LlmAgent.outputSchema 该选项要求模型必须以指定的形式进行回答。
  • The LlmAgent.inputSchema 该选项仅适用于代理被作为工具(tool)使用时。在图中,可以在节点本身上设置用于验证节点输入数据的模式(schema)。 node(agent, {inputSchema}).

图中的代理程序必须能够正常运行(即:代理程序必须能够成功执行其任务)。 single_turn 模式(mode):这是默认值; 或者(or): task mode.

import {
  FunctionTool,
  LlmAgent,
  node,
  NodeContext,
  Workflow,
} from '@google/adk';
import { z } from 'zod';

const flightSearchInputSchema = z.object({
  origin: z.string().describe('Origin airport code, e.g. "SFO".'),
  destination: z.string().describe('Destination airport code, e.g. "CDG".'),
  departureDate: z.string().describe('Departure date, e.g. "2026-03-15".'),
  passengers: z.number().describe('Number of passengers.'),
});
type FlightSearchInput = z.infer<typeof flightSearchInputSchema>;

const flightSchema = z.object({
  carrier: z.string(),
  flightNumber: z.string(),
  price: z.number(),
});

const flightSearchOutputSchema = z.object({
  flights: z.array(flightSchema),
  cheapestPrice: z.number(),
});
type FlightSearchOutput = z.infer<typeof flightSearchOutputSchema>;

/** Stands in for a real flight-search API. */
const searchFlightsApi = new FunctionTool({
  name: 'search_flights_api',
  description: 'Searches available flights for a route and date.',
  parameters: flightSearchInputSchema,
  execute: ({ origin, destination }) => [
    {
      carrier: 'AF',
      flightNumber: `AF${origin.length}${destination.length}0`,
      price: 812.4,
    },
    {
      carrier: 'UA',
      flightNumber: `UA${origin.length}${destination.length}1`,
      price: 947.0,
    },
  ],
});

const parseRequest = node(
  (_ctx: NodeContext, nodeInput: string): FlightSearchInput => {
    const codes = nodeInput.toUpperCase().match(/\b[A-Z]{3}\b/g) ?? [];
    const date = nodeInput.match(/\d{4}-\d{2}-\d{2}/)?.[0];
    const passengers = Number(
      nodeInput.match(/(\d+)\s*(people|pax|passengers?)/i)?.[1],
    );
    return {
      origin: codes[0] ?? 'SFO',
      destination: codes[1] ?? 'CDG',
      departureDate: date ?? '2026-03-15',
      passengers: Number.isFinite(passengers) ? passengers : 1,
    };
  },
  { name: 'parse_request', outputSchema: flightSearchInputSchema },
);

const flightSearcher = new LlmAgent({
  name: 'flight_searcher',
  model: 'gemini-flash-latest',
  mode: 'single_turn',
  instruction:
    'Search for available flights with the search_flights_api tool and report ' +
    'every flight it returns plus the cheapest price.',
  inputSchema: flightSearchInputSchema,
  outputSchema: flightSearchOutputSchema,
  tools: [searchFlightsApi],
});

const renderResults = node(
  (_ctx: NodeContext, results: FlightSearchOutput) =>
    `Cheapest: $${results.cheapestPrice}\n` +
    results.flights
      .map((f) => `  ${f.carrier} ${f.flightNumber} — $${f.price}`)
      .join('\n'),
  { name: 'render_results', inputSchema: flightSearchOutputSchema },
);

export const rootAgent = new Workflow({
  name: 'flight_workflow',
  edges: [
    [
      'START',
      parseRequest,
      node(flightSearcher, { inputSchema: flightSearchInputSchema }),
      renderResults,
    ],
  ],
});

`workflow` 包: 使用 workflow.NewAgentNodeTyped[Input, Output] 用于将模式(schemas)附加到代理节点(agent node)上。这些通用类型参数(generic type parameters)会被相应地反映(reflected)到系统中。 *jsonschema.Schema 自动完成——无需人工构建数据模型(即无需手动设计数据结构)。 Event.Output 将结构化结果传递给后续处理环节(即“successor”)——完成。 OutputKey 或者需要执行状态写入(state write)操作:

// FlightSearchInput is the typed input schema for the flight-search agent node.
// workflow.NewAgentNodeTyped[FlightSearchInput, FlightSearchOutput] reflects
// these structs into *jsonschema.Schema automatically — no hand-built schema
// construction needed.
type FlightSearchInput struct {
    Origin        string `json:"origin"         jsonschema:"Departure airport code e.g. SFO"`
    Destination   string `json:"destination"    jsonschema:"Arrival airport code e.g. CDG"`
    DepartureDate string `json:"departure_date" jsonschema:"Travel date in YYYY-MM-DD format"`
}

// FlightSearchOutput is the typed output schema for the flight-search agent node.
type FlightSearchOutput struct {
    CheapestPrice string `json:"cheapest_price" jsonschema:"Cheapest available fare e.g. $450"`
    FlightCount   string `json:"flight_count"   jsonschema:"Number of matching flights found"`
}

// newSchemaAgentPipeline demonstrates workflow.NewAgentNodeTyped, which infers
// *jsonschema.Schema from the generic type parameters. This is the Go equivalent
// of Python's:
//
//  flight_searcher = Agent(
//      input_schema=FlightSearchInput,
//      output_schema=FlightSearchOutput,
//      ...
//  )
//
// The node's event.Output carries the structured result to the successor —
// no OutputKey or state write is needed.
func newSchemaAgentPipeline(ctx context.Context, geminiModel model.LLM) (agent.Agent, error) {
    flightSearchAgent, err := llmagent.New(llmagent.Config{
        Name:        "flight_searcher",
        Model:       geminiModel,
        Description: "Searches for available flights and returns structured results.",
        Instruction: `You are a flight-search assistant. Respond ONLY with a JSON object.`,
    })
    if err != nil {
        return nil, fmt.Errorf("flightSearchAgent: %w", err)
    }

    synthAgent, err := llmagent.New(llmagent.Config{
        Name:        "trip_assistant",
        Model:       geminiModel,
        Description: "Summarises flight search results for the user.",
        Instruction: `You help users plan trips. Summarise the flight result you received.`,
    })
    if err != nil {
        return nil, fmt.Errorf("synthAgent: %w", err)
    }

    // NewAgentNodeTyped[In, Out] reflects FlightSearchInput and FlightSearchOutput
    // into *jsonschema.Schema automatically. The node enforces the input schema
    // and constrains the model reply to the output schema's shape.
    flightNode, err := workflow.NewAgentNodeTyped[FlightSearchInput, FlightSearchOutput](flightSearchAgent, workflow.NodeConfig{})
    if err != nil {
        return nil, fmt.Errorf("flightNode: %w", err)
    }

    synthNode, err := workflow.NewAgentNode(synthAgent, workflow.NodeConfig{})
    if err != nil {
        return nil, fmt.Errorf("synthNode: %w", err)
    }

    return workflowagent.New(workflowagent.Config{
        Name:      "flight_booking_pipeline",
        Edges:     workflow.Chain(workflow.Start, flightNode, synthNode),
        SubAgents: []agent.Agent{flightSearchAgent, synthAgent},
    })
}

函数节点和动态节点无法根据其类型参数自动推断出数据结构(即 JSON 模式)。若需验证这些节点的输入数据是否符合 JSON 模式,请使用相应的工具或方法进行验证。 WithSchema 它们构造函数的多种变体(例如: workflow.NewFunctionNodeWithSchema.

预先构建的工作流代理(Prebuilt workflow agents): set InputSchema 和 OutputSchema 在……的时候;当……发生时 llmagent.Config. The OutputSchema 该字段会强制模型返回一个符合指定模式的 JSON 对象。请使用该字段来设置模型的响应内容。 OutputKey 为了保存该 JSON 字符串; 以便下游代理能够引用该字符串。 {key} 在他们的……中;属于他们的…… Instruction.

在代理程序中访问结构化数据

使用 input_schema 该数据会被发送到一个代理(agent)那里,由该代理验证前一个节点生成的结构化输出数据,并将其作为自身的输入数据进行处理。请根据指令中的说明,按名称来引用该输入数据中的各个字段。

class CityTime(BaseModel):
    time_info: str  # time information
    city: str       # city name

def lookup_time_function(node_input: str):
    """Simulate returning the current time in the specified city."""
    return Event(output=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="""
        You receive a CityTime with time_info and city fields. Reply with a
        single sentence stating that it is that time in that city right now.
    """,
)

root_agent = Workflow(
    name="root_agent",
    edges=[
        ("START", city_generator_agent, lookup_time_function, city_report_agent)
    ],
)

大括号({ }) {key} 这些占位符(placeholders)用于…… instruction “supports”会被替换掉。 会话状态(session state)这些数据并非来自节点的输入,因此需要使用一个占位符(例如……)来表示这些数据。 {CityTime.time_info} 提示中的内容被原封不动地保留了下来。 要将某个值嵌入到指令中,首先需要将该值写入相应的状态(state)中。 output_key 或者 Event(state=...)...并将其引用为 {time_info}.

在代理指令中,提供了两种数据选择形式:

  • The {Class.field} 该表单从这个节点的输入数据中读取一个字段的值。
  • The <Class.field from source_node> 该表单从一个名为 “predecessor” 的节点的输出中读取某个字段的数据。当多个上游节点使用相同的字段名称时,请使用此表单。

这两种形式都是不同的(即它们彼此之间存在明显的区别)。 {state_key}该代码用于读取会话状态(session state)。 Class. 前缀仅用于文档说明;实际解析过程中会使用点号后的字段名称。

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 the specified city. */
const lookupTimeFunction = node(
  (_ctx: NodeContext, city: string): CityTime => ({
    timeInfo: '10:10 AM',
    city: city.trim(),
  }),
  { name: 'lookup_time_function', outputSchema: cityTimeSchema },
);

const cityReportAgent = new LlmAgent({
  name: 'city_report_agent',
  model: 'gemini-flash-latest',
  instruction:
    'Return a sentence in the following format: It is ' +
    '<CityTime.timeInfo from lookup_time_function> in ' +
    '<CityTime.city from lookup_time_function> right now.',
});

export const rootAgent = new Workflow({
  name: 'root_agent',
  edges: [
    [
      'START',
      cityGeneratorAgent,
      lookupTimeFunction,
      node(cityReportAgent, { inputSchema: cityTimeSchema }),
    ],
  ],
});

在 ADK Go v2.0.0 中, FunctionNode 返回一个类型化的结构体(typed struct),然后框架(framework)会将其序列化(serialize)成相应的格式。 Event.Output. 后继者 AgentNode 该系统接收该结构体作为用户提供的内容;这些结构体中的字段可供代理程序使用。 Instruction 没有任何;完全不 {key} 模板语法。这直接对应于 Python 的语法。 input_schema=CityTime:这两种语言都是一样的。 结构体中的字段是以类型化的数据形式提供的,而不是通过名称从状态(state)中检索出来的。

// newStructuredOutputPipeline shows how to pass a struct from one FunctionNode
// to another. The framework serialises the return value into event.Output and
// deserialises it back into the successor's typed input parameter.
//
// This is the Go equivalent of:
//
//  class CityTime(BaseModel):
//      time_info: str
//      city: str
//
//  def lookup_time_function(city: str):
//      return Event(output=CityTime(time_info="10:10 AM", city=city))
//
//  def city_report(node_input: CityTime):
//      return Event(output=f"It is {node_input.time_info} in {node_input.city}.")
type CityTime struct {
    TimeInfo string `json:"time_info"`
    City     string `json:"city"`
}

func newStructuredOutputPipeline(ctx context.Context, geminiModel model.LLM) (agent.Agent, error) {
    lookupTimeFn := func(_ agent.Context, city string) (CityTime, error) {
        // Simulate looking up the current time in the city.
        return CityTime{TimeInfo: "10:10 AM", City: city}, nil
    }

    cityReportAgent, err := llmagent.New(llmagent.Config{
        Name:        "city_report_agent",
        Model:       geminiModel,
        Description: "Reports the city and current time from the previous node's output.",
        // When wrapped as an AgentNode, the predecessor's event.Output
        // is delivered as the agent's user content. The {key} template
        // syntax is not required — the struct fields are provided inline.
        Instruction: "Report the city time information you received in a friendly sentence.",
    })
    if err != nil {
        return nil, fmt.Errorf("cityReportAgent: %w", err)
    }

    lookupTimeNode := workflow.NewFunctionNode("lookup_time", lookupTimeFn, workflow.NodeConfig{})
    cityReportNode, err := workflow.NewAgentNode(cityReportAgent, workflow.NodeConfig{})
    if err != nil {
        return nil, fmt.Errorf("NewAgentNode: %w", err)
    }

    return workflowagent.New(workflowagent.Config{
        Name:      "city_time_pipeline",
        Edges:     workflow.Chain(workflow.Start, lookupTimeNode, cityReportNode),
        SubAgents: []agent.Agent{cityReportAgent},
    })
}

有关此工作流程的完整示例,请参见…… 基于图的代理工作流程(Graph-based agent workflows).