Membuat teks menggunakan model Gemini dan fungsi AI.GENERATE_TEXT

Tutorial ini menunjukkan cara membuat model jarak jauh yang didasarkan pada model gemini-2.5-flash, dan cara menggunakan model tersebut dengan fungsi AI.GENERATE_TEXT untuk mengekstrak kata kunci dan melakukan analisis sentimen.

Biaya

Dalam dokumen ini, Anda akan menggunakan komponen Google Cloudyang dapat ditagih berikut:

  • 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.

Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda, gunakan kalkulator harga.

Pengguna Google Cloud baru mungkin memenuhi syarat untuk mendapatkan uji coba gratis.

Setelah menyelesaikan tugas yang dijelaskan dalam dokumen ini, Anda dapat menghindari penagihan berkelanjutan dengan menghapus resource yang Anda buat. Untuk mengetahui informasi selengkapnya, baca bagian Pembersihan.

Sebelum memulai

Konsol

  1. Login ke akun Google Cloud Anda. Jika Anda baru menggunakan Google Cloud, buat akun untuk mengevaluasi performa produk kami dalam skenario dunia nyata. Pelanggan baru juga mendapatkan kredit gratis senilai $300 untuk menjalankan, menguji, dan men-deploy workload.
  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. Enable the BigQuery, BigQuery Connection, and Vertex AI APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. 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

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

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

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  8. Pastikan Anda memiliki peran berikut di project: BigQuery Admin, Project IAM Admin

    Memeriksa peran

    1. Di konsol Google Cloud , buka halaman IAM.

      Buka IAM
    2. Pilih project.
    3. Di kolom Akun utama, temukan semua baris yang mengidentifikasi Anda atau grup yang Anda ikuti. Untuk mengetahui grup mana saja yang Anda ikuti, hubungi administrator Anda.

    4. Untuk semua baris yang menentukan atau menyertakan Anda, periksa kolom Peran untuk melihat apakah daftar peran menyertakan peran yang diperlukan.

    Memberikan peran

    1. Di konsol Google Cloud , buka halaman IAM.

      Buka IAM
    2. Pilih project.
    3. Klik Grant access.
    4. Di kolom New principals, masukkan ID pengguna Anda. Biasanya, ini adalah alamat email untuk Akun Google.

    5. Klik Pilih peran, lalu telusuri peran.
    6. Untuk memberikan peran tambahan, klik Add another role, lalu tambahkan tiap peran tambahan.
    7. Klik Simpan.

gcloud

  1. Login ke akun Google Cloud Anda. Jika Anda baru menggunakan Google Cloud, buat akun untuk mengevaluasi performa produk kami dalam skenario dunia nyata. Pelanggan baru juga mendapatkan kredit gratis senilai $300 untuk menjalankan, menguji, dan men-deploy workload.
  2. Instal Google Cloud CLI.

  3. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  4. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

    gcloud init
  5. Buat atau pilih Google Cloud project.

    Peran yang diperlukan untuk memilih atau membuat project

    • Pilih project: Memilih project tidak memerlukan peran IAM tertentu—Anda dapat memilih project mana pun yang telah diberi peran.
    • Membuat project: Untuk membuat project, Anda memerlukan peran Pembuat Project (roles/resourcemanager.projectCreator), yang berisi izin resourcemanager.projects.create. Pelajari cara memberikan peran.
    • Buat Google Cloud project:

      gcloud projects create PROJECT_ID

      Ganti PROJECT_ID dengan nama untuk Google Cloud project yang Anda buat.

    • Pilih project Google Cloud yang Anda buat:

      gcloud config set project PROJECT_ID

      Ganti PROJECT_ID dengan nama project Google Cloud Anda.

  6. Verifikasi bahwa penagihan diaktifkan untuk project Google Cloud Anda.

  7. Aktifkan BigQuery API, BigQuery Connection API, dan Vertex AI API:

    Peran yang diperlukan untuk mengaktifkan API

    Untuk mengaktifkan API, Anda memerlukan peran IAM Service Usage Admin (roles/serviceusage.serviceUsageAdmin), yang berisi izin serviceusage.services.enable. Pelajari cara memberikan peran.

    gcloud services enable bigquery.googleapis.com bigqueryconnection.googleapis.com aiplatform.googleapis.com
  8. Instal Google Cloud CLI.

  9. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  10. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

    gcloud init
  11. Buat atau pilih Google Cloud project.

    Peran yang diperlukan untuk memilih atau membuat project

    • Pilih project: Memilih project tidak memerlukan peran IAM tertentu—Anda dapat memilih project mana pun yang telah diberi peran.
    • Membuat project: Untuk membuat project, Anda memerlukan peran Pembuat Project (roles/resourcemanager.projectCreator), yang berisi izin resourcemanager.projects.create. Pelajari cara memberikan peran.
    • Buat Google Cloud project:

      gcloud projects create PROJECT_ID

      Ganti PROJECT_ID dengan nama untuk Google Cloud project yang Anda buat.

    • Pilih project Google Cloud yang Anda buat:

      gcloud config set project PROJECT_ID

      Ganti PROJECT_ID dengan nama project Google Cloud Anda.

  12. Verifikasi bahwa penagihan diaktifkan untuk project Google Cloud Anda.

  13. Aktifkan BigQuery API, BigQuery Connection API, dan Vertex AI API:

    Peran yang diperlukan untuk mengaktifkan API

    Untuk mengaktifkan API, Anda memerlukan peran IAM Service Usage Admin (roles/serviceusage.serviceUsageAdmin), yang berisi izin serviceusage.services.enable. Pelajari cara memberikan peran.

    gcloud services enable bigquery.googleapis.com bigqueryconnection.googleapis.com aiplatform.googleapis.com
  14. Memberikan peran ke akun pengguna Anda. Jalankan perintah berikut satu kali untuk setiap peran IAM berikut: roles/bigquery.admin, roles/resourcemanager.projectIamAdmin

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    Ganti kode berikut:

    • PROJECT_ID: Project ID Anda.
    • USER_IDENTIFIER: ID untuk akun pengguna Anda. Misalnya, myemail@example.com.
    • ROLE: Peran IAM yang Anda berikan ke akun pengguna Anda.

