使用 AI.GENERATE 函数生成文本

本教程将介绍如何使用 AI.GENERATE 函数以及托管的 Gemini 模型,从文本、音频或视频生成文本。此方法无需您创建和维护自己的模型。

目标

  • 总结新闻报道。
  • 根据新闻报道生成结构化输出,包括摘要和总体情感。
  • 创建日语视频的转写内容并将其翻译成英语。
  • 根据音频内容生成摘要和主题列表。

费用

在本文档中,您将使用 Google Cloud的以下收费组件:

  • BigQuery ML: You incur costs for the data that you process in BigQuery.
  • Gemini Enterprise Agent Platform: You incur costs for calls to the Agent Platform model.

如需根据您的预计使用情况来估算费用,请使用价格计算器

新 Google Cloud 用户可能有资格申请免费试用

如需了解详情,请参阅 BigQuery 价格Agent Platform 价格

准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud新手,请 创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  5. Verify that billing is enabled for your Google Cloud project.

  6. 启用 BigQuery API。

    启用 API 所需的角色

    如需启用 API,您需要拥有 serviceusage.services.enable 权限。如果您创建了项目,则可能已经通过 Owner 角色 (roles/owner) 获得了此权限。否则,您可以通过 Service Usage Admin 角色 (roles/serviceusage.serviceUsageAdmin) 获得此权限。了解如何授予角色

    启用 API

    对于新项目,BigQuery API 会自动启用。

所需的角色

如需获得使用 AI.GENERATE 函数所需的权限,请让您的管理员为您授予以下 IAM 角色:

  • 创建和使用 BigQuery 数据集和表: 项目的 BigQuery Data Editor (roles/bigquery.dataEditor)。
  • 创建、委托和使用 BigQuery 连接:针对您的项目的 BigQuery Connections Admin (roles/bigquery.connectionsAdmin)。
  • 为连接的服务账号授予权限:包含 Gemini Enterprise Agent Platform 端点的项目的 Project IAM Admin (roles/resourcemanager.projectIamAdmin)。
  • 创建 BigQuery 作业:项目的 BigQuery Job User (roles/bigquery.jobUser)。

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

这些预定义角色包含使用 AI.GENERATE 函数所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

使用 AI.GENERATE 函数需要以下权限:

  • 创建数据集: bigquery.datasets.create
  • 创建、委托和使用连接: bigquery.connections.*
  • 设置服务账号权限:
    • resourcemanager.projects.getIamPolicy
    • resourcemanager.projects.setIamPolicy
  • 查询表格数据: bigquery.tables.getData

您也可以使用自定义角色或其他预定义角色来获取这些权限。

创建数据集

创建 BigQuery 数据集以包含您的资源:

控制台

  1. 在 Google Cloud 控制台中,前往 BigQuery 页面。

    转到 BigQuery

  2. 在左侧窗格中,点击 探索器

    突出显示的“探索器”窗格按钮。

    如果您没有看到左侧窗格,请点击 展开左侧窗格以打开该窗格。

  3. 探索器窗格中,点击您的项目名称。

  4. 点击 查看操作 > 创建数据集

  5. 创建数据集 页面上,执行以下操作:

    1. 数据集 ID 中,输入数据集的名称。

    2. 位置类型部分,选择区域多区域

      • 如果您选择了区域,请从区域列表中选择一个位置。
      • 如果您选择了多区域,请从多区域列表中选择美国欧洲
    3. 点击创建数据集

bq

  1. 如需创建新数据集,请使用带有 --location 标志的 bq mk 命令:

    bq --location=LOCATION mk -d DATASET_ID

    替换以下内容:

    • LOCATION:数据集的位置
    • DATASET_ID:您要创建的数据集的 ID。
  2. 确认已创建数据集:

    bq ls

创建连接

创建训练数据集后,您需要建立连接,以关联 BigQuery 和外部来源。创建 Cloud 资源连接并获取连接的服务账号。 在上一步中创建的数据集所在的位置创建连接。

从下列选项中选择一项:

