在智能体开发套件中管理外部服务的 Secret

智能体开发套件 (ADK) 智能体可与 Google Cloud之外的外部服务互动。代理身份和 Identity and Access Management (IAM) 均可让您通过 Google Cloud服务进行身份验证。不过,他们无法向不支持 Google 身份联合的外部平台证明自己的身份。

ADK 智能体需要访问各种凭据才能与外部实体(例如 MCP 服务、ADK 工具和 API)进行交互。常见示例包括:

  • 支付处理平台的 API 密钥
  • 旧版本地数据库的用户名和密码组合
  • 双向 TLS (mTLS) 连接的私钥
为了支持这些用例,ADK 在 google.adk.integrations.secret_manager.secret_client 软件包中提供了 SecretManagerClient 模块。此模块提供了一个标准接口,供代理在运行时从 Secret Manager 中检索 Secret。 本文档介绍了如何使用 Secret Manager 在 ADK 中管理外部服务的 Secret。

将 Secret Manager 与 ADK 搭配使用的优势

手动管理密钥可能会带来安全风险,并增加开发者的工作量。Secret Manager 可通过以下方式帮助解决这些问题:

  • 如果您将 Secret 嵌入代理代码中,就会带来严重的安全风险。这种做法可能会导致未经授权访问生产系统。使用 Secret Manager 可从源代码中移除敏感数据。这有助于提高应用的安全性。
  • 如果您通过环境变量嵌入静态 Secret,凭据轮换会变得很复杂。如需应用更新,您必须重启部署容器。 Secret Manager 会在运行时动态检索凭据,从而允许在不发生系统停机的情况下进行更新。
  • 如果您为每个工具编写自定义 SecretManagerServiceClient 样板代码,则会增加开发者的工作量和出错风险。标准化的 ADK 集成提供了一种简洁且可重复使用的方法来检索凭据。

准备工作

在将 Secret Manager 与 ADK 集成之前,请完成以下操作:

  1. 使用 ADK 设置智能体。此功能需要使用 ADK 1.29 版或更高版本(适用于 Python)。
  2. 向代理身份授予 Secret Manager Secret Accessor IAM 角色。此角色允许您的代理在运行时检索密钥。
  3. 在 Secret Manager 中创建 Secret 并添加 Secret 版本(例如 API 密钥)。

ADK 智能体如何在运行时检索 Secret

secret_client.SecretManagerClient 模块会在运行时将凭据检索到 Python 代理代码逻辑中。智能体编排逻辑会向大语言模型 (LLM) 发送提示,以决定要执行哪个工具,但系统不会将密钥发送给 LLM。

在运行时阶段,代理会执行以下步骤:

  1. 在 ADK 代理调用第三方工具之前,该代理会初始化 SecretManagerClient 模块并调用 get_secret() 函数。
  2. ADK 代理使用代理身份向 Secret Manager 进行身份验证。
  3. SecretManagerClient 模块将明文密钥返回给 ADK 代理。
  4. ADK 代理使用该 Secret 向第三方工具进行经过身份验证的调用。

在运行时检索 ADK 代理中的 Secret

以下代码示例展示了如何在 ADK 代理中使用 SecretManagerClient 模块安全地检索密钥。代理会在内部检索密钥,以防止向 LLM 的上下文窗口或对话历史记录泄露敏感凭据。

Python

如需运行此代码,请先设置 Python 开发环境并安装 Secret Manager Python SDK。 在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证。

#!/usr/bin/env python

# 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
"""
ADK agent for accessing secrets from global Secret Manager.
"""

import os

from google.adk import Agent
from google.adk.integrations.secret_manager.secret_client import SecretManagerClient

# Fetch secret from global Secret Manager
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
secret_id = os.environ.get("ADK_TEST_SECRET_ID")
secret_version = os.environ.get("ADK_TEST_SECRET_VERSION", "latest")

if not project_id or not secret_id:
    raise ValueError("GOOGLE_CLOUD_PROJECT and ADK_TEST_SECRET_ID environment variables must be set.")

resource_name = f"projects/{project_id}/secrets/{secret_id}/versions/{secret_version}"

print("Fetching secret from global Secret Manager...")
# Initialize Secret Manager Client (Global)
client = SecretManagerClient()

# Fetch secret
try:
    secret_payload = client.get_secret(resource_name)
    print("Successfully fetched secret.")
    # The secret_payload can now be used by the agent or its tools as required.
except Exception as e:
    print(f"Error fetching secret: {e}")
    raise e

# Initialize Agent
root_agent = Agent(
    model='gemini-2.5-flash',
    name='root_agent',
    description='A helpful assistant for user questions.',
    instruction='Answer user questions to the best of your knowledge',
)

print("Agent initialized successfully.")

后续步骤