Membuat set data

Buat set data BigQuery untuk menyimpan model ML Anda.

Konsol

  1. Di konsol Google Cloud , buka halaman BigQuery.

    Buka halaman BigQuery

  2. Di panel Explorer, klik nama project Anda.

  3. Klik View actions > Create dataset.

  4. Di halaman Create dataset, lakukan hal berikut:

    • Untuk Dataset ID, masukkan bqml_tutorial.

    • Untuk Location type, pilih Multi-region, lalu pilih US.

    • Jangan ubah setelan default yang tersisa, lalu klik Create dataset.

bq

Untuk membuat set data baru, gunakan perintah bq mk --dataset.

  1. Buat set data bernama bqml_tutorial dengan lokasi data ditetapkan ke US.

    bq mk --dataset \
      --location=US \
      --description "BigQuery ML tutorial dataset." \
      bqml_tutorial
  2. Pastikan set data telah dibuat:

    bq ls

API

Panggil metode datasets.insert dengan resource set data yang ditentukan.

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

Membuat koneksi

Buat koneksi resource Cloud di multiregion US, tempat Anda membuat set data. Kemudian, dapatkan akun layanan koneksi.

Pilih salah satu opsi berikut:

Konsol

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel kiri, klik Explorer:

    Tombol yang ditandai untuk panel Explorer.

    Jika Anda tidak melihat panel kiri, klik Luaskan panel kiri untuk membuka panel.

  3. Di panel Explorer, luaskan nama project Anda, lalu klik Connections.

  4. Di halaman Koneksi, klik Buat koneksi.

  5. Untuk Connection type, pilih Vertex AI remote models, remote functions, BigLake and Spanner (Cloud Resource).

  6. Di kolom Connection ID, masukkan nama untuk koneksi Anda.

  7. Untuk Location type, pilih lokasi untuk koneksi Anda. Koneksi harus ditempatkan bersama resource Anda yang lain seperti set data.

  8. Klik Create connection.

  9. Klik Go to connection.

  10. Di panel Connection info, salin ID akun layanan untuk digunakan pada langkah berikutnya.

bq

  1. Di lingkungan command line, buat koneksi:

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

    Parameter --project_id akan mengganti project default.

    Ganti kode berikut:

    • REGION: region koneksi Anda
    • PROJECT_ID: Project ID Google Cloud Anda
    • CONNECTION_ID: ID untuk koneksi Anda

    Saat Anda membuat resource koneksi, BigQuery akan membuat akun layanan sistem unik dan mengaitkannya dengan koneksi.

    Pemecahan masalah: Jika Anda mendapatkan error koneksi berikut, update Google Cloud SDK:

    Flags parsing error: flag --connection_type=CLOUD_RESOURCE: value should be one of...
    
  2. Ambil dan salin ID akun layanan untuk digunakan pada langkah berikutnya:

    bq show --connection PROJECT_ID.REGION.CONNECTION_ID

    Outputnya mirip dengan hal berikut ini:

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

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Python API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Node.js API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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

