Buat teks menggunakan model Gemini dan fungsi ML.GENERATE_TEXT

Tutorial ini menunjukkan cara membuat model jarak jauh yang didasarkan pada model gemini-1.0-pro-002, lalu cara menggunakan model tersebut dengan fungsi ML.GENERATE_TEXT untuk mengekstrak kata kunci dan melakukan analisis sentimen pada ulasan film dari tabel publik bigquery-public-data.imdb.reviews.

Izin yang diperlukan

  • Untuk membuat set data, Anda memerlukan izin Identity and Access Management (IAM) bigquery.datasets.create.
  • Untuk membuat resource koneksi, Anda memerlukan izin IAM berikut:

    • bigquery.connections.create
    • bigquery.connections.get
  • Untuk memberikan izin ke akun layanan koneksi, Anda memerlukan izin berikut:

    • resourcemanager.projects.setIamPolicy
  • Untuk membuat model, Anda memerlukan izin berikut:

    • bigquery.jobs.create
    • bigquery.models.create
    • bigquery.models.getData
    • bigquery.models.updateData
    • bigquery.connections.delegate
  • Untuk menjalankan inferensi, Anda memerlukan izin berikut:

    • bigquery.models.getData
    • bigquery.jobs.create

Biaya

Dalam dokumen ini, Anda menggunakan komponen Google Cloud yang 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 baru Google Cloud mungkin memenuhi syarat untuk mendapatkan uji coba gratis.

Untuk mengetahui informasi selengkapnya tentang harga BigQuery, lihat harga BigQuery dalam dokumentasi BigQuery.

Untuk mengetahui informasi selengkapnya tentang harga Vertex AI, lihat halaman harga Vertex AI.

Sebelum memulai

  1. Di konsol Google Cloud, pada halaman pemilih project, pilih atau buat project Google Cloud.

    Buka pemilih project

  2. Pastikan penagihan telah diaktifkan untuk project Google Cloud Anda.

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

    Enable the APIs

Membuat set data

Buat set data BigQuery untuk menyimpan model ML Anda:

  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.

    Buat set data.

  4. Di halaman Create dataset, lakukan hal berikut:

    • Untuk Dataset ID, masukkan bqml_tutorial.

    • Untuk Location type, pilih Multi-region, lalu pilih US (multiple regions in United States).

      Set data publik disimpan di US multi-region. Untuk mempermudah, simpan set data Anda di lokasi yang sama.

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

      Halaman Create dataset.

Membuat koneksi

Buat koneksi resource Cloud dan dapatkan akun layanan koneksi. Buat koneksi di lokasi yang sama dengan set data yang Anda buat di langkah sebelumnya.

Pilih salah satu opsi berikut:

Konsol

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Untuk membuat koneksi, klik Add, lalu klik Connections to external data sources.

  3. Dalam daftar Connection type, pilih Vertex AI remote models, remote functions and BigLake (Cloud Resource).

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

  5. Klik Create connection.

  6. Klik Go to connection.

  7. Di panel Connection info, salin ID akun layanan untuk digunakan di 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 mengalami 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 di 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"}
    

Terraform

Tambahkan bagian berikut ke dalam file main.tf Anda.

 ## This creates a cloud resource connection.
 ## Note: The cloud resource nested object has only one output only field - serviceAccountId.
 resource "google_bigquery_connection" "connection" {
    connection_id = "CONNECTION_ID"
    project = "PROJECT_ID"
    location = "REGION"
    cloud_resource {}
}        
Ganti opsi berikut:

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

Memberikan izin ke akun layanan koneksi

Untuk memberikan peran yang sesuai kepada akun layanan koneksi agar dapat mengakses layanan Vertex AI, 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

Buat 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-1.0-pro-002');

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 Connection ID, 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 di panel Explorer. Karena kueri menggunakan pernyataan CREATE MODEL untuk membuat model, tidak akan ada hasil kueri.

Melakukan ekstraksi kata kunci

