跳转到内容

用于 ADK 的 Google Cloud Eventarc 工具

在 ADK 中得到支持。Python v2.6.0实验性的(Experimental)

The EventarcToolset 允许代理与……进行交互。 Google Cloud Eventarc 用于异步发布结构化数据(structured data)。 CloudEvents 这些数据会被传输到 Eventarc 消息总线(Eventarc Message Buses)。该工具集提供了内置的连接池(connection pooling)和缓存机制,可以在多次调用过程中重复使用已建立的连接;同时,它既支持通用类型的事件发布(general-purpose event publishing),也支持针对特定领域、且受数据结构(schema)约束的事件处理功能(domain-specific, schema-enforced event processing)。

实验性的(Experimental)

此功能仍处于试验阶段,可能会在未来的版本中得到更新。

先决条件

在使用之前,请先…… EventarcToolset您需要完成以下设置步骤:

  1. 启用 Eventarc API:在您的 Google Cloud 项目中启用 Eventarc 和 Eventarc Publishing API:

    gcloud services enable eventarc.googleapis.com eventarcpublishing.googleapis.com
    
  2. 身份验证与授权请确保运行该代理程序的用户具有必要的身份与访问管理(IAM)权限,以便能够将消息发布到 Eventarc 消息总线中。 roles/eventarc.publisher (角色)。有关 Eventarc IAM 角色的更多信息,请参阅……) Eventarc 访问控制文档. 如需设置本地开发所需的凭据,请参阅 提供应用程序的默认凭据.

  3. 创建一个消息总线(Message Bus)。在您的 Google Cloud 项目中创建一个 Eventarc Advanced Message Bus(目标消息总线),以便接收发布的事件:

    gcloud eventarc message-buses create my-bus \
        --location=us-central1 \
        --logging-config=DEBUG
    
  4. 安装所需的依赖项。:安装 gcp 需要额外的软件包来安装 Google Cloud Eventarc 客户端库。

    pip install "google-adk[gcp]"
    

与代理程序(agent)一起使用。

以下示例展示了如何配置并为一名代理(agent)配备所需的资源/工具。 EventarcToolset 用于发布 CloudEvents:

# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
import os

from google.adk.agents import Agent
from google.adk.integrations.eventarc import EventarcCredentialsConfig
from google.adk.integrations.eventarc import EventarcToolConfig
from google.adk.integrations.eventarc import EventarcToolset
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
import google.auth

# Define constants for this example agent
AGENT_NAME = "eventarc_agent"
APP_NAME = "eventarc_app"
USER_ID = "user1234"
SESSION_ID = "1234"
GEMINI_MODEL = "gemini-flash-latest"

# Define Eventarc tool config.
# You can optionally set the project_id here, or let the agent infer it from context/user input.
tool_config = EventarcToolConfig(project_id=os.getenv("GOOGLE_CLOUD_PROJECT"))

# Uses externally-managed Application Default Credentials (ADC) by default.
# This decouples authentication from the agent / tool lifecycle.
# https://cloud.google.com/docs/authentication/provide-credentials-adc
application_default_credentials, _ = google.auth.default()
credentials_config = EventarcCredentialsConfig(
    credentials=application_default_credentials
)

# Instantiate an Eventarc toolset
eventarc_toolset = EventarcToolset(
    credentials_config=credentials_config, tool_config=tool_config
)

# Agent Definition
root_agent = Agent(
    model=GEMINI_MODEL,
    name=AGENT_NAME,
    description=(
        "Agent to publish structured CloudEvents to Google Cloud Eventarc"
        " Message Buses."
    ),
    instruction="""\
        You are a cloud integration agent with access to Google Cloud Eventarc tools.
        You can publish structured CloudEvents to Eventarc Message Buses using the publish_message tool.
    """,
    tools=[eventarc_toolset],
)

# Session and Runner
session_service = InMemorySessionService()
session = asyncio.run(
    session_service.create_session(
        app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID
    )
)
runner = Runner(
    agent=root_agent, app_name=APP_NAME, session_service=session_service
)


# Agent Interaction
def call_agent(query: str):
  """Helper function to call the agent with a query."""
  content = types.Content(role="user", parts=[types.Part(text=query)])
  events = runner.run(user_id=USER_ID, session_id=SESSION_ID, new_message=content)

  print("USER:", query)
  for event in events:
    if event.is_final_response():
      final_response = event.content.parts[0].text
      print("AGENT:", final_response)


