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.

料金計算ツールを使うと、予想使用量に基づいて費用の見積もりを生成できます。 新規の 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

データセットを作成する

ML モデルを保存する BigQuery データセットを作成します。

コンソール

  1. Google Cloud コンソールで、[BigQuery] ページに移動します。

    [BigQuery] ページに移動

  2. [エクスプローラ] ペインで、プロジェクト名をクリックします。

  3. [アクションを表示] > [データセットを作成] をクリックします。

    [データセットを作成] のメニュー オプション。

  4. [データセットを作成] ページで、次の操作を行います。

    • [データセット ID] に「bqml_tutorial」と入力します。

    • [ロケーション タイプ] で [マルチリージョン] を選択してから、[US(米国の複数のリージョン)] を選択します。

    • 残りのデフォルトの設定は変更せず、[データセットを作成] をクリックします。

bq

新しいデータセットを作成するには、--location フラグを指定した bq mk コマンドを使用します。使用可能なパラメータの一覧については、bq mk --dataset コマンドのリファレンスをご覧ください。

  1. データの場所が US に設定され、BigQuery ML tutorial dataset という説明の付いた、bqml_tutorial という名前のデータセットを作成します。

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

    このコマンドでは、--dataset フラグの代わりに -d ショートカットを使用しています。-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 が [エクスプローラ] ペインの bqml_tutorial データセットに表示されます。クエリは CREATE MODEL ステートメントを使用してモデルを作成するため、クエリの結果はありません。

キーワード抽出を行う

リモートモデルと ML.GENERATE_TEXT 関数を使用して、IMDB 映画レビューに対してキーワード抽出を行います。

  1. Google Cloud コンソールで、[BigQuery] ページに移動します。

    [BigQuery] に移動

  2. クエリエディタで次のステートメントを入力して、5 つの映画レビューでキーワード抽出を行います。

    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. クエリエディタで次のステートメントを実行して、5 つの映画レビューの感情分析を行います。

    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.