יצירת טקסט באמצעות מודל Gemini והפונקציה AI.GENERATE_TEXT

במדריך הזה נסביר איך ליצור מודל מרוחק שמבוסס על מודל gemini-2.5-flash, ואז איך להשתמש במודל הזה עם הפונקציה AI.GENERATE_TEXT כדי לחלץ מילות מפתח מביקורות על סרטים מbigquery-public-data.imdb.reviews הטבלה הציבורית ולבצע ניתוח סנטימנטים.

התפקידים הנדרשים

כדי להפעיל את המדריך הזה, אתם צריכים את התפקידים הבאים בניהול הזהויות והרשאות הגישה (IAM):

  • יצירה ושימוש במערכי נתונים, בחיבורים ובמודלים של BigQuery: אדמין של BigQuery‏ (roles/bigquery.admin).
  • נותנים הרשאות לחשבון השירות של החיבור: אדמין IAM של פרויקט (roles/resourcemanager.projectIamAdmin).

התפקידים המוגדרים מראש האלה כוללים את ההרשאות שנדרשות לביצוע המשימות שמתוארות במסמך הזה. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:

ההרשאות הנדרשות

  • יצירת מערך נתונים: bigquery.datasets.create
  • יצירה, הקצאה ושימוש בחיבור: bigquery.connections.*
  • הגדרת החיבור המוגדר כברירת מחדל: bigquery.config.*
  • מגדירים את ההרשאות לחשבון השירות: resourcemanager.projects.getIamPolicy ו- resourcemanager.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.

    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

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

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

יצירת מערך נתונים

יוצרים מערך נתונים ב-BigQuery לאחסון מודל ה-ML.

המסוף

  1. במסוף Google Cloud , עוברים לדף BigQuery.

    לדף BigQuery

  2. בחלונית Explorer, לוחצים על שם הפרויקט.

  3. לוחצים על הצגת פעולות > יצירת מערך נתונים.

  4. בדף Create dataset, מבצעים את הפעולות הבאות:

    • בשדה Dataset ID (מזהה מערך הנתונים), מזינים bqml_tutorial.

    • בקטע Location type, בוחרים באפשרות במספר אזורים ואז באפשרות US (multiple regions in United States).

    • משאירים את שאר הגדרות ברירת המחדל כמו שהן ולוחצים על 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

    במקום להשתמש בדגל --dataset, הפקודה משתמשת בקיצור הדרך -d. אם לא מציינים את -d ואת --dataset, ברירת המחדל של הפקודה היא יצירת מערך נתונים.

  2. בודקים שמערך הנתונים נוצר:

    bq ls

API

מבצעים קריאה לשיטה datasets.insert עם משאב מוגדר של מערך נתונים.

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

יצירת חיבור

יוצרים חיבור למשאב בענן ומקבלים את חשבון השירות של החיבור. יוצרים את החיבור באותו מיקום של מערך הנתונים שיצרתם בשלב הקודם.

אם כבר הגדרתם חיבור ברירת מחדל או שיש לכם את תפקיד האדמין ב-BigQuery, אתם יכולים לדלג על השלב הזה.

בוחרים באחת מהאפשרויות הבאות:

המסוף

  1. עוברים לדף BigQuery.

    כניסה ל-BigQuery

  2. בחלונית השמאלית, לוחצים על Explorer:

    כפתור מודגש לחלונית הסייר.

    אם החלונית הימנית לא מוצגת, לוחצים על הרחבת החלונית הימנית כדי לפתוח אותה.

  3. בחלונית Explorer מרחיבים את שם הפרויקט ואז לוחצים על Connections.

  4. בדף Connections (חיבורים), לוחצים על Create connection (יצירת חיבור).

  5. בקטע Connection type (סוג החיבור), בוחרים באפשרות Vertex AI remote models, remote functions, BigLake and Spanner (Cloud Resource) (מודלים מרוחקים של Vertex AI, פונקציות מרוחקות, BigLake ו-Spanner (משאב בענן)).

  6. בשדה מזהה החיבור, מזינים שם לחיבור.

  7. בקטע Location type, בוחרים מיקום לחיבור. החיבור צריך להיות ממוקם יחד עם המשאבים האחרים שלכם, כמו מערכי נתונים.

  8. לוחצים על יצירת קישור.

  9. לוחצים על מעבר לחיבור.

  10. בחלונית Connection info (פרטי התחברות), מעתיקים את מזהה חשבון השירות כדי להשתמש בו בשלב מאוחר יותר.

BQ

  1. בסביבת שורת פקודה, יוצרים חיבור:

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

    הפרמטר --project_id מבטל את פרויקט ברירת המחדל.

    מחליפים את מה שכתוב בשדות הבאים:

    • REGION: אזור החיבור
    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
    • CONNECTION_ID: מזהה לחיבור

    כשיוצרים משאב חיבור, מערכת BigQuery יוצרת חשבון שירות ייחודי ומקשרת אותו לחיבור.

    פתרון בעיות: אם מופיעה שגיאת החיבור הבאה, צריך לעדכן את Google Cloud SDK:

    Flags parsing error: flag --connection_type=CLOUD_RESOURCE: value should be one of...
    
  2. מאחזרים ומעתיקים את מזהה חשבון השירות כדי להשתמש בו בשלב מאוחר יותר:

    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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Python API.

