使用 Gemini 模型和 AI.GENERATE_TEXT 函式生成文字
本教學課程說明如何根據 gemini-2.5-flash 模型建立遠端模型,然後使用 AI.GENERATE_TEXT 函式,從 bigquery-public-data.imdb.reviews 公開資料表擷取電影評論中的關鍵字,並進行情緒分析。
必要的角色
如要執行本教學課程,您需要下列 Identity and Access Management (IAM) 角色:
- 建立及使用 BigQuery 資料集、連線和模型:
BigQuery 管理員 (
roles/bigquery.admin)。 - 將權限授予連線的服務帳戶:專案 IAM 管理員 (
roles/resourcemanager.projectIamAdmin)。
這些預先定義的角色具備執行本文所述工作所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:
所需權限
- 建立資料集:
bigquery.datasets.create - 建立、委派及使用連線:
bigquery.connections.* - 設定預設連線:
bigquery.config.* - 設定服務帳戶權限:
resourcemanager.projects.getIamPolicy和resourcemanager.projects.setIamPolicy - 建立模型並執行推論:
bigquery.jobs.createbigquery.models.createbigquery.models.getDatabigquery.models.updateDatabigquery.models.updateMetadata
費用
在本文件中,您會使用下列 Cloud de Confiance by S3NS的計費元件:
- 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.
如要進一步瞭解 BigQuery 定價,請參閱 BigQuery 說明文件中的「BigQuery 定價」一文。
如要進一步瞭解 Vertex AI 定價,請參閱 Vertex AI 定價頁面。
事前準備
-
In the Cloud de Confiance console, on the project selector page, select or create a Cloud de Confiance 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 Cloud de Confiance 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 資料集來儲存機器學習模型。
控制台
前往 Cloud de Confiance 控制台的「BigQuery」頁面。
在「Explorer」窗格中,按一下專案名稱。
依序點按 「View actions」(查看動作) >「Create dataset」(建立資料集)
在「建立資料集」頁面中,執行下列操作:
在「Dataset ID」(資料集 ID) 中輸入
bqml_tutorial。針對「Location type」(位置類型) 選取「Multi-region」(多區域),然後選取「US (multiple regions in United States)」(us (多個美國區域))。
其餘設定請保留預設狀態,然後按一下「建立資料集」。
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」。
建立連線
建立Cloud 資源連線,並取得連線的服務帳戶。在與上一步建立的資料集相同的位置中建立連線。
如果您已設定預設連線,或具備 BigQuery 管理員角色,可以略過這個步驟。
選取下列選項之一:控制台
前往「BigQuery」頁面。
點選左側窗格中的 「Explorer」:

如果沒有看到左側窗格,請按一下「展開左側窗格」圖示 開啟窗格。
在「Explorer」窗格中展開專案名稱,然後按一下「Connections」。
在「Connections」(連線) 頁面中,按一下「Create connection」(建立連線)。
在「連線類型」中,選擇「Vertex AI 遠端模型、遠端函式、BigLake 和 Spanner (Cloud 資源)」。
在「連線 ID」欄位中,輸入連線名稱。
在「位置類型」部分,選取連線位置。連線應與資料集等其他資源位於同一位置。
點選「建立連線」。
點選「前往連線」。
在「連線資訊」窗格中,複製服務帳戶 ID,以便在後續步驟中使用。
bq
在指令列環境中建立連線:
bq mk --connection --location=REGION --project_id=PROJECT_ID \ --connection_type=CLOUD_RESOURCE CONNECTION_ID
--project_id參數會覆寫預設專案。更改下列內容:
REGION:您的連線區域PROJECT_ID:您的 Cloud de Confiance 專案 IDCONNECTION_ID:連線的 ID
建立連線資源時,BigQuery 會建立專屬的系統服務帳戶,並將其與連線建立關聯。
疑難排解:如果收到下列連線錯誤訊息,請更新 Google Cloud SDK:
Flags parsing error: flag --connection_type=CLOUD_RESOURCE: value should be one of...
擷取並複製服務帳戶 ID,以供後續步驟使用:
bq show --connection PROJECT_ID.REGION.CONNECTION_ID
輸出結果會與下列內容相似:
name properties 1234.REGION.CONNECTION_ID {"serviceAccountId": "connection-1234-9u56h9@gcp-sa-bigquery-condel.s3ns-system.iam.gserviceaccount.com"}
Python
在試用這個範例之前,請先按照「使用用戶端程式庫的 BigQuery 快速入門導覽課程」中的 Python 設定操作說明進行操作。詳情請參閱 BigQuery Python API 參考說明文件。
如要向 BigQuery 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。
執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。
Node.js
在試用這個範例之前,請先按照「使用用戶端程式庫的 BigQuery 快速入門導覽課程」中的 Node.js 設定操作說明進行操作。詳情請參閱 BigQuery Node.js API 參考說明文件。
如要向 BigQuery 進行驗證,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。
執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。
Terraform
使用 google_bigquery_connection 資源。
如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。
下列範例會在 US 地區中建立名為 my_cloud_resource_connection 的 Cloud 資源連線:
如要在 Cloud de Confiance 專案中套用 Terraform 設定,請完成下列各節的步驟。
準備 Cloud Shell
- 啟動 Cloud Shell。
-
設定要套用 Terraform 設定的預設 Cloud de Confiance 專案。
每項專案只需要執行一次這個指令,且可以在任何目錄中執行。
export GOOGLE_CLOUD_PROJECT=PROJECT_ID
如果您在 Terraform 設定檔中設定明確值,環境變數就會遭到覆寫。
準備目錄
每個 Terraform 設定檔都必須有自己的目錄 (也稱為根模組)。
-
在 Cloud Shell 中建立目錄,並在該目錄中建立新檔案。檔案名稱的副檔名必須是
.tf,例如main.tf。在本教學課程中,這個檔案稱為main.tf。mkdir DIRECTORY && cd DIRECTORY && touch main.tf
-
如果您正在學習教學課程,可以複製每個章節或步驟中的範例程式碼。
將範例程式碼複製到新建立的
main.tf。視需要從 GitHub 複製程式碼。如果 Terraform 代码片段是端對端解決方案的一部分,建議您使用這個方法。
- 查看並修改範例參數,套用至您的環境。
- 儲存變更。
-
初始化 Terraform。每個目錄只需執行一次這項操作。
terraform init
如要使用最新版 Google 供應商,請加入
-upgrade選項:terraform init -upgrade
套用變更
-
檢查設定,確認 Terraform 即將建立或更新的資源符合您的預期:
terraform plan
視需要修正設定。
-
執行下列指令,並在提示中輸入
yes,套用 Terraform 設定:terraform apply
等待 Terraform 顯示「Apply complete!」訊息。
- 開啟 Cloud de Confiance 專案即可查看結果。在 Cloud de Confiance 控制台中,前往 UI 中的資源,確認 Terraform 已建立或更新這些資源。
將權限授予連線的服務帳戶
為連線的服務帳戶授予 Vertex AI 使用者角色。您必須在「開始前」一節中建立或選取的專案中,授予這項角色。在其他專案中授予角色會導致 bqcx-1234567890-xxxx@gcp-sa-bigquery-condel.s3ns-system.iam.gserviceaccount.com does not have the permission to access resource 錯誤。
如要授予角色,請按照下列步驟操作:
前往「IAM & Admin」(IAM 與管理) 頁面。
按一下 「授予存取權」。
在「新增主體」欄位,輸入先前複製的服務帳戶 ID。
在「選取角色」欄位中,選擇「Vertex AI」,然後選取「Vertex AI 使用者」角色。
按一下 [儲存]。
建立遠端模型
建立代表代管 Vertex AI 模型的遠端模型:
前往 Cloud de Confiance 控制台的「BigQuery」頁面。
在查詢編輯器中執行下列陳述式:
CREATE OR REPLACE MODEL `bqml_tutorial.gemini_model` REMOTE WITH CONNECTION `LOCATION.CONNECTION_ID` OPTIONS (ENDPOINT = 'gemini-2.5-flash');
更改下列內容:
LOCATION:連線位置CONNECTION_ID:BigQuery 連線的 ID在 Cloud de Confiance 控制台中查看連線詳細資料時,這是「連線 ID」中顯示的完整連線 ID 最後一個部分的值,例如
projects/myproject/locations/connection_location/connections/myconnection
查詢作業會在幾秒內完成,模型 gemini_model 隨即會顯示在 bqml_tutorial 資料集中。由於查詢使用 CREATE MODEL 陳述式建立模型,因此不會有查詢結果。
執行關鍵字擷取
使用遠端模型和 AI.GENERATE_TEXT 函式,對 IMDB 電影評論執行關鍵字擷取作業:
前往 Cloud de Confiance 控制台的「BigQuery」頁面。
在查詢編輯器中輸入下列陳述式,對五則電影評論執行關鍵字擷取作業:
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... | | ... | ... | ... | +--------------+------------------+----------------------------------------+
執行情緒分析
使用遠端模型和 AI.GENERATE_TEXT 函式,對 IMDB 電影評論執行情緒分析:
前往 Cloud de Confiance 控制台的「BigQuery」頁面。
在查詢編輯器中執行下列陳述式,對電影評論執行情緒分析:
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 ... | | ... | ... | ... | +----------+----------+------------------------------------------------+
清除所用資源
- In the Cloud de Confiance 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.