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

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

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

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

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

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

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

  • יצירת מערך נתונים: bigquery.datasets.create
  • יצירה, הקצאה ושימוש בחיבור: bigquery.connections.*
  • הגדרת החיבור המוגדר כברירת מחדל: bigquery.config.*
  • מגדירים את ההרשאות לחשבון השירות: resourcemanager.projects.getIamPolicy ו- resourcemanager.projects.setIamPolicy
  • פריסה וביטול פריסה של מודל Vertex AI:
    • aiplatform.endpoints.deploy
    • aiplatform.endpoints.undeploy
  • יצירת מודל והרצת הסקה:
    • 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 model that's represented by the remote model.

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

יכול להיות שמשתמשים חדשים ב- Google Cloud זכאים לתקופת ניסיון בחינם.

מידע נוסף על התמחור של BigQuery זמין במאמר תמחור ב-BigQuery במסמכי התיעוד של BigQuery.

מודלים פתוחים שפורסים ב-Vertex AI מחויבים לפי שעת מכונה. המשמעות היא שהחיוב מתחיל ברגע שנקודת הקצה מוגדרת במלואה, וממשיך עד שמבטלים את הפריסה שלה. מידע נוסף על התמחור של 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"
  }
}

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

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

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

    כניסה ל-BigQuery

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

