跳转到内容

适用于 Android Development Kit (ADK) 的 Google Cloud Trace 可观测性功能

在 ADK 中得到支持。PythonTypeScriptGo

在本地开发过程中,您可以使用相关工具来检查代理程序(agent)的行为。 在 ADK Web UI 中的跟踪视图(Trace View)一旦您的代理被部署到位,您就需要一种方法来集中查看来自实际网络流量的数据(即“trace”信息)。

Cloud Trace Cloud Trace 是 Google Cloud Observability 平台中的分布式追踪组件。它负责收集并可视化追踪数据,帮助您监控应用程序的延迟情况、排查错误以及提升整体性能。对于 ADK(Android Development Kit)代理而言,Cloud Trace 能详细记录每个请求在模型调用、工具执行以及代理操作过程中的具体流程,从而帮助您准确识别生产环境中的性能瓶颈和错误所在。

概述

Cloud Trace 是基于……(此处应填写 Cloud Trace 的技术基础或开发框架)构建的。 OpenTelemetry这是一个开源标准,支持多种编程语言和数据采集方式,用于生成跟踪数据(trace data)。这一标准符合 ADK(Application Development Kit)应用程序的可观测性(observability)最佳实践;ADK 应用程序同样采用了与 OpenTelemetry 兼容的监控工具(instrumentation),从而让您能够:

  • 跟踪代理之间的交互(即代理之间的通信或数据交换行为)Cloud Trace 会持续收集并分析您项目中的跟踪数据,帮助您快速诊断 ADK 应用程序中存在的延迟问题及错误。这种自动数据收集功能简化了在复杂的应用程序工作流程中识别问题的过程。
  • 调试问题通过分析详细的日志记录(trace),可以快速诊断延迟问题及错误。这些日志记录对于理解那些表现为不同服务之间通信延迟增加的问题,或者在特定代理操作(如工具调用)期间出现的问题,至关重要。
  • 深入分析与可视化:Trace Explorer 是用于分析跟踪数据(traces)的主要工具,它提供了多种可视化辅助工具,例如用于显示任务执行时间(span duration)的热图(heatmaps),以及用于显示任务执行频率(span rates)的折线图(line charts)。该工具还提供了一个可以按服务(service)和操作(operation)进行分类的跟踪数据表(spans table),用户可以通过单击即可查看具有代表性的跟踪数据;同时,它还提供了“瀑布图”(waterfall view)功能,帮助用户轻松识别代理执行路径中的瓶颈和错误来源。

以下示例将假设代理目录结构如下:

working_dir/
├── weather_agent/
│   ├── agent.py
│   └── __init__.py
└── deploy_agent_engine.py
└── deploy_fast_api_app.py
└── agent_runner.py
# weather_agent/agent.py

import os
from google.adk.agents import Agent

os.environ.setdefault("GOOGLE_CLOUD_PROJECT", "{your-project-id}")
os.environ.setdefault("GOOGLE_CLOUD_LOCATION", "global")
os.environ.setdefault("GOOGLE_GENAI_USE_ENTERPRISE", "True")


# Define a tool function
def get_weather(city: str) -> dict:
    """Retrieves the current weather report for a specified city.

    Args:
        city (str): The name of the city for which to retrieve the weather report.

    Returns:
        dict: status and result or error msg.
    """
    if city.lower() == "new york":
        return {
            "status": "success",
            "report": (
                "The weather in New York is sunny with a temperature of 25 degrees"
                " Celsius (77 degrees Fahrenheit)."
            ),
        }
    else:
        return {
            "status": "error",
            "error_message": f"Weather information for '{city}' is not available.",
        }


# Create an agent with tools
root_agent = Agent(
    name="weather_agent",
    model="gemini-flash-latest",
    description="Agent to answer questions using weather tools.",
    instruction="You must use the available tools to find an answer.",
    tools=[get_weather],
)

Cloud Trace 的设置

使用 ADK CLI

您可以通过在部署或运行代理时使用 ADK CLI 添加一个标志来启用云追踪功能。

在使用以下方法部署您的代理时: adk deploy command:

adk deploy agent_engine \
    --project=$GOOGLE_CLOUD_PROJECT \
    --region=$GOOGLE_CLOUD_LOCATION \
    --otel_to_cloud \
    $AGENT_PATH

在运行使用 ADK Go 启动器构建的代理程序时:

adkgo web -otel_to_cloud

程序化设置(Programmatic setup)

使用 ADK 应用程序抽象层(Application Abstractions)。

如果您正在使用 Agent Platform SDK…… AdkApp 对于抽象概念(即那些难以直接理解或实现的概念),你可以通过添加相应的代码来实现云追踪(cloud tracing)功能。 enable_tracing=True:

from vertexai.agent_engines import AdkApp

adk_app = AdkApp(
    agent=root_agent,
    enable_tracing=True,
)

使用遥测模块(Telemetry Modules)。

