使用 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.

如要根據預測用量估算費用,請使用 Pricing Calculator

初次使用 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 權限。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「服務使用情形管理員」角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色

    啟用 API

    新專案會自動啟用 BigQuery API。

必要的角色

如要取得使用 AI.GENERATE 函式所需的權限,請要求管理員授予您下列 IAM 角色:

  • 建立及使用 BigQuery 資料集和資料表: 專案的 BigQuery 資料編輯者 (roles/bigquery.dataEditor)。
  • 建立、委派及使用 BigQuery 連線: 專案的 BigQuery 連線管理員 (roles/bigquery.connectionsAdmin) 。
  • 將權限授予連線的服務帳戶: Gemini Enterprise Agent Platform 端點所在專案的專案 IAM 管理員 (roles/resourcemanager.projectIamAdmin)。
  • 建立 BigQuery 工作: 專案的 BigQuery 工作使用者 (roles/bigquery.jobUser)。

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

這些預先定義的角色具備使用 AI.GENERATE 函式所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:

所需權限

如要使用 AI.GENERATE 函式,必須具備下列權限:

  • 建立資料集: bigquery.datasets.create
  • 建立、委派及使用連線: bigquery.connections.*
  • 設定服務帳戶權限:
    • resourcemanager.projects.getIamPolicy
    • resourcemanager.projects.setIamPolicy
  • 查詢資料表資料: bigquery.tables.getData

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

建立資料集

建立 BigQuery 資料集來存放資源:

控制台

  1. 前往 Google Cloud 控制台的「BigQuery」頁面。

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」

    醒目顯示的「Explorer」窗格按鈕。

    如果沒有看到左側窗格,請按一下 「Expand left pane」(展開左側窗格),開啟窗格。

  3. 在「Explorer」窗格中,按一下專案名稱。

  4. 依序點按 「View actions」(查看動作)「>」(大於符號)「Create dataset」(建立資料集)

  5. 在「建立資料集」頁面中,執行下列操作:

    1. 在「Dataset ID」(資料集 ID) 部分,輸入資料集的名稱。

    2. 在「位置類型」部分,選取「區域」或「多區域」

      • 如果選取「區域」,請從「區域」清單中選取位置。
      • 如果選取「多區域」,請從「多區域」清單中選取「美國」或「歐洲」
    3. 點選「建立資料集」

bq

  1. 如要建立新的資料集,請使用 bq mk 指令,並加上 --location 旗標:

    bq --location=LOCATION mk -d DATASET_ID

    更改下列內容:

    • LOCATION:資料集的位置
    • DATASET_ID:您要建立的資料集 ID。
  2. 確認資料集已建立完成:

    bq ls

建立連線

建立訓練資料集後,請建立連線,連結 BigQuery 和外部來源。建立Cloud 資源連線,並取得連線的服務帳戶。在與您在上一步建立的資料集相同的位置建立連線。

選取下列選項之一:

控制台

  1. 前往「BigQuery」頁面。

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」

    醒目顯示的「Explorer」窗格按鈕。

    如果沒有看到左側窗格,請按一下 「Expand left pane」(展開左側窗格),開啟窗格。

  3. 在「Explorer」窗格中展開專案名稱,然後按一下「Connections」

  4. 在「Connections」(連線) 頁面中,按一下「Create connection」(建立連線)

  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 顯示「Apply complete!」訊息。

  3. 開啟 Google Cloud 專案即可查看結果。在 Google Cloud 控制台中,前往 UI 中的資源,確認 Terraform 已建立或更新這些資源。

授予服務帳戶存取權

將 Agent Platform 使用者和 Storage 物件檢視者角色授予連線的服務帳戶。如要授予角色,請按照下列步驟操作:

  1. 前往「IAM & Admin」(IAM 與管理) 頁面。

    前往「IAM & Admin」(IAM 與管理)

  2. 按一下「新增」圖示

    「新增主體」對話方塊隨即開啟。

  3. 在「新增主體」欄位,輸入先前複製的服務帳戶 ID。

  4. 在「選取角色」欄位中,依序選取「Vertex AI」和「Agent Platform 使用者」

  5. 按一下 [Add another role] (新增其他角色)

  6. 在「選取角色」欄位中,依序選取「Cloud Storage」和「Storage 物件檢視者」

  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 控制台的「Manage resources」(管理資源) 頁面。

    前往「Manage resources」(管理資源)

  2. 在專案清單中選取要刪除的專案,然後點選「Delete」(刪除)
  3. 在對話方塊中輸入專案 ID,然後按一下 [Shut down] (關閉) 以刪除專案。

刪除個別資源

如要重複使用專案,請刪除您為本教學課程建立的資源。

控制台

  1. 前往 BigQuery 頁面。

    前往「BigQuery」頁面

  2. 刪除 bqml_tutorial 資料集。刪除資料集也會一併刪除遠端模型。

    1. 在「Explorer」窗格中展開專案,然後按一下「Datasets」(資料集)

    2. 在「Datasets」(資料集) 清單中,按一下 bqml_tutorial 資料集。

    3. 在詳細資料窗格中,按一下 「刪除」

    4. 在「Delete dataset」(刪除資料集) 對話方塊中,按一下「Delete」(刪除)

  3. 刪除連結:

    1. 在「Explorer」窗格中展開專案,然後按一下「Connections」

    2. 在「連線 ID」清單中,按一下您建立的連線。

    3. 在詳細資料窗格中,按一下 「刪除」

    4. 在「Delete connection」(刪除連線) 對話方塊中輸入 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

後續步驟