Skip to content

Google Cloud 工具

python_only

Google Cloud 工具可讓你更輕鬆地將 agent 連接到 Google Cloud 的產品與服務。只需幾行程式碼,你就能使用這些工具將 agent 連接至:

  • 任何由開發人員在 Apigee 上架設的自訂 API
  • 數百種預建連接器,可連接至企業系統,如 Salesforce、Workday 和 SAP
  • 透過應用程式整合所建立的自動化工作流程
  • 使用 MCP Toolbox for databases 連接如 Spanner、AlloyDB、Postgres 等資料庫

Google Cloud Tools

Apigee API Hub 工具

ApiHubToolset 讓你只需幾行程式碼,即可將任何來自 Apigee API hub 的已文件化 API 轉換為工具。本節將逐步說明相關操作,包括如何設定驗證,以安全連接你的 API。

先決條件

  1. 安裝 Agent Development Kit (ADK)
  2. 安裝 Google Cloud CLI
  3. 擁有 Apigee API hub 實例,且其中包含已文件化(即 OpenAPI 規格)的 API
  4. 設定你的專案結構並建立所需檔案
project_root_folder
 |
 `-- my_agent
     |-- .env
     |-- __init__.py
     |-- agent.py
     `__ tool.py

建立 API Hub 工具組

注意:本教學包含 agent 的建立。如果你已經有一個 agent,只需依照部分步驟操作即可。

  1. 取得你的 access token,以便 APIHubToolset 能夠從 API Hub API 擷取規格。在終端機執行以下指令

    gcloud auth print-access-token
    # Prints your access token like 'ya29....'
    
  2. 確認所使用的帳戶具備所需權限。你可以使用預先定義的角色 roles/apihub.viewer,或指派下列權限:

    1. apihub.specs.get(必要)
    2. apihub.apis.get(選用)
    3. apihub.apis.list(選用)
    4. apihub.versions.get(選用)
    5. apihub.versions.list(選用)
    6. apihub.specs.list(選用)
  3. 使用 APIHubToolset 建立工具。將以下內容新增至 tools.py

    如果你的 API 需要驗證,必須為該工具設定驗證機制。以下範例程式碼說明如何設定 API 金鑰(API Key)。Agent Development Kit (ADK) 支援以 token 為基礎的驗證(API Key、Bearer token)、服務帳戶(Service Account)以及 OpenID Connect。我們即將支援各種 OAuth2 流程。

    from google.adk.tools.openapi_tool.auth.auth_helpers import token_to_scheme_credential
    from google.adk.tools.apihub_tool.apihub_toolset import APIHubToolset
    
    # Provide authentication for your APIs. Not required if your APIs don't required authentication.
    auth_scheme, auth_credential = token_to_scheme_credential(
        "apikey", "query", "apikey", apikey_credential_str
    )
    
    sample_toolset = APIHubToolset(
        name="apihub-sample-tool",
        description="Sample Tool",
        access_token="...",  # Copy your access token generated in step 1
        apihub_resource_name="...", # API Hub resource name
        auth_scheme=auth_scheme,
        auth_credential=auth_credential,
    )
    

    在正式環境部署時,我們建議使用服務帳戶(Service Account)來取代 access token。在上述程式碼片段中,請使用 service_account_json=service_account_cred_json_str,並提供您的服務帳戶憑證,而非使用 token。

對於 apihub_resource_name,如果您已知要用於 API 的特定 OpenAPI 規格(OpenAPI Spec)ID,請使用 `projects/my-project-id/locations/us-west1/apis/my-api-id/versions/version-id/specs/spec-id`。 如果您希望 API Hub 工具組(Toolset)自動從 API 中擷取第一個可用的規格,請使用 `projects/my-project-id/locations/us-west1/apis/my-api-id`

  1. 建立您的 agent 檔案 Agent.py,並將已建立的 tools 加入到 agent 定義中:

    from google.adk.agents.llm_agent import LlmAgent
    from .tools import sample_toolset
    
    root_agent = LlmAgent(
        model='gemini-2.0-flash',
        name='enterprise_assistant',
        instruction='Help user, leverage the tools you have access to',
        tools=sample_toolset.get_tools(),
    )
    
  2. 設定你的 __init__.py 以公開你的 agent

    from . import agent
    
  3. 啟動 Google Agent Development Kit (ADK) Web UI,並嘗試你的 agent。

    # make sure to run `adk web` from your project_root_folder
    adk web
    

然後前往 http://localhost:8000,透過網頁 UI 試用你的 agent。


應用程式整合工具

使用 ApplicationIntegrationToolset,你可以透過 Integration Connectors 提供的 100 多種預先建置的連接器,為你的 agent 無縫提供安全且受治理的企業應用程式存取權限,支援如 Salesforce、ServiceNow、JIRA、SAP 等系統。