Gunakan resource google_bigquery_connection.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Contoh berikut membuat koneksi resource Cloud bernama my_cloud_resource_connection di region US:


# 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 {}
}

Untuk menerapkan konfigurasi Terraform di project, selesaikan langkah-langkah di bagian berikut. Google Cloud

Menyiapkan Cloud Shell

  1. Luncurkan Cloud Shell.
  2. Tetapkan project Google Cloud default tempat Anda ingin menerapkan konfigurasi Terraform.

    Anda hanya perlu menjalankan perintah ini sekali per project, dan dapat dijalankan di direktori mana pun.

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    Variabel lingkungan akan diganti jika Anda menetapkan nilai eksplisit dalam file konfigurasi Terraform.

Menyiapkan direktori

Setiap file konfigurasi Terraform harus memiliki direktorinya sendiri (juga disebut modul root).

  1. Di Cloud Shell, buat direktori dan file baru di dalam direktori tersebut. Nama file harus memiliki ekstensi .tf—misalnya main.tf. Dalam tutorial ini, file ini disebut sebagai main.tf.
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. Jika mengikuti tutorial, Anda dapat menyalin kode contoh di setiap bagian atau langkah.

    Salin kode contoh ke dalam main.tf yang baru dibuat.

    Atau, salin kode dari GitHub. Tindakan ini direkomendasikan jika cuplikan Terraform adalah bagian dari solusi menyeluruh.

  3. Tinjau dan ubah contoh parameter untuk diterapkan pada lingkungan Anda.
  4. Simpan perubahan Anda.
  5. Lakukan inisialisasi Terraform. Anda hanya perlu melakukan ini sekali per direktori.
    terraform init

    Secara opsional, untuk menggunakan versi penyedia Google terbaru, sertakan opsi -upgrade:

    terraform init -upgrade

Menerapkan perubahan

  1. Tinjau konfigurasi dan pastikan resource yang akan dibuat atau diupdate oleh Terraform sesuai yang Anda inginkan:
    terraform plan

    Koreksi konfigurasi jika diperlukan.

  2. Terapkan konfigurasi Terraform dengan menjalankan perintah berikut dan memasukkan yes pada prompt:
    terraform apply

    Tunggu hingga Terraform menampilkan pesan "Apply complete!".

  3. Buka Google Cloud project Anda untuk melihat hasilnya. Di konsol Google Cloud , buka resource Anda di UI untuk memastikan bahwa Terraform telah membuat atau mengupdatenya.

Memberikan izin ke akun layanan koneksi

Berikan peran Vertex AI User ke akun layanan koneksi. Anda harus memberikan peran ini di project yang sama dengan yang Anda buat atau pilih di bagian Sebelum memulai. Memberikan peran dalam project yang berbeda akan menghasilkan error bqcx-1234567890-xxxx@gcp-sa-bigquery-condel.iam.gserviceaccount.com does not have the permission to access resource.

Untuk memberikan peran, ikuti langkah-langkah berikut:

  1. Buka halaman IAM & Admin.

    Buka IAM & Admin

  2. Klik Berikan Akses.

  3. Di kolom New principals, masukkan ID akun layanan yang Anda salin sebelumnya.

  4. Di kolom Pilih peran, pilih Vertex AI, lalu pilih Peran Pengguna Vertex AI.

  5. Klik Save.

Membuat model jarak jauh

Gunakan pernyataan CREATE MODEL untuk membuat model jarak jauh yang merepresentasikan model Vertex AI yang dihosting:

  1. Di konsol Google Cloud , buka halaman BigQuery.

    Buka BigQuery

  2. Di editor kueri, jalankan pernyataan berikut:

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

Ganti kode berikut:

  • LOCATION: lokasi koneksi
  • CONNECTION_ID: ID koneksi BigQuery Anda

    Saat Anda melihat detail koneksi di konsol Google Cloud , ini adalah nilai di bagian terakhir ID koneksi yang sepenuhnya memenuhi syarat yang ditampilkan di ID Koneksi, misalnya projects/myproject/locations/connection_location/connections/myconnection