控制台

  1. 前往 BigQuery 页面。

    转到 BigQuery

  2. 在左侧窗格中,点击 探索器

    突出显示的“探索器”窗格按钮。

    如果您没有看到左侧窗格,请点击 展开左侧窗格以打开该窗格。

  3. 探索器窗格中,展开您的项目名称,然后点击连接

  4. 连接页面上,点击创建连接

  5. 对于连接类型,请选择 Vertex AI 远程模型、远程函数、BigLake 和 Spanner(Cloud 资源)

  6. 连接 ID 字段中,输入连接的名称。

  7. 对于位置类型,为连接选择一个位置。连接应与数据集等其他资源位于同一位置。

  8. 点击创建连接

  9. 点击转到连接

  10. 连接信息窗格中,复制服务账号 ID 以在后续步骤中使用。

SQL

使用 CREATE CONNECTION 语句

  1. 在 Google Cloud 控制台中,前往 BigQuery 页面。

    转到 BigQuery

  2. 在查询编辑器中,输入以下语句:

    CREATE CONNECTION [IF NOT EXISTS] `CONNECTION_NAME`
    OPTIONS (
      connection_type = "CLOUD_RESOURCE",
      friendly_name = "FRIENDLY_NAME",
      description = "DESCRIPTION"
      );

    请替换以下内容:

    • CONNECTION_NAME:连接的名称,格式为 PROJECT_ID.LOCATION.CONNECTION_IDLOCATION.CONNECTION_IDCONNECTION_ID。如果省略项目或位置,则系统会根据运行语句的项目和位置推断出相应信息。
    • FRIENDLY_NAME(可选):连接的描述性名称。
    • DESCRIPTION(可选):连接的说明。

  3. 点击 运行

如需详细了解如何运行查询,请参阅运行交互式查询

bq

  1. 在命令行环境中,创建连接:

    bq mk --connection --location=REGION --project_id=PROJECT_ID \
        --connection_type=CLOUD_RESOURCE CONNECTION_ID

    --project_id 参数会替换默认项目。

    请替换以下内容:

    • REGION:您的连接区域
    • PROJECT_ID:您的 Google Cloud 项目 ID
    • CONNECTION_ID:您的连接的 ID

    当您创建连接资源时,BigQuery 会创建一个唯一的系统服务账号,并将其与该连接相关联。

    问题排查:如果您收到以下连接错误,请更新 Google Cloud SDK

    Flags parsing error: flag --connection_type=CLOUD_RESOURCE: value should be one of...
    
  2. 检索并复制服务账号 ID 以在后续步骤中使用:

    bq show --connection PROJECT_ID.REGION.CONNECTION_ID

    输出类似于以下内容:

    name                          properties
    1234.REGION.CONNECTION_ID     {"serviceAccountId": "connection-1234-9u56h9@gcp-sa-bigquery-condel.iam.gserviceaccount.com"}
    

Python

试用此示例之前,请按照 BigQuery 快速入门:使用客户端库中的 Python 设置说明进行操作。 如需了解详情,请参阅 BigQuery Python API 参考文档

如需向 BigQuery 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

import google.api_core.exceptions
from google.cloud import bigquery_connection_v1

client = bigquery_connection_v1.ConnectionServiceClient()


def create_connection(
    project_id: str,
    location: str,
    connection_id: str,
):
    """Creates a BigQuery connection to a Cloud Resource.

    Cloud Resource connection creates a service account which can then be
    granted access to other Google Cloud resources for federated queries.

    Args:
        project_id: The Google Cloud project ID.
        location: The location of the connection (for example, "us-central1").
        connection_id: The ID of the connection to create.
    """

    parent = client.common_location_path(project_id, location)

    connection = bigquery_connection_v1.Connection(
        friendly_name="Example Connection",
        description="A sample connection for a Cloud Resource.",
        cloud_resource=bigquery_connection_v1.CloudResourceProperties(),
    )

    try:
        created_connection = client.create_connection(
            parent=parent, connection_id=connection_id, connection=connection
        )
        print(f"Successfully created connection: {created_connection.name}")
        print(f"Friendly name: {created_connection.friendly_name}")
        print(
            f"Service Account: {created_connection.cloud_resource.service_account_id}"
        )

    except google.api_core.exceptions.AlreadyExists:
        print(f"Connection with ID '{connection_id}' already exists.")
        print("Please use a different connection ID.")
    except Exception as e:
        print(f"An unexpected error occurred while creating the connection: {e}")

Node.js

试用此示例之前,请按照 BigQuery 快速入门:使用客户端库中的 Node.js 设置说明进行操作。 如需了解详情,请参阅 BigQuery Node.js API 参考文档

如需向 BigQuery 进行身份验证,请设置应用默认凭证。如需了解详情,请参阅为客户端库设置身份验证