它同時支援內部部署(on-premise)與 SaaS 應用程式。此外,你也可以將現有的應用程式整合自動化流程,作為工具(tools)提供給你的 Agent Development Kit (ADK) agent,進而轉換為 agentic 工作流程。

先決條件

1. 安裝 ADK

Install the latest version of ADK. For information about the latest version of ADK, see Agent Development Kit Walkthrough.

Install the latest version of ADK. For information about the latest version of ADK, see Agent Development Kit Walkthrough.

2. 安裝命令列介面 (Command Line Interface)

Install Google Cloud CLI. To use the tool with default credentials, run the following commands:

gcloud config set project <project-id>
gcloud auth application-default login
gcloud auth application-default set-quota-project <project-id>

Replace <project-id> with the unique ID of your Google Cloud project.

Install Google Cloud CLI. To use the tool with default credentials, run the following commands:

gcloud config set project <project-id>
gcloud auth application-default login
gcloud auth application-default set-quota-project <project-id>

Replace <project-id> with the unique ID of your Google Cloud project.

3. 建立 Application Integration 工作流程並發佈 Connection Tool

Use an existing Application Integration workflow or Integrations Connector connection you want to use with your agent. You can also create a new Application Integration workflow or a connection.

Import and publish the Connection Tool from the template library.

Note: To use a connector from Integration Connectors, you need to provision Application Integration in the same region as your connection.

Use an existing Application Integration workflow or Integrations Connector connection you want to use with your agent. You can also create a new Application Integration workflow or a connection.

Import and publish the Connection Tool from the template library.

Note: To use a connector from Integration Connectors, you need to provision Application Integration in the same region as your connection, import and publish Connection Tool from the template library.

4. 建立專案結構

Set up your project structure and create required files.

project_root_folder
|-- .env
`-- my_agent
    |-- __init__.py
    |-- agent.py
    `__ tools.py

When running the agent, make sure to run adk web in the project\_root_folder.

Set up your project structure and create required files.

```console
  project_root_folder
  |-- my_agent
  |   |-- agent.java
  |   `-- pom.xml
```

When running the agent, make sure to run the commands in the project\_root_folder.

5. 設定角色與權限

To get the permissions that you need to set up ApplicationIntegrationToolset, you must have the following IAM roles on the project (common to both Integration Connectors and Application Integration Workflows):

  • roles/integrations.integrationEditor
  • roles/connectors.invoker
  • roles/secretmanager.secretAccessor

Note: For Agent Engine (AE), don't use roles/integrations.integrationInvoker, as it can result in 403 errors. Use roles/integrations.integrationEditor instead.

To get the permissions that you need to set up ApplicationIntegrationToolset, you must have the following IAM roles on the project (common to both Integration Connectors and Application Integration Workflows):

  • roles/integrations.integrationEditor
  • roles/connectors.invoker
  • roles/secretmanager.secretAccessor

Note: For Agent Engine (AE), don't use roles/integrations.integrationInvoker, as it can result in 403 errors. Use roles/integrations.integrationEditor instead.

使用 Integration Connectors

使用 Integration Connectors 將你的 agent 連接到企業應用程式。

開始之前

注意: ExecuteConnection 整合通常會在你於特定區域佈建 Application Integration 時自動建立。如果在 integrations 清單 中沒有 ExecuteConnection,你必須依照以下步驟手動建立:

  1. 若要從 Integration Connectors 使用 connector,請點選 QUICK SETUP,並在與你的連線相同的區域 佈建 Application Integration。

Google Cloud Tools

  1. 前往範本庫中的 Connection Tool 範本,然後點選 USE TEMPLATE

    Google Cloud Tools

  2. 輸入 Integration Name 為 ExecuteConnection(必須完全使用此名稱)。接著,選擇與你的連線相同的區域,並點選 CREATE

  3. Application Integration 編輯器中,點選 PUBLISH 以發佈此整合。

    Google Cloud Tools

建立 Application Integration 工具組

若要為 Integration Connectors 建立 Application Integration 工具組,請依照以下步驟操作:

  1. tools.py 檔案中,使用 ApplicationIntegrationToolset 建立一個工具:

    from google.adk.tools.application_integration_tool.application_integration_toolset import ApplicationIntegrationToolset
    
    connector_tool = ApplicationIntegrationToolset(
        project="test-project", # TODO: replace with GCP project of the connection
        location="us-central1", #TODO: replace with location of the connection
        connection="test-connection", #TODO: replace with connection name
        entity_operations={"Entity_One": ["LIST","CREATE"], "Entity_Two": []},#empty list for actions means all operations on the entity are supported.
        actions=["action1"], #TODO: replace with actions
        service_account_json='{...}', # optional. Stringified json for service account key
        tool_name_prefix="tool_prefix2",
        tool_instructions="..."
    )
    

    注意:

  2. 你可以提供一個服務帳戶(Service Account)來取代預設憑證,方法是產生一組 Service Account Key,並賦予該服務帳戶正確的 Application Integration 和 Integration Connector IAM 角色

  3. 若要查詢某個連線支援的實體(entity)與操作(action)清單,請使用 Connectors API:listActionslistEntityTypes

ApplicationIntegrationToolset 支援 auth_schemeauth_credential,可用於 Integration Connectors 的動態 OAuth2 認證。如需使用,請在 tools.py 檔案中建立類似以下的工具:

```py
from google.adk.tools.application_integration_tool.application_integration_toolset import ApplicationIntegrationToolset
from google.adk.tools.openapi_tool.auth.auth_helpers import dict_to_auth_scheme
from google.adk.auth import AuthCredential
from google.adk.auth import AuthCredentialTypes
from google.adk.auth import OAuth2Auth

oauth2_data_google_cloud = {
  "type": "oauth2",
  "flows": {
      "authorizationCode": {
          "authorizationUrl": "https://accounts.google.com/o/oauth2/auth",
          "tokenUrl": "https://oauth2.googleapis.com/token",
          "scopes": {
              "https://www.googleapis.com/auth/cloud-platform": (
                  "View and manage your data across Google Cloud Platform"
                  " services"
              ),
              "https://www.googleapis.com/auth/calendar.readonly": "View your calendars"
          },
      }
  },
}

oauth_scheme = dict_to_auth_scheme(oauth2_data_google_cloud)

auth_credential = AuthCredential(
  auth_type=AuthCredentialTypes.OAUTH2,
  oauth2=OAuth2Auth(
      client_id="...", #TODO: replace with client_id
      client_secret="...", #TODO: replace with client_secret
  ),
)

connector_tool = ApplicationIntegrationToolset(
    project="test-project", # TODO: replace with GCP project of the connection
    location="us-central1", #TODO: replace with location of the connection
    connection="test-connection", #TODO: replace with connection name
    entity_operations={"Entity_One": ["LIST","CREATE"], "Entity_Two": []},#empty list for actions means all operations on the entity are supported.
    actions=["GET_calendars/%7BcalendarId%7D/events"], #TODO: replace with actions. this one is for list events
    service_account_json='{...}', # optional. Stringified json for service account key
    tool_name_prefix="tool_prefix2",
    tool_instructions="...",
    auth_scheme=oauth_scheme,
    auth_credential=auth_credential
)
```
  1. 更新 agent.py 檔案並將工具(tool)加入你的 agent:

    from google.adk.agents.llm_agent import LlmAgent
    from .tools import connector_tool
    
    root_agent = LlmAgent(
        model='gemini-2.0-flash',
        name='connector_agent',
        instruction="Help user, leverage the tools you have access to",
        tools=[connector_tool],
    )
    
  2. 設定 __init__.py 以公開你的 agent:

    from . import agent
    
  3. 啟動 Google Agent Development Kit (ADK) Web UI,並使用你的 agent:

    # make sure to run `adk web` from your project_root_folder
    adk web
    

完成上述步驟後,前往 http://localhost:8000,然後選擇 my\_agent agent(這與 agent 資料夾名稱相同)。

使用 Application Integration 工作流程

使用現有的 Application Integration 工作流程作為你的 agent 工具,或建立新的工作流程。

1. 建立工具

To create a tool with ApplicationIntegrationToolset in the tools.py file, use the following code:

    integration_tool = ApplicationIntegrationToolset(
        project="test-project", # TODO: replace with GCP project of the connection
        location="us-central1", #TODO: replace with location of the connection
        integration="test-integration", #TODO: replace with integration name
        triggers=["api_trigger/test_trigger"],#TODO: replace with trigger id(s). Empty list would mean all api triggers in the integration to be considered.
        service_account_json='{...}', #optional. Stringified json for service account key
        tool_name_prefix="tool_prefix1",
        tool_instructions="..."
    )

Note: You can provide a service account to be used instead of using default credentials. To do this, generate a Service Account Key and provide the correct Application Integration and Integration Connector IAM roles to the service account. For more details about the IAM roles, refer to the Prerequisites section.

To create a tool with ApplicationIntegrationToolset in the tools.java file, use the following code:

    import com.google.adk.tools.applicationintegrationtoolset.ApplicationIntegrationToolset;
    import com.google.common.collect.ImmutableList;
    import com.google.common.collect.ImmutableMap;

    public class Tools {
        private static ApplicationIntegrationToolset integrationTool;
        private static ApplicationIntegrationToolset connectionsTool;

        static {
            integrationTool = new ApplicationIntegrationToolset(
                    "test-project",
                    "us-central1",
                    "test-integration",
                    ImmutableList.of("api_trigger/test-api"),
                    null,
                    null,
                    null,
                    "{...}",
                    "tool_prefix1",
                    "...");

            connectionsTool = new ApplicationIntegrationToolset(
                    "test-project",
                    "us-central1",
                    null,
                    null,
                    "test-connection",
                    ImmutableMap.of("Issue", ImmutableList.of("GET")),
                    ImmutableList.of("ExecuteCustomQuery"),
                    "{...}",
                    "tool_prefix",
                    "...");
        }
    }

Note: You can provide a service account to be used instead of using default credentials. To do this, generate a Service Account Key and provide the correct Application Integration and Integration Connector IAM roles to the service account. For more details about the IAM roles, refer to the Prerequisites section.

2. 將工具加入你的 agent

To update the agent.py file and add the tool to your agent, use the following code:

    from google.adk.agents.llm_agent import LlmAgent
    from .tools import integration_tool, connector_tool

    root_agent = LlmAgent(
        model='gemini-2.0-flash',
        name='integration_agent',
        instruction="Help user, leverage the tools you have access to",
        tools=[integration_tool],
    )

To update the agent.java file and add the tool to your agent, use the following code:

```java import com.google.adk.agent.LlmAgent; import com.google.adk.tools.BaseTool; import com.google.common.collect.ImmutableList;

    public class MyAgent {
        public static void main(String[] args) {
            // Assuming Tools class is defined as in the previous step
            ImmutableList<BaseTool> tools = ImmutableList.<BaseTool>builder()
                    .add(Tools.integrationTool)
                    .add(Tools.connectionsTool)
                    .build();

            // Finally, create your agent with the tools generated automatically.
            LlmAgent rootAgent = LlmAgent.builder()
                    .name("science-teacher")
                    .description("Science teacher agent")
                    .model("gemini-2.0-flash")
                    .instruction(
                            "Help user, leverage the tools you have access to."
                    )
                    .tools(tools)
                    .build();

            // You can now use rootAgent to interact with the LLM
            // For example, you can start a conversation with the agent.
        }
    }

```

Note: To find the list of supported entities and actions for a connection, use these Connector APIs: listActions, listEntityTypes.

3. 對外公開你的 agent

To configure __init__.py to expose your agent, use the following code:

    from . import agent

4. 使用你的 agent

To start the Google ADK Web UI and use your agent, use the following commands:

    # make sure to run `adk web` from your project_root_folder
    adk web
After completing the above steps, go to http://localhost:8000, and choose the my_agent agent (which is the same as the agent folder name).

To start the Google ADK Web UI and use your agent, use the following commands:

    mvn install

    mvn exec:java \
        -Dexec.mainClass="com.google.adk.web.AdkWebServer" \
        -Dexec.args="--adk.agents.source-dir=src/main/java" \
        -Dexec.classpathScope="compile"

After completing the above steps, go to http://localhost:8000, and choose the my_agent agent (which is the same as the agent folder name).


資料庫的 Toolbox 工具

MCP Toolbox for Databases 是一個開源的 MCP 伺服器,專為資料庫設計。其設計目標為企業級與生產環境品質。它能協助你更輕鬆、更快速且更安全地開發工具,因為它已處理了連線池、驗證等複雜性。

Google 的 Agent Development Kit (ADK) 已內建對 Toolbox 的支援。若需瞭解 快速開始設定 Toolbox,請參閱 文件說明

GenAI Toolbox

設定與部署

Toolbox 是一個開源伺服器,需要你自行部署與管理。更多部署與設定說明,請參考官方 Toolbox 文件說明:

安裝用戶端 SDK

Agent Development Kit (ADK) 依賴 toolbox-core Python 套件來使用 Toolbox。開始前請先安裝此套件:

pip install toolbox-core

載入 Toolbox 工具

當你的 Toolbox 伺服器已設定完成並啟動後,你可以使用 Agent Development Kit (ADK) 從伺服器載入 tools:

from google.adk.agents import Agent
from toolbox_core import ToolboxSyncClient

toolbox = ToolboxSyncClient("https://127.0.0.1:5000")

# Load a specific set of tools
tools = toolbox.load_toolset('my-toolset-name'),
# Load single tool
tools = toolbox.load_tool('my-tool-name'),

root_agent = Agent(
    ...,
    tools=tools # Provide the list of tools to the Agent

)

進階 Toolbox 功能

Toolbox 提供多種功能,協助開發用於資料庫的 Gen AI 工具。
如需更多資訊,請參閱以下功能說明:

  • Authenticated Parameters:可自動將工具輸入綁定至 OIDC token 的值,讓執行敏感查詢時更容易,並避免潛在的資料外洩風險
  • Authorized Invocations: 可根據使用者的 Auth token 限制工具的存取權限
  • OpenTelemetry:可透過 OpenTelemetry 從 Toolbox 取得指標與追蹤資料