Kueri memerlukan waktu beberapa detik untuk diselesaikan, setelah itu model gemini_model akan muncul di set data bqml_tutorial. Tidak ada hasil kueri.

Melakukan ekstraksi kata kunci

Lakukan ekstraksi kata kunci pada ulasan film IMDB dengan menggunakan model jarak jauh dan fungsi AI.GENERATE_TEXT:

  1. Di konsol Google Cloud , buka halaman BigQuery.

    Buka BigQuery

  2. Di editor kueri, masukkan pernyataan berikut untuk melakukan ekstraksi kata kunci pada lima ulasan film:

    SELECT
      title, result, review
    FROM
      AI.GENERATE_TEXT(
        MODEL `bqml_tutorial.gemini_model`,
        (
          SELECT
            CONCAT(
              """Extract a list of only 3 key words from this review.
                List only the key words, nothing else. Review: """,
                review) AS prompt,
            *
          FROM
            `bigquery-public-data.imdb.reviews`
          LIMIT 5
        ),
        STRUCT(
          0.2 AS temperature,
          100 AS max_output_tokens));

    Outputnya mirip dengan hal berikut ini:

    +--------------+------------------+----------------------------------------+
    | title        | result           | review                                 |
    +--------------+------------------+----------------------------------------+
    | The Guardian | * Costner        | Once again Mr. Costner has dragged out |
    |              | * Kutcher        | a movie for far longer than necessary. |
    |              | * Rescue         | Aside from the terrific sea rescue...  |
    |              |                  |                                        |
    | Trespass     | * Generic        | This is an example of why the majority |
    |              | * Waste          | of action films are the same. Generic  |
    |              | * Cinematography | and boring, there's really nothing...  |
    | ...          | ...              | ...                                    |
    +--------------+------------------+----------------------------------------+
    

Melakukan analisis sentimen

Lakukan analisis sentimen pada ulasan film IMDB menggunakan model jarak jauh dan fungsi AI.GENERATE_TEXT:

  1. Di konsol Google Cloud , buka halaman BigQuery.

    Buka BigQuery

  2. Di editor kueri, jalankan pernyataan berikut untuk melakukan analisis sentimen pada ulasan film:

    SELECT
      title, result, review
    FROM
      AI.GENERATE_TEXT(
        MODEL `bqml_tutorial.gemini_model`,
        (
          SELECT
            CONCAT(
              """Perform sentiment analysis on the following text and
                 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));

    Outputnya mirip dengan hal berikut ini:

    +----------+----------+------------------------------------------------+
    | title    | result   | review                                         |
    +----------+----------+------------------------------------------------+
    | Quitting | Positive | This movie is amazing because the fact that... |
    | Trespass | Negative | This is an example of why the majority of ...  |
    | ...      | ...      | ...                                            |
    +----------+----------+------------------------------------------------+
    

Pembersihan

Agar tidak perlu membayar biaya pada akun Google Cloud Anda untuk resource yang digunakan dalam tutorial ini, hapus project yang berisi resource tersebut, atau simpan project dan hapus setiap resource.

Menghapus project

    Menghapus Google Cloud project:

    gcloud projects delete PROJECT_ID

Menghapus resource satu per satu

Jika Anda ingin menggunakan kembali project, hapus resource yang Anda buat untuk tutorial.

Konsol

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Hapus set data bqml_tutorial. Menghapus set data juga akan menghapus model jarak jauh.

    1. Di panel Explorer, luaskan project Anda dan klik Set data

    2. Di daftar Set data, klik set data.

    3. Di panel detail, klik Hapus.

    4. Pada dialog Hapus set data, klik Hapus.

  3. Menghapus koneksi.

    1. Di panel Explorer, luaskan project Anda dan klik Connections.

    2. Di daftar Set data, klik koneksi.

    3. Di panel detail, klik Hapus.

    4. Di dialog Hapus koneksi, masukkan delete untuk mengonfirmasi penghapusan.

    5. Klik Hapus.

gcloud

  1. Hapus set data bqml_tutorial dan model jarak jauh.

    bq rm --dataset --recursive bqml_tutorial
    
  2. Menghapus koneksi.

    bq rm --connection PROJECT_ID.REGION.CONNECTION_ID
    

    Ganti kode berikut:

    • PROJECT_ID: Project ID Google Cloud Anda
    • REGION: region koneksi
    • CONNECTION_ID: ID koneksi

Langkah berikutnya