# Example call to publish a CloudEvent
call_agent(
    "Publish an event of type 'com.example.user.signup' to bus"
    " 'projects/my-project/locations/us-central1/messageBuses/my-bus' with data"
    " '{\"user\": \"alice\"}', datacontenttype 'application/json', and source"
    " '//my-service/auth'"
)

工具

The EventarcToolset 默认情况下,该工具包含以下通用发布工具:

publish_message

将结构化的 CloudEvent 发布到 Google Cloud Eventarc 的高级消息总线(Advanced Message Bus)中。

参数 类型 描述
bus str Eventarc Message Bus 的完整资源名称(例如: projects/my-project/locations/us-central1/messageBuses/my-bus).
type str `CloudEvents` 类型标识符用于表示某个事件的发生(例如……) com.example.user.signup).
source str `CloudEvents` 源 URI 用于标识事件发生的上下文(例如: //my-service/auth).
data dict \| str \| Any (可选)要包含在 CloudEvent 中的事件有效载荷数据。
datacontenttype str (可选)该媒体的类型为…… data 例如, application/json)。默认值为 application/json 当提供字典或列表形式的数据时, text/plain 用于处理字符串类型的有效载荷(string payloads)。
subject str (可选)事件的主题,即该事件在事件生产者(event producer)所处的上下文中的含义。
id str (可选)事件的唯一标识符。如果未提供该标识符,系统会自动生成一个 UUID。
time str (可选)事件发生的时间戳,采用 RFC 3339 格式。如果未提供该时间戳,则使用当前的 UTC 时间戳。
specversion str (可选)CloudEvents 规范的版本号。默认值为…… 1.0.
is_base64_encoded bool (可选)是否 data 这是经过 Base64 编码的二进制数据。默认值为…… False.
include_tracing_extension bool (可选)是否自动提取分布式追踪的上下文信息,并将其插入到 CloudEvent 的扩展属性中。默认值为…… False.
custom_attributes dict[str, str] (可选)用于附加到事件中的其他自定义 CloudEvent 扩展属性。

特定于领域的发布工具(Domain-specific publish tools)

在生产环境中的多智能体架构中,允许大型语言模型(LLM)自由地设置路由参数……)bus, type, source这可能会导致用户产生幻觉(即看到虚假的“目的地”),或者导致事件数据的结构发生异常(即事件数据被错误地解析或存储)。 EventarcToolset.create_publish_tool 工厂方法(Factory Method)允许你创建针对特定领域、且遵循严格数据结构的发布工具(publishing tools)。

通过创建一个特定于某个领域的工具,你可以使用该工具来绑定路由相关的属性(即决定数据传输路径的规则或设置)。 CloudEventAttributesBinding 在强制要求事件数据(event payload)遵循严格的 Pydantic 模型规范时……)payload_schema这确保了生成的事件与您的业务领域相关,并且只会被发送到授权的消息总线(message buses)中。

与代理程序(agent)一起使用。

# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
import os
from typing import Any

from google.adk.agents import Agent
from google.adk.integrations.eventarc import AgentProvided
from google.adk.integrations.eventarc import CloudEventAttributesBinding
from google.adk.integrations.eventarc import EventarcCredentialsConfig
from google.adk.integrations.eventarc import EventarcToolConfig
from google.adk.integrations.eventarc import EventarcToolset
from google.adk.integrations.eventarc import OMIT
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
import google.auth
import pydantic

# Define constants for this example agent
AGENT_NAME = "domain_specific_eventarc_agent"
APP_NAME = "eventarc_app"
USER_ID = "user1234"
SESSION_ID = "1234"
GEMINI_MODEL = "gemini-flash-latest"

PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
BUS_NAME = os.getenv("EVENTARC_BUS_NAME", "outreach-bus")
BUS_URI = f"projects/{PROJECT_ID}/locations/us-central1/messageBuses/{BUS_NAME}"


# 1. Define a strictly validated Pydantic schema for the CloudEvent payload
class OutreachContext(pydantic.BaseModel):
  """Structured event payload for a completed customer outreach attempt."""

  customer_id: str = pydantic.Field(
      description="Unique identifier of the customer reached out to."
  )
  resolution_notes: str = pydantic.Field(
      description="Summary notes describing the outcome of the outreach call."
  )
  high_priority: bool = pydantic.Field(
      default=False,
      description="Whether this outreach requires urgent follow-up action.",
  )