对于完全定制的代理运行时环境,您可以通过使用内置的遥测模块来启用云追踪功能。

from google.adk.telemetry import google_cloud
from google.adk.telemetry.setup import maybe_set_otel_providers

# Get GCP exporters configuration
hooks = google_cloud.get_gcp_exporters(enable_cloud_tracing=True)

# Initialize and set global OTel providers
maybe_set_otel_providers(otel_hooks_to_setup=[hooks])
import { getGcpExporters, maybeSetOtelProviders } from '@google/adk';

// Get GCP exporters configuration
const gcpExporters = await getGcpExporters({
  enableTracing: true,
});

// Initialize and set global OTel providers
maybeSetOtelProviders([gcpExporters]);

// ... your agent code ...
import (
    "context"
    "log"
    "time"

    "google.golang.org/adk/v2/telemetry"
)

func main() {
    ctx := context.Background()

    // Initialize telemetry with cloud export enabled.
    // By default, the GCP project ID is read from the GOOGLE_CLOUD_PROJECT environment variable.
    // You can also specify it explicitly using telemetry.WithGcpResourceProject("my-project").
    telemetryProviders, err := telemetry.New(ctx,
        telemetry.WithOtelToCloud(true),
        // telemetry.WithGcpResourceProject("your-project-id"),
    )
    if err != nil {
        log.Fatalf("failed to initialize telemetry: %v", err)
    }
    defer func() {
        shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
        defer cancel()
        if err := telemetryProviders.Shutdown(shutdownCtx); err != nil {
            log.Printf("failed to shutdown telemetry: %v", err)
        }
    }()

    // Register as global OTel providers
    telemetryProviders.SetGlobalOtelProviders()

    // ... your agent code ...
}

检查 Cloud Trace 数据

设置完成后,每当您与代理进行交互时,代理都会自动将跟踪数据发送到 Cloud Trace。您可以通过访问相应的界面来查看这些跟踪数据。 跟踪浏览器(Trace Explorer) 在……里面;在……期间 Google Cloud 控制台(Console).

cloud-trace

您将看到由 ADK 代理生成的所有可用跟踪记录(trace),这些记录都带有相应的“span 名称”(span name)。 invoke_agent, generate_content, call_llm,以及 execute_tool.

cloud-trace

如果您点击其中一条记录(trace),将会看到该详细处理过程的“瀑布图”显示效果,这种显示方式与本地 ADK Web UI 中的记录视图类似。

cloud-trace

被捕获的属性(Captured attributes)

代理开发工具包(Agent Development Kit,简称 ADK)为日志数据(traces)添加了遥测(telemetry)属性,从而帮助您过滤、监控和分析代理程序(agents)的行为。

属性 描述
gen_ai.agent.name 正在执行的代理的名称。
gcp.vertex.agent.invocation_id 调用的唯一标识符。
gcp.vertex.agent.event_id 特定事件的 ID。
gen_ai.conversation.id 会话或对话的 ID。
gcp.vertex.agent.session_id 与代理调用上下文相关联的会话 ID。
gcp.vertex.agent.llm_request 已序列化的 LLM 请求,其中包含提示文本(prompt text)和配置信息(configuration)。
gcp.vertex.agent.llm_response 序列化的 LLM(大型语言模型)响应,其中包含了模型的输出结果。
gcp.vertex.agent.tool_call_args 传递给工具调用的序列化参数。
gcp.vertex.agent.tool_response 工具返回的序列化结果。
gcp.vertex.agent.data 序列化后的数据负载被发送给代理(agent)。

数据隐私与数据内容的加密处理(即对数据内容进行加密,以防止未经授权的访问或泄露)

为防止在生产环境中泄露敏感数据和个人身份信息(PII),请采取以下措施:

  • 部署默认设置: 在部署时(使用……方法): adk deploy agent_engine --otel_to_cloudADK 会自动进行相关设置。 ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS='false' 除非该内容已经在其他地方被定义过了。 .env 对于 Cloud Run 或 GKE 等其他目标环境,需要显式设置该变量。
  • 被屏蔽的负载数据(Redacted payloads): 当……的时候 ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS 是 'false' 或者 '0'负载属性(payload attributes)gcp.vertex.agent.llm_request, gcp.vertex.agent.llm_response, gcp.vertex.agent.tool_call_args, gcp.vertex.agent.tool_response,以及 gcp.vertex.agent.data)会被替换为占位符值,例如 "{}" 或者 "N/A".
  • 启用捕获功能: 为了捕获完整的负载数据以用于本地测试或调试,请显式地进行设置。 ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS='true' 在你的…… .env 文件或环境变量。
  • OpenTelemetry 消息捕获功能: `Set` OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT='true' (或 '1')以在 OpenTelemetry 事件中记录提示信息(prompt)和响应内容(response content)。

资源

要了解更多关于跟踪(tracing)、OpenTelemetry 以及与 Google Cloud 的集成信息,请查阅以下文档: