跳转到内容

用于 ADK 的 Google Cloud Data Agents 工具

在 ADK 中得到支持。Python v1.23.0

这是一组工具,旨在实现与由……提供支持的数据代理(data agents)的集成。 Conversational Analytics API数据代理是一种由人工智能驱动的辅助工具,可以帮助您使用自然语言来分析数据。在配置数据代理时,您可以从支持的数据源中选择所需的数据源。 BigQuery, Looker,以及 Looker StudioThe DataAgentToolset 默认情况下,包含以下仅限读取(read-only)的工具:

  • list_accessible_data_agents:列出您有权访问的特定 Google Cloud 项目中的数据代理(data agents)。支持可选参数。 location 支持覆盖(override)功能,以及自动或手动的分页(pagination)方式。page_size 和 page_token).
  • get_data_agent_info:根据特定数据代理的完整资源名称,检索其详细信息以及相关的公开信息。projects/{project}/locations/{location}/dataAgents/{agent}).
  • ask_data_agent:将一个自然语言问题发送给特定的数据处理系统(即“数据代理”),并接收该系统的响应结果。

如果您设置了…… enable_data_agent_modification=True 在……里面;处于……状态 DataAgentToolConfig该工具集还包括以下工具:

  • create_data_agent:使用给定的参数创建一个新的数据代理。 data_agent_id 从一个 JSON 文件中,获取 Google Cloud 项目的相关信息。 agent_config “that follows the”中的“that”指的是前面提到的某个事物或情况;“follows”则表示“跟随”或“接着发生”。因此,整个短语的意思是:“紧随在……之后发生的事情”。 DataAgent 资源模式(Resource Schema). The location 该参数是可选的。
  • update_data_agent:从 JSON 格式的数据中更新现有的数据代理。 agent_config 以及由逗号分隔的…… update_mask 使用驼峰式(camelCase)的字段名称(例如: displayName,description). 列出的每个字段…… update_mask 也必须存在于……中。 agent_config.
  • delete_data_agent:根据数据代理的完整资源名称来删除该数据代理。

这些修改工具会等待底层的长时间运行操作完成(这个过程可能需要很长时间)。 data_agent_modification_timeout_seconds.

先决条件

在使用这些工具之前,请先在 Google Cloud 中完成以下步骤:

身份验证(Authentication)

The DataAgentToolset 需要一个 DataAgentCredentialsConfig 并且支持多种身份验证机制。您必须提供其中一种身份验证方式。 credentials, external_access_token_key,或者一个 client_id 和 client_secret `pair`。默认情况下, DataAgentCredentialsConfig 使用(该工具/方法等) https://www.googleapis.com/auth/bigquery OAuth 的作用范围(scope);您可以使用相应的设置来覆盖该默认值。 scopes 在配置 OAuth 客户端凭据时。

实验性的(Experimental)

The DataAgentCredentialsConfig `class extends` 是一种用于继承类的语法结构。它表示一个类(称为子类或派生类)继承另一个类(称为父类或基类)的属性和方法。子类可以访问父类的所有成员(包括属性和方法),并且可以根据需要添加新的成员或修改父类的成员。 BaseGoogleCredentialsConfig该功能仍处于实验阶段,不应用于生产环境中的项目。

应用程序默认凭据(Application Default Credentials)

你应该在本地开发以及使用 Google Cloud 服务(如 Cloud Run 和 GKE)时采用这种方法。

import google.auth
from google.adk.tools.data_agent import DataAgentToolset, DataAgentCredentialsConfig

# Load Application Default Credentials
credentials, project_id = google.auth.default()

# Configure the toolset
credentials_config = DataAgentCredentialsConfig(credentials=credentials)
data_agent_toolset = DataAgentToolset(credentials_config=credentials_config)

服务账户(Service Account)

您可以明确提供一个服务账户文件或相关信息。

from google.oauth2 import service_account
from google.adk.tools.data_agent import DataAgentToolset, DataAgentCredentialsConfig

# Load Service Account credentials
credentials = service_account.Credentials.from_service_account_file('path/to/key.json')

# Configure the toolset
credentials_config = DataAgentCredentialsConfig(credentials=credentials)
data_agent_toolset = DataAgentToolset(credentials_config=credentials_config)

外部访问令牌(External Access Token)

对于那些需要代表最终用户执行操作的应用程序来说,您可以直接使用从访问令牌(例如通过 OAuth2 流程或外部 IDP 获得的访问令牌)中提取的用户凭据。

from google.oauth2.credentials import Credentials
from google.adk.tools.data_agent import DataAgentToolset, DataAgentCredentialsConfig

# Assume 'user_token' is obtained via an external OAuth flow
credentials = Credentials(token=user_token)

# Configure the toolset
credentials_config = DataAgentCredentialsConfig(credentials=credentials)
data_agent_toolset = DataAgentToolset(credentials_config=credentials_config)

外部身份验证提供商(External Auth Providers)

如果您正在与外部身份验证提供商进行集成(在该提供商中,令牌由平台本身管理,例如 Gemini Enterprise),请使用以下方法: external_access_token_key.

from google.adk.tools.data_agent import DataAgentToolset, DataAgentCredentialsConfig

# The key used to look up the access token in the session state
credentials_config = DataAgentCredentialsConfig(
    external_access_token_key="YOUR_AUTH_ID"
)
data_agent_toolset = DataAgentToolset(credentials_config=credentials_config)

交互式身份验证(ADK Web)

在使用该功能时,请确保遵循以下步骤: adk web 该接口用于实现交互式会话;您可以通过提供 OAuth 2.0 客户端凭据来触发登录流程。该机制既适用于本地开发环境,也适用于将 ADK 代理部署到 Cloud Run 等环境中的情况。