# 2. Configure credentials and toolset
tool_config = EventarcToolConfig(project_id=PROJECT_ID)
application_default_credentials, _ = google.auth.default()
credentials_config = EventarcCredentialsConfig(
    credentials=application_default_credentials
)
eventarc_toolset = EventarcToolset(
    credentials_config=credentials_config, tool_config=tool_config
)

# 3. Create Domain-Specific Publish Tools

# Example A: Fully Statically Bound Tool (Safest)
# All routing parameters are locked down by the developer.
# The LLM only provides the structured data matching OutreachContext.
complete_outreach_static_tool = eventarc_toolset.create_publish_tool(
    name="complete_outreach_static",
    description="Logs a completed outreach attempt (statically bound routing).",
    payload_schema=OutreachContext,
    bus=BUS_URI,
    ce_attributes_binding=CloudEventAttributesBinding(
        type="vendor_outreach.completed",
        source="//my-agent/outreach",
        datacontenttype="application/json",
    ),
)

# Example B: Dynamically Bound Tool using AgentProvided and Sentinels
# Allows the LLM to provide the CloudEvent subject, while excluding optional attributes from the event payload.
complete_outreach_dynamic_tool = eventarc_toolset.create_publish_tool(
    name="complete_outreach_dynamic",
    description="Logs an outreach attempt with a dynamically provided subject.",
    payload_schema=OutreachContext,
    bus=BUS_URI,
    ce_attributes_binding=CloudEventAttributesBinding(
        type="vendor_outreach.completed",
        source="//my-agent/outreach",
        subject=AgentProvided("The unique customer ID being reached out to."),
        time=OMIT,
    ),
)


# Example C: Runtime Lambda Binding
# Evaluates attribute values dynamically at execution time from event payload, runtime context, or both.
def resolve_source_from_context(context: Any) -> str:
  """Extracts the source URI dynamically from runtime tool execution context."""
  return f"//my-agent/session/{getattr(context, 'session_id', 'default')}"


complete_outreach_lambda_tool = eventarc_toolset.create_publish_tool(
    name="complete_outreach_lambda",
    description="Logs an outreach attempt using runtime context lambda binding.",
    payload_schema=OutreachContext,
    bus=BUS_URI,
    ce_attributes_binding=CloudEventAttributesBinding(
        type="vendor_outreach.completed",
        source=resolve_source_from_context,
    ),
)

# 4. Equip the agent with the domain-specific tools
root_agent = Agent(
    model=GEMINI_MODEL,
    name=AGENT_NAME,
    description="Agent for recording customer outreach completion events.",
    instruction="""\
        You are a customer outreach agent.
        Use the available outreach tools to record structured outreach events.
    """,
    tools=[
        complete_outreach_static_tool,
        complete_outreach_dynamic_tool,
        complete_outreach_lambda_tool,
    ],
)

# 5. Session and Runner
session_service = InMemorySessionService()
session = asyncio.run(
    session_service.create_session(
        app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID
    )
)
runner = Runner(
    agent=root_agent, app_name=APP_NAME, session_service=session_service
)


def call_agent(query: str):
  """Helper function to call the agent with a query."""
  content = types.Content(role="user", parts=[types.Part(text=query)])
  events = runner.run(user_id=USER_ID, session_id=SESSION_ID, new_message=content)

  print("USER:", query)
  for event in events:
    if event.is_final_response():
      final_response = event.content.parts[0].text
      print("AGENT:", final_response)


# Example invocation
call_agent(
    "We successfully completed an outreach call with CUST-883. "
    "Resolution notes: All issues resolved. Not high priority."
)

参数(用于……) create_publish_tool

The create_publish_tool 该方法仅接受以下以关键字形式提供的参数:

参数 类型 描述
name str 暴露给大型语言模型(LLM)的函数工具名称(例如: complete_outreach_static).
description str 这是一段用自然语言编写的描述,用于指导大型语言模型(LLM)在何时使用该工具以及该工具应执行的具体操作。
bus str \| Callable[[Any], str] \| AgentProvided 目标 Eventarc 消息总线(Eventarc Message Bus)可以是以下几种形式之一: 1. 一个静态的 URI 字符串; 2. 一个在运行时可以根据工具上下文(tool context)进行评估的、可被调用的对象(runtime callable object); 3. ……(此处可补充其他可能的形式)。 AgentProvided 该实例用于提示大型语言模型(LLM)提供所需的信息。
ce_attributes_binding CloudEventAttributesBinding CloudEvent 属性的绑定规则(Binding rules for CloudEvent attributes)type, source, subject, datacontenttype, time, id, specversion, custom_attributes).
payload_schema type[pydantic.BaseModel] \| None (可选)一个用于定义结构化事件负载数据的 Pydantic 模式类。当该类被指定时,工具的使用方式(即工具的接口或行为)将受到相应限制。 event_data 该参数需符合此模型要求。如果未提供(或……) None), no event_data 该参数被添加到工具的签名中,工具会发布一个仅包含通知内容的 CloudEvent(即不包含任何数据内容的事件),而不会附带数据 payload。

CloudEvent 属性绑定(Attribute Bindings)与监控机制(Sentinels)

The CloudEventAttributesBinding `dataclass` 指定了如何填充各个 `CloudEvent` 字段的值。每个属性(……)type, source, datacontenttype, subject, time, id, specversion, custom_attributes可以为其分配以下绑定机制中的一种:

绑定类型(Binding Type) 示例: 暴露于大型语言模型(LLM)的环境中 描述
静态字符串(Static String) type="vendor_outreach.completed" 没有。 该属性强制使用一个固定的字符串值。该属性对大型语言模型(LLM)的接口签名是不可见的,并会在每次调用时自动被应用。
运行时 Lambda(Runtime Lambda) source=lambda ctx: f"//agent/{ctx.session_id}" 没有。 一个可调用的对象(callable object)……Callable[[Any], str]这些内容会在执行时根据事件数据(event payload)、运行时环境(runtime context)或两者的信息动态计算得出。它们对大型语言模型(LLM)的“签名”(signature)是不可见的(即:这些计算结果不会被包含在大型语言模型的“签名”中)。
AgentProvided subject=AgentProvided("Customer ID") 是的 该指令要求 ADK 将该属性作为显式参数包含在函数签名中,以便大型语言模型(LLM)能够获取该属性的值。接受一个输入参数(Input Parameter)。 description string.
MISSING time=MISSING 没有。 可选属性的默认“哨兵”(即默认行为指示器)。表示适用默认行为(例如,自动生成当前的 UTC 时间戳)。 time 或者是一个 UUID(Universally Unique Identifier,通用唯一标识符)。 id).
OMIT time=OMIT 没有。 明确地将某个可选属性从生成的 CloudEvent 中排除掉。强制性的属性(……)type, source, bus, id, specversion)无法被设置为 OMIT.

示例:理解(Example: Understanding) MISSING (用于表示对比或对立关系)与……相对;对抗…… OMIT

要理解……之间的区别 MISSING 和 OMIT请考虑这些因素如何影响一个可选的 CloudEvent 属性(例如……)。 time:

  • time=MISSING (默认行为):当您进行设置时…… time=MISSING (或保持原样) time 如果未指定任何参数(即使用默认值),该工具集会应用其内置的默认行为。 time它会自动生成并以 RFC 3339 格式显示当前的 UTC 时间戳(例如:`2021-01-01T12:34:56.7890Z`)。 "time": "2026-07-31T20:20:00Z").
  • time=OMIT:当您明确进行设置时 time=OMIT,the time 该字段已被完全从发布的 CloudEvent 数据负载中删除。请使用(相应的功能或方法)来处理这种情况。 OMIT 当下游事件消费者不需要或不期望某些可选属性时(即这些属性是可选的,但消费者并不强制要求必须提供)。
from google.adk.integrations.eventarc import (
    CloudEventAttributesBinding,
    MISSING,
    OMIT,
)

# 1. Using MISSING (default): CloudEvent automatically includes the current UTC timestamp
binding_with_timestamp = CloudEventAttributesBinding(
    type="vendor_outreach.completed",
    source="//my-agent/outreach",
    time=MISSING,  # Results in "time": "2026-07-31T20:20:00Z"
)

# 2. Using OMIT: CloudEvent will NOT include a 'time' attribute
binding_without_timestamp = CloudEventAttributesBinding(
    type="vendor_outreach.completed",
    source="//my-agent/outreach",
    time=OMIT,  # The 'time' field is excluded from the published event
)

其他资源