使用 Gemini 模型和 ML.GENERATE_TEXT 函式生成文字

本教學課程說明如何根據 gemini-2.0-flash 模型建立遠端模型,然後使用 ML.GENERATE_TEXT 函式,從 bigquery-public-data.imdb.reviews 公開資料表擷取電影評論中的關鍵字,並進行情緒分析。

必要的角色

如要執行本教學課程,您需要下列 Identity and Access Management (IAM) 角色:

  • 建立及使用 BigQuery 資料集、連線和模型: BigQuery 管理員 (roles/bigquery.admin)。
  • 將權限授予連線的服務帳戶:專案 IAM 管理員 (roles/resourcemanager.projectIamAdmin)。

這些預先定義的角色具備執行本文中工作所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

  • 建立資料集:bigquery.datasets.create
  • 建立、委派及使用連線: bigquery.connections.*
  • 設定預設連線:bigquery.config.*
  • 設定服務帳戶權限: resourcemanager.projects.getIamPolicyresourcemanager.projects.setIamPolicy
  • 建立模型並執行推論:
    • bigquery.jobs.create
    • bigquery.models.create
    • bigquery.models.getData
    • bigquery.models.updateData
    • bigquery.models.updateMetadata

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

費用

在本文件中,您會使用 Google Cloud的下列計費元件:

  • BigQuery ML: You incur costs for the data that you process in BigQuery.
  • Vertex AI: You incur costs for calls to the Vertex AI service that's represented by the remote model.

如要根據預測用量估算費用,請使用 Pricing Calculator 初次使用 Google Cloud 的使用者可能符合免費試用資格。

如要進一步瞭解 BigQuery 定價,請參閱 BigQuery 說明文件中的「BigQuery 定價」一文。

如要進一步瞭解 Vertex AI 定價,請參閱 Vertex AI 定價頁面。

事前準備

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

    Go to project selector

  2. Make sure that billing is enabled for your Google Cloud project.

  3. Enable the BigQuery, BigQuery Connection, and Vertex AI APIs.

    Enable the APIs

建立資料集

建立 BigQuery 資料集來儲存機器學習模型。

控制台

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

    前往 BigQuery 頁面

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

  3. 依序點按 「View actions」(查看動作) >「Create dataset」(建立資料集)

    「建立資料集」選單選項。

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

    • 在「Dataset ID」(資料集 ID) 中輸入 bqml_tutorial

    • 針對「Location type」(位置類型) 選取「Multi-region」(多區域),然後選取「US (multiple regions in United States)」(us (多個美國區域))

    • 其餘設定請保留預設狀態,然後按一下「Create dataset」(建立資料集)

bq

如要建立新的資料集,請使用 bq mk 指令搭配 --location 旗標。如需可能的完整參數清單,請參閱 bq mk --dataset 指令參考資料。

  1. 建立名為「bqml_tutorial」的資料集,並將資料位置設為「US」,以及說明設為「BigQuery ML tutorial dataset」:

    bq --location=US mk -d \
     --description "BigQuery ML tutorial dataset." \
     bqml_tutorial

    這個指令採用 -d 捷徑,而不是使用 --dataset 旗標。如果您省略 -d--dataset,該指令預設會建立資料集。

  2. 確認資料集已建立完成:

    bq ls

API

請呼叫 datasets.insert 方法,搭配已定義的資料集資源

{
  "datasetReference": {
     "datasetId": "bqml_tutorial"
  }
}

BigQuery DataFrames

在嘗試這個範例之前,請按照使用 BigQuery DataFrames 的 BigQuery 快速入門導覽課程中的 BigQuery DataFrames 設定說明操作。 詳情請參閱 BigQuery DataFrames 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定 ADC」。

import google.cloud.bigquery

bqclient = google.cloud.bigquery.Client()
bqclient.create_dataset("bqml_tutorial", exists_ok=True)

建立遠端模型

建立代表代管 Vertex AI 模型的遠端模型:

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

    前往 BigQuery

  2. 在查詢編輯器中執行下列陳述式:

CREATE OR REPLACE MODEL `bqml_tutorial.gemini_model`
  REMOTE WITH CONNECTION DEFAULT
  OPTIONS (ENDPOINT = 'gemini-2.0-flash');