כדי לבצע אימות ב-BigQuery, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsהוראות ההגדרה שבמדריך למתחילים של BigQuery באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של BigQuery Node.js API.

כדי לבצע אימות ב-BigQuery, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

בדוגמה הבאה נוצר חיבור למשאב Cloud בשם my_cloud_resource_connection באזור 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 {}
}

כדי להחיל את ההגדרות של Terraform בפרויקט ב- Google Cloud , מבצעים את השלבים בקטעים הבאים.

הכנת 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

    אופציונלי: תוכלו לכלול את האפשרות -upgrade, כדי להשתמש בגרסה העדכנית ביותר של הספק של Google:

    terraform init -upgrade

החלה של השינויים

  1. בודקים את ההגדרות ומוודאים שהמשאבים שמערכת Terraform תיצור או תעדכן תואמים לציפיות שלכם:
    terraform plan

    מתקנים את ההגדרות לפי הצורך.

  2. מריצים את הפקודה הבאה ומזינים yes בהודעה שמופיעה, כדי להחיל את הגדרות Terraform:
    terraform apply

    ממתינים עד שב-Terraform תוצג ההודעה "Apply complete!‎".

  3. פותחים את Google Cloud הפרויקט כדי לראות את התוצאות. במסוף Google Cloud , נכנסים למשאבים בממשק המשתמש כדי לוודא שהם נוצרו או עודכנו ב-Terraform.

מתן הרשאות לחשבון השירות של החיבור

מקצים לחשבון השירות של החיבור את התפקיד Vertex AI User. צריך להעניק את התפקיד הזה באותו פרויקט שיצרתם או בחרתם בקטע לפני שמתחילים. הקצאת התפקיד בפרויקט אחר מובילה לשגיאה bqcx-1234567890-xxxx@gcp-sa-bigquery-condel.iam.gserviceaccount.com does not have the permission to access resource.

כדי להקצות את התפקיד, בצע את השלבים הבאים:

  1. עוברים לדף IAM & Admin.

    כניסה לדף IAM & Admin

  2. לוחצים על Grant Access.

  3. בשדה New principals, מזינים את מזהה חשבון השירות שהעתקתם קודם.

  4. בשדה Select a role (בחירת תפקיד), בוחרים באפשרות Vertex AI ואז בוחרים באפשרות Vertex AI User role (תפקיד משתמש ב-Vertex AI).

  5. לוחצים על Save.

יצירת המודל המרוחק

יוצרים מודל מרוחק שמייצג מודל מתארח של Vertex AI:

  1. במסוף Google Cloud , עוברים לדף BigQuery.

    כניסה ל-BigQuery

  2. בעורך השאילתות, מריצים את ההצהרה הבאה:

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

מחליפים את מה שכתוב בשדות הבאים:

  • LOCATION: מיקום החיבור
  • CONNECTION_ID: המזהה של החיבור ל-BigQuery

    כשמציגים את פרטי החיבור במסוף Google Cloud , זה הערך בקטע האחרון של מזהה החיבור המלא שמוצג במזהה החיבור, לדוגמה projects/myproject/locations/connection_location/connections/myconnection

השאילתה מסתיימת אחרי כמה שניות, ואז המודל gemini_model מופיע במערך הנתונים bqml_tutorial. מכיוון שהשאילתה משתמשת בהצהרה CREATE MODEL כדי ליצור מודל, אין תוצאות לשאילתה.

ביצוע חילוץ מילות מפתח

בצע חילוץ של מילות מפתח מביקורות על סרטים ב-IMDB באמצעות המודל המרוחק והפונקציה AI.GENERATE_TEXT:

  1. במסוף Google Cloud , עוברים לדף BigQuery.

    כניסה ל-BigQuery

  2. בעורך השאילתות, מזינים את ההצהרה הבאה כדי לבצע חילוץ של מילות מפתח מתוך חמש ביקורות על סרטים:

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

    הפלט אמור להיראות כך:

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

ביצוע ניתוח סנטימנטים

תבצע ניתוח סנטימנטים של ביקורות על סרטים ב-IMDB באמצעות המודל המרוחק והפונקציה AI.GENERATE_TEXT:

  1. במסוף Google Cloud , עוברים לדף BigQuery.

    כניסה ל-BigQuery

  2. בעורך השאילתות, מריצים את ההצהרה הבאה כדי לבצע ניתוח סנטימנטים של ביקורות על סרטים:

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

    הפלט אמור להיראות כך:

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

הסרת המשאבים

  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.