CREATE OR REPLACE MODEL `bqml_tutorial.gemma_model`
  REMOTE WITH CONNECTION DEFAULT
  OPTIONS (
    MODEL_GARDEN_MODEL_NAME = 'publishers/google/models/gemma3@gemma-3-270m-it',
    MACHINE_TYPE = 'g2-standard-12'
  );

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

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

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

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

    כניסה ל-BigQuery

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

    -- This function takes your instruction and wraps it with chat template for
    -- better output quality.
    -- This is usually the recommended way when using Gemma instruction-tuned models.
    CREATE TEMP FUNCTION FormatPromptWithChatTemplate(user_instruction STRING) AS (
      CONCAT(
        '<start_of_turn>user\n',
        user_instruction,
        '<end_of_turn>\n<start_of_turn>model\n'
      )
    );
    
    SELECT
      *
    FROM
      AI.GENERATE_TEXT(
        MODEL `bqml_tutorial.gemma_model`,
        (
          SELECT
            FormatPromptWithChatTemplate(
              'Extract the key words from the movie review below: ' || review)
              AS prompt,
            *
          FROM
            `bigquery-public-data.imdb.reviews`
          LIMIT 10
        ),
        STRUCT(
          0.2 AS temperature,
          100 AS max_output_tokens));

    מידע נוסף על שימוש בתבניות צ'אט עם Gemma זמין במאמר בנושא הוראות מערכת ועיצוב ב-Gemma.

    הפלט אמור להיראות כך, בלי העמודות שלא נוצרו לשם הבהרה:

    +----------------------------------------------+-------------------------+-----------------------------+-----+
    | result                                       | status                  | prompt                      | ... |
    +----------------------------------------------+-------------------------------------------------------+-----+
    | Here are some key words from the             |                         | <start_of_turn>user         |     |
    | movie review: * **Romance:**                 |                         | Extract the key words from  |     |
    | "romantic tryst," "elope" * **Comedy:**      |                         | the movie review below:     |     |
    | "Contrived Comedy" * **Burglary:**           |                         | Linda Arvidson (as Jennie)  |     |
    | "burglar," "rob," "booty" * **Chase:**       |                         | and Harry Solter (as Frank) |     |
    | "chases," "escape" * **Director:** "D.W.     |                         | are enjoying a romantic     |     |
    | Griffith" * **Actors:** "Linda Arvidson,"... |                         | tryst, when in walks her... |     |
    +----------------------------------------------+-------------------------+-----------------------------+-----+
    | Here are some key words from the             |                         | <start_of_turn>user         |     |
    | movie review: * **Elderbush Gilch:** The     |                         | Extract the key words from  |     |
    | name of the movie being reviewed. *          |                         | the movie review below:     |     |
    | **Disappointment:** The reviewer's           |                         | This is the second addition |     |
    | overall feeling about the film. *            |                         | to Frank Baum's personally  |     |
    | **Dim-witted:** Describes the story          |                         | produced trilogy of Oz      |     |
    | line negatively. * **Moronic, sadistic,...   |                         | films. It's essentially ... |     |
    +----------------------------------------------+-------------------------+-----------------------------+-----+
    

    התוצאות כוללות את העמודות הבאות:

    • result: הטקסט שנוצר.
    • status: סטטוס התגובה מה-API בשורה המתאימה. אם הפעולה בוצעה בהצלחה, הערך הזה יהיה ריק.
    • prompt: ההנחיה שמשמשת לניתוח הסנטימנטים.
    • כל העמודות מהטבלה bigquery-public-data.imdb.reviews.

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

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

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

    כניסה ל-BigQuery

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

    -- This function takes your instruction and wraps it with chat template for
    -- better output quality.
    -- This is usually the recommended way when using Gemma instruction-tuned models.
    CREATE TEMP FUNCTION FormatPromptWithChatTemplate(user_instruction STRING) AS (
      CONCAT(
        '<start_of_turn>user\n',
        user_instruction,
        '<end_of_turn>\n<start_of_turn>model\n'
      )
    );
    
    SELECT
      *
    FROM
      AI.GENERATE_TEXT(
        MODEL `bqml_tutorial.gemma_model`,
        (
          SELECT
            FormatPromptWithChatTemplate(
              'Analyze the sentiment of the following movie review and classify it as either POSITIVE or NEGATIVE. \nMovie Review: '
              || review) AS prompt,
            *
          FROM
            `bigquery-public-data.imdb.reviews`
          LIMIT 10
        ),
        STRUCT(
          0.2 AS temperature,
          128 AS max_output_tokens));

    מידע נוסף על שימוש בתבניות צ'אט עם Gemma זמין במאמר בנושא הוראות מערכת ועיצוב ב-Gemma.

    הפלט אמור להיראות כך, בלי העמודות שלא נוצרו לשם הבהרה:

    +-----------------------------+-------------------------+-----------------------------+-----+
    | result                      | status                  | prompt                      | ... |
    +-----------------------------+-------------------------------------------------------+-----+
    | **NEGATIVE**                |                         | <start_of_turn>user         |     |
    |                             |                         | Analyze the sentiment of    |     |
    |                             |                         | movie review and classify   |     |
    |                             |                         | it as either POSITIVE or    |     |
    |                             |                         | NEGATIVE. Movie Review:     |     |
    |                             |                         | Although Charlie Chaplin    |     |
    |                             |                         | made some great short       |     |
    |                             |                         | comedies in the late...     |     |
    +-----------------------------+-------------------------+-----------------------------+-----+
    | **NEGATIVE**                |                         | <start_of_turn>user         |     |
    |                             |                         | Analyze the sentiment of    |     |
    |                             |                         | movie review and classify   |     |
    |                             |                         | it as either POSITIVE or    |     |
    |                             |                         | NEGATIVE. Movie Review:     |     |
    |                             |                         | Opulent sets and sumptuous  |     |
    |                             |                         | costumes well photographed  |     |
    |                             |                         | by Theodor Sparkuhl, and... |     |
    +-----------------------------+-------------------------+-----------------------------+-----+
    

    התוצאות כוללות את אותן עמודות שמתועדות בביצוע חילוץ מילות מפתח.

ביטול הפריסה של מודל

אם תבחרו שלא למחוק את הפרויקט כמומלץ, תצטרכו לבטל את הפריסה של מודל Gemma ב-Vertex AI כדי שלא תמשיכו לשלם עליו. מערכת BigQuery מבטלת את הפריסה של המודל באופן אוטומטי אחרי תקופה מוגדרת של חוסר פעילות (6.5 שעות כברירת מחדל). לחלופין, אפשר לבטל את הפריסה של המודל באופן מיידי באמצעות ההצהרה ALTER MODEL, כמו בדוגמה הבאה:

ALTER MODEL `bqml_tutorial.gemma_model`
SET OPTIONS (deploy_model = false);

מידע נוסף זמין במאמר בנושא ביטול פריסה אוטומטי או מיידי של מודל פתוח.

הסרת המשאבים

  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.