查詢作業會在幾秒內完成,完成後,模型 gemini_model 會顯示在「Explorer」(探索工具) 窗格的 bqml_tutorial 資料集中。由於查詢是使用 CREATE MODEL 陳述式建立模型,因此不會有查詢結果。

執行關鍵字擷取作業

使用遠端模型和 ML.GENERATE_TEXT 函式,對 IMDB 電影評論執行關鍵字擷取作業:

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

    前往 BigQuery

  2. 在查詢編輯器中輸入下列陳述式,對五則電影評論執行關鍵字擷取作業:

    SELECT
      ml_generate_text_result['candidates'][0]['content'] AS generated_text,
      * EXCEPT (ml_generate_text_result)
    FROM
      ML.GENERATE_TEXT(
        MODEL `bqml_tutorial.gemini_model`,
        (
          SELECT
            CONCAT('Extract the key words from the text below: ', review) AS prompt,
            *
          FROM
            `bigquery-public-data.imdb.reviews`
          LIMIT 5
        ),
        STRUCT(
          0.2 AS temperature,
          100 AS max_output_tokens));

    輸出內容會與下列內容類似,為求清楚,我們省略了非產生的資料欄:

    +----------------------------------------+-------------------------+----------------------------+-----+
    | generated_text                         | ml_generate_text_status | prompt                     | ... |
    +----------------------------------------+-------------------------+----------------------------+-----+
    | {"parts":[{"text":"## Key words:\n\n*  |                         | Extract the key words from |     |
    | **Negative sentiment:** \"terribly     |                         | the text below: I had to   |     |
    | bad acting\", \"dumb story\", \"not    |                         | see this on the British    |     |
    | even a kid would enjoy this\",         |                         | Airways plane. It was      |     |
    | \"something to switch off\"\n*         |                         | terribly bad acting and    |     |
    | **Context:** \"British Airways plane\" |                         | a dumb story. Not even     |     |
    | \n* **Genre:** \"movie\" (implied)...  |                         | a kid would enjoy this...  |     |
    +----------------------------------------+-------------------------+----------------------------+-----+
    | {"parts":[{"text":"## Key words:\n\n*  |                         | Extract the key words from |     |
    | **Movie:** The Real Howard Spitz\n*    |                         | the text below: This is    |     |
    | **Genre:** Family movie\n*             |                         | a family movie that was    |     |
    | **Broadcast:** ITV station, 1.00 am\n* |                         | broadcast on my local      |     |
    | **Director:** Vadim Jean\n*            |                         | ITV station at 1.00 am a   |     |
    | **Main character:** Howard Spitz,      |                         | couple of nights ago.      |     |
    | a children's author who hates...       |                         | This might be a strange... |     |
    +----------------------------------------+-------------------------+----------------------------+-----+
    

    結果包含下列資料欄:

    • generated_text:生成的文字。
    • ml_generate_text_status:對應資料列的 API 回應狀態。如果作業成功,這個值會留空。
    • prompt:用於情緒分析的提示。
    • bigquery-public-data.imdb.reviews 資料表中的所有資料欄。
  3. 選用:您不必像上一個步驟一樣手動剖析函式傳回的 JSON,而是使用 flatten_json_output 引數,在不同資料欄中傳回產生的文字和安全性屬性。

    在查詢編輯器中執行下列陳述式:

    SELECT
      *
    FROM
      ML.GENERATE_TEXT(
        MODEL `bqml_tutorial.gemini_model`,
        (
          SELECT
            CONCAT('Extract the key words from the text below: ', review) AS prompt,
            *
          FROM
            `bigquery-public-data.imdb.reviews`
          LIMIT 5
        ),
        STRUCT(
          0.2 AS temperature,
          100 AS max_output_tokens,
          TRUE AS flatten_json_output));

    輸出內容會與下列內容類似,為求清楚,我們省略了非產生的資料欄:

    +----------------------------------------+----------------------------------------------+-------------------------+----------------------------+-----+
    | ml_generate_text_llm_result            | ml_generate_text_rai_result                  | ml_generate_text_status | prompt                     | ... |
    +----------------------------------------+----------------------------------------------+-------------------------+----------------------------+-----+
    | ## Keywords:                           |                                              |                         | Extract the key words from |     |
    |                                        |                                              |                         | the text below: I had to   |     |
    | * **Negative sentiment:**              |                                              |                         | see this on the British    |     |
    | "terribly bad acting", "dumb           |                                              |                         | Airways plane. It was      |     |
    | story", "not even a kid would          |                                              |                         | terribly bad acting and    |     |
    | enjoy this", "switch off"              |                                              |                         | a dumb story. Not even     |     |
    | * **Context:** "British                |                                              |                         | a kid would enjoy this...  |     |
    +----------------------------------------+----------------------------------------------+-------------------------+----------------------------+-----+
    | ## Key words:                          |                                              |                         | Extract the key words from |     |
    |                                        |                                              |                         | the text below: This is    |     |
    | * **Movie:** The Real Howard Spitz     |                                              |                         | a family movie that was    |     |
    | * **Genre:** Family movie              |                                              |                         | broadcast on my local      |     |
    | * **Broadcast:** ITV, 1.00             |                                              |                         | ITV station at 1.00 am a   |     |
    | am                                     |                                              |                         | couple of nights ago.      |     |
    | - ...                                  |                                              |                         | This might be a strange... |     |
    +----------------------------------------+----------------------------------------------+-------------------------+----------------------------+-----+
    

    結果包含下列資料欄:

    • ml_generate_text_llm_result:生成的文字。
    • ml_generate_text_rai_result:安全屬性,以及內容是否因其中一個封鎖類別而遭封鎖的相關資訊。如要進一步瞭解安全屬性,請參閱「設定安全篩選機制」。
    • ml_generate_text_status:對應資料列的 API 回應狀態。如果作業成功,這個值會留空。
    • prompt:用於關鍵字擷取的提示。
    • bigquery-public-data.imdb.reviews 資料表中的所有資料欄。

執行情緒分析

使用遠端模型和 ML.GENERATE_TEXT 函式,對 IMDB 電影評論執行情緒分析:

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

    前往 BigQuery

  2. 在查詢編輯器中執行下列陳述式,對五則電影評論進行情緒分析:

    SELECT
      ml_generate_text_result['candidates'][0]['content'] AS generated_text,
      * EXCEPT (ml_generate_text_result)
    FROM
      ML.GENERATE_TEXT(
        MODEL `bqml_tutorial.gemini_model`,
        (
          SELECT
            CONCAT(
              'perform sentiment analysis on the following text, return one the following categories: positive, negative: ',
              review) AS prompt,
            *
          FROM
            `bigquery-public-data.imdb.reviews`
          LIMIT 5
        ),
        STRUCT(
          0.2 AS temperature,
          100 AS max_output_tokens));

    輸出內容會與下列內容類似,為求清楚,我們省略了非產生的資料欄:

    +--------------------------------------------+-------------------------+----------------------------+-----+
    | generated_text                             | ml_generate_text_status | prompt                     | ... |
    +--------------------------------------------+-------------------------+----------------------------+-----+
    | {"parts":[{"text":"## Sentiment Analysis:  |                         | perform sentiment analysis |     |
    | Negative \n\nThis text expresses a         |                         | on the following text,     |     |
    | strongly negative sentiment towards the    |                         | return one the following   |     |
    | movie. Here's why:\n\n* **Negative         |                         | negative: I  had to see    |     |
    | like \"terribly,\" \"dumb,\" and           |                         | this on the British        |     |
    | \"not even\" to describe the acting...     |                         | Airways plane. It was...   |     |
    +--------------------------------------------+-------------------------+----------------------------+-----+
    | {"parts":[{"text":"## Sentiment Analysis:  |                         | perform sentiment analysis |     |
    | Negative \n\nThis review expresses a       |                         | on the following text,     |     |
    | predominantly negative sentiment towards   |                         | return one the following   |     |
    | the movie \"The Real Howard Spitz.\"       |                         | categories: positive,      |     |
    | Here's why:\n\n* **Criticism of the film's |                         | negative: This is a family |     |
    | premise:** The reviewer finds it strange   |                         | movie that was broadcast   |     |
    | that a film about a children's author...   |                         | on my local ITV station... |     |
    +--------------------------------------------+-------------------------+----------------------------+-----+
    

    結果包含與「執行關鍵字擷取作業」一節所述相同的資料欄。

清除所用資源

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.