const {ConnectionServiceClient} =
  require('@google-cloud/bigquery-connection').v1;
const {status} = require('@grpc/grpc-js');

const client = new ConnectionServiceClient();

/**
 * Creates a new BigQuery connection to a Cloud Resource.
 *
 * A Cloud Resource connection creates a service account that can be granted access
 * to other Google Cloud resources.
 *
 * @param {string} projectId The Google Cloud project ID. for example, 'example-project-id'
 * @param {string} location The location of the project to create the connection in. for example, 'us-central1'
 * @param {string} connectionId The ID of the connection to create. for example, 'example-connection-id'
 */
async function createConnection(projectId, location, connectionId) {
  const parent = client.locationPath(projectId, location);

  const connection = {
    friendlyName: 'Example Connection',
    description: 'A sample connection for a Cloud Resource',
    // The service account for this cloudResource will be created by the API.
    // Its ID will be available in the response.
    cloudResource: {},
  };

  const request = {
    parent,
    connectionId,
    connection,
  };

  try {
    const [response] = await client.createConnection(request);

    console.log(`Successfully created connection: ${response.name}`);
    console.log(`Friendly name: ${response.friendlyName}`);

    console.log(`Service Account: ${response.cloudResource.serviceAccountId}`);
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.log(`Connection '${connectionId}' already exists.`);
    } else {
      console.error(`Error creating connection: ${err.message}`);
    }
  }
}

Terraform

使用 google_bigquery_connection 资源。

如需向 BigQuery 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为客户端库设置身份验证

以下示例在 US 区域中创建一个名为 my_cloud_resource_connection 的 Cloud 资源连接:


# This queries the provider for project information.
data "google_project" "default" {}

# This creates a cloud resource connection in the US region named my_cloud_resource_connection.
# Note: The cloud resource nested object has only one output field - serviceAccountId.
resource "google_bigquery_connection" "default" {
  connection_id = "my_cloud_resource_connection"
  project       = data.google_project.default.project_id
  location      = "US"
  cloud_resource {}
}

如需在 Google Cloud 项目中应用 Terraform 配置,请完成以下部分中的步骤。

准备 Cloud Shell

  1. 启动 Cloud Shell
  2. 设置要应用 Terraform 配置的默认 Google Cloud 项目。

    您只需为每个项目运行一次以下命令,即可在任何目录中运行它。

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    如果您在 Terraform 配置文件中设置显式值,则环境变量会被替换。

准备目录

每个 Terraform 配置文件都必须有自己的目录(也称为“根模块”)。

  1. Cloud Shell 中,创建一个目录,并在该目录中创建一个新文件。文件名必须具有 .tf 扩展名,例如 main.tf。在本教程中,该文件称为 main.tf
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. 如果您按照教程进行操作,可以在每个部分或步骤中复制示例代码。

    将示例代码复制到新创建的 main.tf 中。

    (可选)从 GitHub 中复制代码。如果端到端解决方案包含 Terraform 代码段,则建议这样做。

  3. 查看和修改要应用到您的环境的示例参数。
  4. 保存更改。
  5. 初始化 Terraform。您只需为每个目录执行一次此操作。
    terraform init

    (可选)如需使用最新的 Google 提供程序版本,请添加 -upgrade 选项:

    terraform init -upgrade

应用更改

  1. 查看配置并验证 Terraform 将创建或更新的资源是否符合您的预期:
    terraform plan

    根据需要更正配置。

  2. 通过运行以下命令并在提示符处输入 yes 来应用 Terraform 配置:
    terraform apply

    等待 Terraform 显示“应用完成!”消息。

  3. 打开您的 Google Cloud 项目以查看结果。在 Google Cloud 控制台的界面中找到资源,以确保 Terraform 已创建或更新它们。

向服务账号授予访问权限

向连接的服务账号授予 Agent Platform User 和 Storage Object Viewer 角色。如需授予这些角色,请按以下步骤操作:

  1. 前往 IAM 和管理页面。

    转到“IAM 和管理”

  2. 点击 Add

    系统随即会打开添加主账号对话框。

  3. 新的主账号字段中,输入您之前复制的服务账号 ID。

  4. 选择角色字段中,选择 Vertex AI,然后选择 Agent Platform User

  5. 点击添加其他角色

  6. 选择角色字段中,选择 Cloud Storage,然后选择 Storage Object Viewer

  7. 点击保存

总结文本并使用默认输出格式