Lakukan ekstraksi kata kunci pada ulasan film IMDB dengan menggunakan model jarak jauh dan fungsi ML.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
      ml_generate_text_result['candidates'][0]['content'] AS generated_text,
      ml_generate_text_result['candidates'][0]['safety_ratings']
        AS safety_ratings,
      * 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));
    

    Outputnya mirip dengan yang berikut, dengan kolom yang tidak dihasilkan dihilangkan agar lebih jelas:

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

    Hasilnya mencakup kolom berikut:

    • generated_text: teks yang dihasilkan.
    • safety_ratings: atribut keamanan, beserta informasi tentang apakah konten diblokir karena salah satu kategori pemblokiran. Untuk mengetahui informasi selengkapnya tentang atribut keamanan, lihat Vertex PaLM API.
    • ml_generate_text_status: status respons API untuk baris yang sesuai. Jika operasi berhasil, nilai ini akan kosong.
    • prompt: prompt yang digunakan untuk analisis sentimen.
    • Semua kolom dari tabel bigquery-public-data.imdb.reviews.
  3. Opsional: Daripada mengurai JSON yang ditampilkan oleh fungsi secara manual, seperti yang Anda lakukan di langkah sebelumnya, gunakan argumen flatten_json_output untuk menampilkan teks yang dihasilkan dan atribut keamanan dalam kolom terpisah.

    Di editor kueri, jalankan pernyataan berikut:

    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));
    

    Outputnya mirip dengan yang berikut, dengan kolom yang tidak dihasilkan dihilangkan agar lebih jelas:

    +----------------------------------------+----------------------------------------------+-------------------------+----------------------------+-----+
    | ml_generate_text_llm_result            | ml_generate_text_rai_result                  | ml_generate_text_status | prompt                     | ... |
    +----------------------------------------+----------------------------------------------+-------------------------+----------------------------+-----+
    | ## Keywords:                           | [{"category":1,"probability":1,              |                         | Extract the key words from |     |
    |                                        | "probability_score":0.29391089,"severity":1, |                         | the text below: I had to   |     |
    | * **Negative sentiment:**              | "severity_score":0.15584777},{"category":2,  |                         | see this on the British    |     |
    | "terribly bad acting", "dumb           | "probability":1,"probability_score":         |                         | Airways plane. It was      |     |
    | story", "not even a kid would          | 0.061311536,"severity":1,"severity_score":   |                         | terribly bad acting and    |     |
    | enjoy this", "switch off"              | 0.10320505},{"category":3,"probability":2,   |                         | a dumb story. Not even     |     |
    | * **Context:** "British                | "probability_score":0.60340...               |                         | a kid would enjoy this...  |     |
    +----------------------------------------+----------------------------------------------+-------------------------+----------------------------+-----+
    | ## Key words:                          | [{"category":1,"probability":1,              |                         | Extract the key words from |     |
    |                                        | "probability_score":0.16968086,"severity":1, |                         | the text below: This is    |     |
    | * **Movie:** The Real Howard Spitz     | "severity_score":0.13386749},{"category":2,  |                         | a family movie that was    |     |
    | * **Genre:** Family movie              | "probability":1,"probability_score":         |                         | broadcast on my local      |     |
    | * **Broadcast:** ITV, 1.00             | 0.14841709,"severity":1,"severity_score":    |                         | ITV station at 1.00 am a   |     |
    | am                                     | 0.062674366},{"category":3,"probability":1,  |                         | couple of nights ago.      |     |
    | - ...                                  | "probability_score":0.38116196,...           |                         | This might be a strange... |     |
    +----------------------------------------+----------------------------------------------+-------------------------+----------------------------+-----+
    

    Hasilnya mencakup kolom berikut:

    • ml_generate_text_llm_result: teks yang dihasilkan.
    • ml_generate_text_rai_result: atribut keamanan, beserta informasi tentang apakah konten diblokir karena salah satu kategori pemblokiran. Untuk mengetahui informasi selengkapnya tentang atribut keamanan, lihat Vertex PaLM API.
    • ml_generate_text_status: status respons API untuk baris yang sesuai. Jika operasi berhasil, nilai ini akan kosong.
    • prompt: perintah yang digunakan untuk ekstraksi kata kunci.
    • Semua kolom dari tabel bigquery-public-data.imdb.reviews.

Melakukan analisis sentimen

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

  1. Di konsol Google Cloud, buka halaman BigQuery.

    Buka BigQuery

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

    SELECT
      ml_generate_text_result['candidates'][0]['content'] AS generated_text,
      ml_generate_text_result['candidates'][0]['safety_ratings']
        AS safety_ratings,
      * 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));
    

    Outputnya mirip dengan yang berikut, dengan kolom yang tidak dihasilkan dihilangkan agar lebih jelas:

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

    Hasilnya mencakup kolom yang sama dengan yang didokumentasikan untuk Melakukan ekstraksi kata kunci.

Pembersihan

  1. Di konsol Google Cloud, buka halaman Manage resource.

    Buka Manage resource

  2. Pada daftar project, pilih project yang ingin Anda hapus, lalu klik Delete.
  3. Pada dialog, ketik project ID, lalu klik Shut down untuk menghapus project.