使用 Gemma 開放式模型和 AI.GENERATE_TEXT 函式生成文字
本教學課程說明如何建立以 Gemma 模型為基礎的遠端模型,然後使用 AI.GENERATE_TEXT 函式搭配該模型,從 bigquery-public-data.imdb.reviews 公開資料表擷取關鍵字,並對電影評論執行情緒分析。
所需權限
如要執行本教學課程,您需要下列 Identity and Access Management (IAM) 角色:
- 建立及使用 BigQuery 資料集、連線和模型:
BigQuery 管理員 (
roles/bigquery.admin)。 - 將權限授予連線的服務帳戶:專案 IAM 管理員 (
roles/resourcemanager.projectIamAdmin)。 - 在 Vertex AI 中部署及取消部署模型:Vertex AI 管理員 (
roles/aiplatform.admin)。
這些預先定義的角色具備執行本文所述工作所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:
所需權限
- 建立資料集:
bigquery.datasets.create - 建立、委派及使用連線:
bigquery.connections.* - 設定預設連線:
bigquery.config.* - 設定服務帳戶權限:
resourcemanager.projects.getIamPolicy和resourcemanager.projects.setIamPolicy - 部署及取消部署 Vertex AI 模型:
aiplatform.endpoints.deployaiplatform.endpoints.undeploy
- 建立模型並執行推論:
bigquery.jobs.createbigquery.models.createbigquery.models.getDatabigquery.models.updateDatabigquery.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.
您可以使用 Pricing Calculator,根據預測用量估算費用。
如要進一步瞭解 BigQuery 定價,請參閱 BigQuery 說明文件中的「BigQuery 定價」一文。
部署至 Vertex AI 的開放式模型會依機器時數計費。也就是說,端點完全設定完成後,系統就會開始計費,直到您解除部署為止。如要進一步瞭解 Vertex AI 定價,請參閱 Vertex AI 定價頁面。
事前準備
-
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 theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
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 theserviceusage.services.enablepermission. Learn how to grant roles.
建立資料集
建立 BigQuery 資料集來儲存機器學習模型。
控制台
前往 Google Cloud 控制台的「BigQuery」頁面。
在「Explorer」窗格中,按一下專案名稱。
依序點按 「View actions」(查看動作) >「Create dataset」(建立資料集)
在「建立資料集」頁面中,執行下列操作:
在「Dataset ID」(資料集 ID) 中輸入
bqml_tutorial。針對「位置類型」選取「多區域」,然後選取「美國 (多個美國地區)」。
其餘設定請保留預設狀態,然後按一下「建立資料集」。
bq
如要建立新的資料集,請使用 bq mk 指令,搭配 --location 旗標。如需可能的完整參數清單,請參閱 bq mk --dataset 指令參考資料。
建立名為「
bqml_tutorial」的資料集,並將資料位置設為「US」,說明則設為「BigQuery ML tutorial dataset」:bq --location=US mk -d \ --description "BigQuery ML tutorial dataset." \ bqml_tutorial
這個指令採用
-d捷徑,而不是使用--dataset旗標。如果您省略-d和--dataset,該指令預設會建立資料集。確認資料集已建立完成:
bq ls
API
請呼叫 datasets.insert 方法,搭配已定義的資料集資源。
{ "datasetReference": { "datasetId": "bqml_tutorial" } }
BigQuery DataFrames
在嘗試這個範例之前,請按照使用 BigQuery DataFrames 的 BigQuery 快速入門導覽課程中的 BigQuery DataFrames 設定說明操作。 詳情請參閱 BigQuery DataFrames 參考說明文件。
如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定 ADC」。
建立遠端模型
建立代表代管 Vertex AI 模型的遠端模型:
前往 Google Cloud 控制台的「BigQuery」頁面。
在查詢編輯器中執行下列陳述式:
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 模型會顯示在「Explorer」(探索工具) 窗格的 bqml_tutorial 資料集中。由於查詢是使用 CREATE MODEL 陳述式建立模型,因此不會有查詢結果。
執行關鍵字擷取作業
使用遠端模型和 AI.GENERATE_TEXT 函式,對 IMDB 電影評論執行關鍵字擷取作業:
前往 Google Cloud 控制台的「BigQuery」頁面。
在查詢編輯器中輸入下列陳述式,對 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資料表中的所有資料欄。
執行情緒分析
使用遠端模型和 AI.GENERATE_TEXT 函式,對 IMDB 電影評論執行情緒分析:
前往 Google Cloud 控制台的「BigQuery」頁面。
在查詢編輯器中執行下列陳述式,對 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... | | +-----------------------------+-------------------------+-----------------------------+-----+結果包含與「執行關鍵字擷取作業」一節所述相同的資料欄。
取消部署模型
如果您選擇不刪除專案 (建議做法),請務必在 Vertex AI 中取消部署 Gemma 模型,以免持續產生相關費用。BigQuery 會在指定閒置時間 (預設為 6.5 小時) 過後,自動取消部署模型。或者,您也可以使用 ALTER MODEL 陳述式立即取消部署模型,如下列範例所示:
ALTER MODEL `bqml_tutorial.gemma_model` SET OPTIONS (deploy_model = false);
詳情請參閱「自動或立即取消部署開放模型」。
清除所用資源
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.