如需总结新闻报道,请调用 AI.GENERATE 函数,并将报道文本作为提示。默认情况下,输出包括生成的摘要文本、完整响应以及一个状态(如果函数成功返回,则为空)。

  1. 在 Google Cloud 控制台中,前往 BigQuery 页面。

    转到 BigQuery

  2. 在查询编辑器中,运行以下查询:

    WITH
    bbc_news AS (
      SELECT body FROM `bigquery-public-data.bbc_news.fulltext` LIMIT 5
    )
    SELECT AI.GENERATE(body, endpoint => 'gemini-2.5-pro') AS news FROM bbc_news;

    输出类似于以下内容:

    +---------------------------------------------+------------------------------------+---------------+
    | news.result                                 | news.full_response                 | news.status   |
    +---------------------------------------------+------------------------------------+---------------+
    | This article presents a debate about the    | {"candidates":[{"avg_logprobs":    |               |
    | "digital divide" between rich and poor      | -0.31465074559841777, content":    |               |
    | nations. Here's a breakdown of the key...   | {"parts":[{"text":"This article... |               |
    +---------------------------------------------+------------------------------------+---------------+
    | This article discusses how advanced         | {"candidates":[{"avg_logprobs":    |               |
    | mapping technology is aiding humanitarian   | -0.21313422900091983,"content":    |               |
    | efforts in Darfur, Sudan. Here's a...       | {"parts":[{"text":"This article... |               |
    +---------------------------------------------+------------------------------------+---------------+
    | ...                                         | ...                                | ...           |
    +---------------------------------------------+------------------------------------+---------------+
    

总结文本并输出结构化结果

请按照以下步骤操作,使用 AI.GENERATE 函数生成文本,并使用 AI.GENERATE 函数的 output_schema 参数设置输出格式:

  1. 在 Google Cloud 控制台中,前往 BigQuery 页面。

    转到 BigQuery

  2. 在查询编辑器中,运行以下查询:

    WITH bbc_news AS (
      SELECT
        body
      FROM
        `bigquery-public-data`.bbc_news.fulltext
      LIMIT 5
    )
    SELECT
      news.good_sentiment,
      news.summary
    FROM
      bbc_news,
      UNNEST(ARRAY[AI.GENERATE(body, endpoint => 'gemini-2.5-pro', output_schema  => 'summary STRING, good_sentiment BOOL')]) AS news;

    输出类似于以下内容:

    +----------------+--------------------------------------------+
    | good_sentiment | summary                                    |
    +----------------+--------------------------------------------+
    | true           | A World Bank report suggests the digital   |
    |                | divide is rapidly closing due to increased |
    |                | access to technology in developing...      |
    +----------------+--------------------------------------------+
    | false          | A massive earthquake and subsequent        |
    |                | waves have devastated southern Asia, with  |
    |                | Sri Lanka, India, Indonesia, and...        |
    +----------------+--------------------------------------------+
    | ...            | ...                                        |
    +----------------+--------------------------------------------+
    

转写和翻译视频内容

您可以使用外部对象表处理存储在 Cloud Storage 中的多媒体文件。以下步骤展示了如何为视频文件创建对象表、转写日语视频内容,以及将文本翻译成英语。

  1. 在 Google Cloud 控制台中,前往 BigQuery 页面。

    转到 BigQuery

  2. 在查询编辑器中,运行以下查询以创建对象表:

    CREATE OR REPLACE EXTERNAL TABLE `bqml_tutorial.video`
    WITH CONNECTION `us.test_connection`
    OPTIONS (
      object_metadata = 'SIMPLE',
      uris =
        ['gs://cloud-samples-data/generative-ai/video/*']);
  3. 在查询编辑器中,运行以下查询以转写和翻译 pixel8.mp4 文件:

    SELECT
      AI.GENERATE(
        (OBJ.GET_ACCESS_URL(ref, 'r'), 'Transcribe the video in Japanese and then translate to English.'),
        endpoint => 'gemini-2.5-pro',
        output_schema => 'japanese_transcript STRING, english_translation STRING'
      ).* EXCEPT (full_response, status)
    FROM
      `bqml_tutorial.video`
    WHERE
      REGEXP_CONTAINS(uri, 'pixel8.mp4');

    输出类似于以下内容:

    +--------------------------------------------+--------------------------------+
    | english_translation                        | japanese_transcript            |
    +--------------------------------------------+--------------------------------+
    | My name is Saeka Shimada. I'm a            | 島田 さえか です 。 東京 で フ     |
    | photographer in Tokyo. Tokyo has many      | ォトグラファー を し て い ま      |
    | faces. The city at night is totally...     | す 。 東京 に は いろんな 顔 が    |
    +--------------------------------------------+--------------------------------+
    

分析音频文件内容

按照以下步骤,基于公开音频内容创建对象表,然后分析音频文件的内容。

  1. 在 Google Cloud 控制台中,前往 BigQuery 页面。

    转到 BigQuery

  2. 在查询编辑器中,运行以下查询以创建对象表:

    CREATE OR REPLACE EXTERNAL TABLE `bqml_tutorial.audio`
    WITH CONNECTION `us.test_connection`
    OPTIONS (
      object_metadata = 'SIMPLE',
      uris =
        ['gs://cloud-samples-data/generative-ai/audio/*']);
  3. 在查询编辑器中,运行以下查询以分析音频文件:

    SELECT
      AI.GENERATE(
        (OBJ.GET_ACCESS_URL(ref, 'r'), 'Summarize the content of this audio file.'),
        endpoint => 'gemini-2.5-pro',
        output_schema => 'topic ARRAY<STRING>, summary STRING'
      ).* EXCEPT (full_response, status), uri
    FROM
      `bqml_tutorial.audio`;

    结果类似于以下内容:

    +--------------------------------------------+-----------------------------------------------------------+
    | summary                                    | topic              | uri                                  |
    +--------------------------------------------+-----------------------------------------------------------+
    | The audio contains a distinctive 'beep'    | beep sound         | gs://cloud-samples-data/generativ... |
    | sound, followed by the characteristic      |                    |                                      |
    | sound of a large vehicle or bus backing..  |                    |                                      |
    +--------------------------------------------+--------------------+--------------------------------------+
    |                                            | vehicle backing up |                                      |
    |                                            +--------------------+                                      |
    |                                            | bus                |                                      |
    |                                            +--------------------+                                      |
    |                                            | alarm              |                                      |
    +--------------------------------------------+--------------------+--------------------------------------+
    | The speaker introduces themselves          | Introduction       | gs://cloud-samples-data/generativ... |
    | as Gemini and expresses their excitement   |                    |                                      |
    | and readiness to dive into something..     |                    |                                      |
    +--------------------------------------------+--------------------+--------------------------------------+
    |                                            | Readiness          |                                      |
    |                                            +--------------------+                                      |
    |                                            | Excitement         |                                      |
    |                                            +--------------------+                                      |
    |                                            | Collaboration      |                                      |
    +--------------------------------------------+--------------------+--------------------------------------+
    | ...                                        | ...                | ...                                  |
    +--------------------------------------------+--------------------+--------------------------------------+
    

清理

为避免因本教程中使用的资源导致您的 Google Cloud 账号产生费用,请删除包含这些资源的项目,或者保留项目但删除各个资源。

  1. 在 Google Cloud 控制台中,前往管理资源页面。

    转到“管理资源”

  2. 在项目列表中,选择要删除的项目,然后点击删除
  3. 在对话框中输入项目 ID,然后点击关闭以删除项目。

删除各个资源

如果您希望重复使用该项目,请删除为本教程创建的资源。

控制台

  1. 转到 BigQuery 页面。

    转到 BigQuery

  2. 删除 bqml_tutorial 数据集。删除数据集也会删除远程模型。

    1. 探索器窗格中,展开您的项目,然后点击数据集

    2. 数据集列表中,点击 bqml_tutorial 数据集。

    3. 在详细信息窗格中,点击 删除

    4. 删除数据集对话框中,点击删除

  3. 删除连接:

    1. 探索器窗格中,展开您的项目,然后点击连接

    2. 连接 ID 列表中,点击您创建的连接。

    3. 在详细信息窗格中,点击 删除

    4. 删除关联对话框中,输入 delete 以确认删除。

    5. 点击删除

gcloud

  1. 删除 bqml_tutorial 数据集和远程模型:

    bq rm --dataset --recursive bqml_tutorial
    
  2. 删除连接。

    bq rm --connection PROJECT_ID.LOCATION.CONNECTION_ID
    

    替换以下内容:

    • PROJECT_ID:您的 Google Cloud 项目 ID
    • LOCATION:连接的位置
    • CONNECTION_ID:连接 ID

后续步骤