在 Agent Development Kit 中管理外部服務的密鑰

Agent Development Kit (ADK) 代理會與 Google Cloud以外的外部服務互動。代理程式身分Identity and Access Management (IAM) 都可讓您向 Google Cloud服務驗證身分。不過,如果外部平台不支援 Google 的身分聯盟,他們就無法向這些平台證明身分。

ADK 代理需要存取各種憑證,才能與外部實體互動,例如 MCP 服務、ADK 工具和 API。常見範例如下:

  • 付款處理平台的 API 金鑰
  • 舊版地端部署資料庫的使用者名稱和密碼組合
  • 雙向傳輸層安全標準 (mTLS) 連線的私密金鑰
為支援這些用途,ADK 在 google.adk.integrations.secret_manager.secret_client 套件中提供 SecretManagerClient 模組。本模組提供標準介面,供代理程式在執行階段從 Secret Manager 擷取密鑰。本文說明如何使用 Secret Manager 管理 ADK 中外部服務的密鑰。

搭配使用 Secret Manager 與 ADK 的優點

手動管理密鑰可能會導致安全風險,並增加開發人員的手動作業。Secret Manager 可透過下列方式協助解決這些問題:

  • 如果將密鑰嵌入代理程式碼,會造成重大安全風險。這種做法可能導致未經授權存取生產系統。使用 Secret Manager 可從原始碼中移除敏感資料。這有助於提高應用程式的安全性。
  • 如果透過環境變數嵌入靜態密鑰,憑證輪替就會變得複雜。如要套用更新,請重新啟動部署容器。 Secret Manager 會在執行階段動態擷取憑證,因此更新時系統不會停機。
  • 如果您為每個工具編寫自訂 SecretManagerServiceClient 樣板程式碼,就會增加開發人員的手動作業和錯誤風險。標準化的 ADK 整合方式提供乾淨且可重複使用的憑證擷取方法。

事前準備

將 Secret Manager 與 ADK 整合前,請先完成下列步驟:

  1. 使用 ADK 設定代理。這項功能需要使用 Python 適用的 ADK 1.29 以上版本
  2. Secret Manager Secret Accessor IAM 角色授予代理程式身分。這個角色可讓代理在執行階段擷取密鑰。
  3. 在 Secret Manager 中建立密鑰新增密鑰版本,例如 API 金鑰。

ADK 代理在執行階段擷取密鑰的方式

secret_client.SecretManagerClient 模組會在執行階段將憑證擷取到 Python 代理程式碼邏輯中。代理自動調度管理邏輯會將提示傳送至大型語言模型 (LLM),決定要執行的工具,但系統不會將密鑰傳送至 LLM。

代理程式會在執行階段執行下列步驟:

  1. ADK 代理呼叫第三方工具前,會先初始化 SecretManagerClient 模組,然後呼叫 get_secret() 函式。
  2. ADK 代理程式會使用代理程式身分向 Secret Manager 進行驗證。
  3. SecretManagerClient 模組會將明文密碼傳回 ADK 代理。
  4. ADK 代理程式會使用密鑰,向第三方工具發出經過驗證的呼叫。

在執行階段擷取 ADK 代理中的密鑰

下列程式碼範例說明如何使用 SecretManagerClient 模組,在 ADK 代理程式中安全地擷取密鑰。代理程式會在內部擷取密鑰,避免將敏感憑證暴露在 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.")

後續步驟