from google.adk.tools.data_agent import DataAgentToolset, DataAgentCredentialsConfig

# Provide OAuth 2.0 Client ID and Secret
credentials_config = DataAgentCredentialsConfig(
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET"
)
data_agent_toolset = DataAgentToolset(credentials_config=credentials_config)

配置

您可以使用相关功能来自定义工具的行为。 DataAgentToolConfig:

  • max_query_result_rows (int, 默认值: 50):允许显示的最大行数 ask_data_agent 为每个数据结果返回相应的信息。
  • location (str | None, 默认值: None): 默认的 Google Cloud 位置(例如, global, us,或 eu用于选择 API 端点的参数。某些工具会接受这个参数。 location **参数说明:** 当该参数未被设置时,使用此值作为默认值。 global其他工具会使用数据代理资源名称中包含的位置信息,但…… ask_data_agent如果该值被设置了,程序就会使用这个值。
  • api_endpoint (str | None, 默认值: None):用于 Conversational Analytics API 请求的可选自定义 API 端点。如果提供了该自定义端点,它将覆盖默认的或根据位置自动确定的 API 端点。
  • enable_data_agent_modification (bool, 默认值: False):什么时候 True该工具集还包括: create_data_agent, update_data_agent,以及 delete_data_agent. 当……的时候 False该工具集仅具有读取权限(即用户只能查看其中的内容,而不能对其进行修改或删除)。
  • data_agent_modification_timeout_seconds (int, 默认值: 60): 在轮询耗时较长的创建(create)、更新(update)或删除(delete)操作时,总超时时间(以秒为单位)。该值必须大于…… 0.
  • data_agent_modification_poll_interval_seconds (int, 默认值: 2): 在等待创建、更新或删除操作完成期间的轮询间隔(以秒为单位)。该间隔必须大于…… 0.

请谨慎使用。

设置 enable_data_agent_modification=True 该工具允许代理在您的 Google Cloud 项目中创建、更新和删除数据代理。请确保该工具集使用的凭据仅限于被授权的项目,并且这些凭据仅具备完成所需任务所需的最低限度的 IAM 权限。您也可以选择手动传递这些凭据(即不使用工具集自带的凭据管理功能)。 tool_filter 给……;发送到…… DataAgentToolset 仅显示特定的工具(例如,排除其他工具)。 delete_data_agent).

import google.auth
from google.adk.tools.data_agent import DataAgentToolset, DataAgentCredentialsConfig
from google.adk.tools.data_agent.config import DataAgentToolConfig

credentials, _ = google.auth.default()
credentials_config = DataAgentCredentialsConfig(credentials=credentials)

tool_config = DataAgentToolConfig(
    max_query_result_rows=100,
    enable_data_agent_modification=True,
    data_agent_modification_timeout_seconds=120,
)
data_agent_toolset = DataAgentToolset(
    credentials_config=credentials_config,
    data_agent_tool_config=tool_config,
)

示例代码

以下示例代码展示了如何使用该功能。 DataAgentToolset 在 ADK 代理中,使用应用程序默认凭据(Application Default Credentials,简称 ADC)进行身份验证。

import asyncio

from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.tools.data_agent import DataAgentCredentialsConfig
from google.adk.tools.data_agent import DataAgentToolset
from google.adk.tools.data_agent.config import DataAgentToolConfig
from google.genai import types
import google.auth

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

# Define tool configuration
# Set `enable_data_agent_modification=True` to also expose `create_data_agent`,
# `update_data_agent`, and `delete_data_agent`.
tool_config = DataAgentToolConfig(
    max_query_result_rows=100,
    enable_data_agent_modification=False,
)

# Use Application Default Credentials (ADC)
# https://cloud.google.com/docs/authentication/provide-credentials-adc
application_default_credentials, _ = google.auth.default()
credentials_config = DataAgentCredentialsConfig(
    credentials=application_default_credentials
)

# Instantiate a Data Agent toolset
da_toolset = DataAgentToolset(
    credentials_config=credentials_config,
    data_agent_tool_config=tool_config,
)

# Agent Definition
data_agent = Agent(
    name=AGENT_NAME,
    model=GEMINI_MODEL,
    description="Agent to answer user questions using data agents.",
    instruction=(
        "## Persona\nYou are a helpful assistant that uses data agents"
        " to answer user questions about their data.\n\n"
    ),
    tools=[da_toolset],
)


# Session and Runner
async def setup_session_and_runner():
    session_service = InMemorySessionService()
    await session_service.create_session(
        app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID
    )
    return Runner(
        agent=data_agent, app_name=APP_NAME, session_service=session_service
    )


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

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


async def main():
    runner = await setup_session_and_runner()
    # Replace `<PROJECT_ID>` with your Google Cloud project ID, and replace
    # `<DATA_AGENT_NAME>` with a full resource name in the format:
    # `projects/{project}/locations/{location}/dataAgents/{agent}`
    await call_agent_async(
        runner, "List accessible data agents in project <PROJECT_ID>."
    )
    await call_agent_async(runner, "Get information about <DATA_AGENT_NAME>.")
    # The data agent in this example is configured with the BigQuery table:
    # `bigquery-public-data.san_francisco.street_trees`
    await call_agent_async(
        runner, "Ask <DATA_AGENT_NAME> to count the rows in the table."
    )
    await call_agent_async(runner, "What are the columns in the table?")
    await call_agent_async(runner, "What are the top 5 tree species?")
    await call_agent_async(
        runner, "For those species, what is the distribution of legal status?"
    )

注意:如果您想直接使用某个工具来查询 BigQuery 的表和数据集,请参阅…… 用于 ADK 的 BigQuery 工具.