大規模運用 BigQuery AI 函式:零樣本預測和成本防護機制

1. 總覽

直接在 SQL 中執行基礎模型,資料團隊就不必將資料移至獨立的推論服務。BigQuery AI 函式可在資料倉儲中生成文字 (AI.GENERATE)、分類 (AI.CLASSIFY) 及預測時間序列 (AI.FORECAST)。

在本程式碼實驗室中,您將對零售範例資料大規模使用這些函式。您預測了商店銷售額、大量分類顧客對話,並新增護欄,確保模型成本可預測。

課程內容

  • 如何啟用 BigQuery AI 函式所需的 API。
  • 如何透過連線和服務帳戶 (而非使用者憑證),從 BigQuery 呼叫 Agent Platform 模型。
  • 如何使用 TimesFM 和 AI.FORECAST 預測時間序列,不需訓練模型。
  • 如何使用 AI.GENERATE 執行批次推論,並只重試失敗的資料列。
  • 如何使用臨時資料表篩選器、每列單一模型呼叫和權杖設定,限制模型成本。

學習內容

  • 啟用 BigQuery、BigQuery Connection、BigQuery Reservation 和 Agent Platform API。
  • 建立區域性 BigQuery 連線 (bigquery_ai_conn),並將 Agent Platform 使用者角色授予其服務帳戶。
  • 建立商店銷售資料範例和 30 天預測資料表 (q4_store_projections)。
  • 將 300 則顧客即時通訊轉錄稿分類至 scored_interactions 資料表,並採用遞增重試機制。
  • 建立受控管的 actionable_churn_alerts 資料表,只將相符的資料列傳送至模型。

軟硬體需求

  • 已啟用計費功能的 Google Cloud 雲端專案,且具備建立本程式碼實驗室資源的權限。
  • Cloud Shell,包含 gcloud 和 bq 指令列工具。
  • 對 SQL 和指令列有基本瞭解。您不需要具備 BigQuery AI 函式、TimesFM 或 Agent Platform 的使用經驗。

本程式碼實驗室解決的難題

挑戰

本程式碼實驗室如何解決這個問題

排定的 BigQuery AI 工作在使用者憑證下失敗,團隊需要封鎖未編列預算的臨時 AI.GENERATE 呼叫。

建立 AI 連線:建立 Cloud 資源連結,將 roles/aiplatform.user (Agent Platform 使用者) 授予其服務帳戶,並將 roles/bigquery.connectionUser 限制為管道身分。

受管制的工作負載必須將資料集和連線保留在相同區域。

建立 AI 連線和使用 TimesFM 預測銷售量:在相同區域 (us-central1) 建立連線和資料集。

團隊希望在 SQL 中進行零樣本時間序列預測,而不必為每個 SKU 訓練模型。

使用 TimesFM 預測銷售量:使用 Google 研究團隊的 TimesFM 模型執行 AI.FORECAST,預測期間為 30 天,預測區間為 95%。

在動態共用配額 (DSQ) 下,對多個資料列執行 AI.GENERATE 擴充作業,代表只會重試因暫時性 429 錯誤而失敗的資料列。

執行批次推論並重試:擷取資料列層級 model_output.status,並僅針對 execution_status != '' 的資料列執行增量 MERGE 重試。

如果分別選取 .result、.status 和 .full_response,系統會為每個資料列的每個欄位呼叫遠端模型一次。

執行批次推論並重試和新增成本防護機制:在 CTE 中,為每個資料列呼叫一次 AI.GENERATE,並讀取該結果中的每個欄位。

如果篩選器位於 CTE 外部,且呼叫 AI.GENERATE,則不會在模型執行前套用,因此模型可能會處理每個基本資料列,產生高於預期的費用。

新增成本防護措施:套用具體化屏障模式 (CREATE TEMP TABLE),確保只有預先篩選的資料列會傳送至模型。

2. 設定環境

首先,請準備專案:設定環境變數和 API,供程式碼實驗室的其餘部分使用。

在 Cloud Shell 設定專案和區域,然後啟用 BigQuery、BigQuery Connection、BigQuery Reservation 和 Gemini Enterprise Agent Platform (Agent Platform) API:

export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value project)
export REGION="us-central1"

gcloud services enable \
  bigquery.googleapis.com \
  bigqueryconnection.googleapis.com \
  bigqueryreservation.googleapis.com \
  aiplatform.googleapis.com \
  --project="${GOOGLE_CLOUD_PROJECT}"

驗證

執行下列檢查,確認專案已啟用這四個 API:

ENABLED_APIS=$(gcloud services list --enabled \
  --project="${GOOGLE_CLOUD_PROJECT}" \
  --filter="config.name:(bigquery.googleapis.com OR bigqueryconnection.googleapis.com OR bigqueryreservation.googleapis.com OR aiplatform.googleapis.com)" \
  --format="value(config.name)" | wc -l | tr -d ' ')

if [[ "${ENABLED_APIS}" -lt 4 ]]; then
  echo "ERROR: Step 2 verification failed (ENABLED_APIS=${ENABLED_APIS}, expected 4)" >&2
  exit 1
fi
echo "Step 2 Verification Passed: ${ENABLED_APIS}/4 BigQuery and Vertex AI APIs enabled in ${GOOGLE_CLOUD_PROJECT}."

輸出結果會與下列內容相似:

Step 2 Verification Passed: 4/4 BigQuery and Vertex AI APIs enabled in <PROJECT_ID>.

專案現在已啟用四個 API。接著,您要為 BigQuery 建立專屬身分,以便呼叫 Agent Platform 模型。

3. 建立 AI 連線

本程式碼實驗室中的生成式 AI 函式會呼叫 Agent Platform 模型,因此請先設定發出呼叫的身分。

如果沒有明確連線,BigQuery AI 函式會使用提交查詢的使用者憑證。因此排定的查詢和自動化管道會因驗證錯誤而失敗。直接授予分析師 roles/aiplatform.user 權限,也能讓他們執行未編列預算的臨時 AI.GENERATE 呼叫。

在這個步驟中,您會在 us-central1 建立區域 BigQuery Cloud 資源連結。您將 Agent Platform 使用者 (roles/aiplatform.user) 角色授予服務帳戶,因此使用者不會直接呼叫 Agent Platform。

  1. 在 us-central1 中建立連線,讀取產生的服務帳戶,並授予 roles/aiplatform.user:
if ! bq show --connection "${GOOGLE_CLOUD_PROJECT}.us-central1.bigquery_ai_conn" >/dev/null 2>&1; then
  bq mk --connection --location=us-central1 \
    --project_id="${GOOGLE_CLOUD_PROJECT}" \
    --connection_type=CLOUD_RESOURCE \
    bigquery_ai_conn
fi

export CONNECTION_SA=$(bq show --format=prettyjson --connection "${GOOGLE_CLOUD_PROJECT}.us-central1.bigquery_ai_conn" | jq -r '.cloudResource.serviceAccountId')
if [[ -z "${CONNECTION_SA}" || "${CONNECTION_SA}" == "null" ]]; then
  echo "ERROR: Failed to extract Connection Service Account." >&2
  exit 1
fi
echo "Connection Service Account: ${CONNECTION_SA}"

for attempt in 1 2 3 4 5; do
  gcloud projects add-iam-policy-binding "${GOOGLE_CLOUD_PROJECT}" \
    --member="serviceAccount:${CONNECTION_SA}" \
    --role="roles/aiplatform.user" \
    --condition=None \
    --quiet && break
  sleep 5
done
sleep 15

驗證

執行下列檢查,確認 us-central1.bigquery_ai_conn 連線存在,且其服務帳戶在專案中具備 roles/aiplatform.user 角色:

CONN_SA_CHECK=$(bq show --format=json --connection "${GOOGLE_CLOUD_PROJECT}.us-central1.bigquery_ai_conn" | jq -r '.cloudResource.serviceAccountId')
IAM_BINDING_CHECK=$(gcloud projects get-iam-policy "${GOOGLE_CLOUD_PROJECT}" --format=json | jq -r --arg sa "serviceAccount:${CONN_SA_CHECK}" '.bindings[] | select(.role=="roles/aiplatform.user") | .members[] | select(. == $sa)')

if [[ -z "${CONN_SA_CHECK}" || -z "${IAM_BINDING_CHECK}" ]]; then
  echo "ERROR: Step 3 verification failed (CONN_SA_CHECK=${CONN_SA_CHECK}, IAM_BINDING_CHECK=${IAM_BINDING_CHECK})" >&2
  exit 1
fi
echo "Step 3 Verification Passed: Connection=us-central1.bigquery_ai_conn, SA=${CONN_SA_CHECK} bound to roles/aiplatform.user."

輸出結果會與下列內容相似:

Step 3 Verification Passed: Connection=us-central1.bigquery_ai_conn, SA=bqcx-<PROJECT_NUMBER>-...@gcp-sa-bigquery-condel.iam.gserviceaccount.com bound to roles/aiplatform.user.

您現在已有區域性 bigquery_ai_conn 連線,其服務帳戶可以呼叫 Agent Platform 模型。使用前,您先試用不需要連線的 AI 函式:預測。

4. 使用 TimesFM 預測銷售量

預測是最容易上手的起點,因為不需要訓練模型,也不需要提示。

預測通常是指為每項產品或顧客區隔訓練個別模型,例如 ARIMA、Prophet 或 XGBoost。AI.FORECAST 使用 Google 研究的 TimesFM,這是一種時間序列基礎模型。這項服務會產生零樣本預測,也就是說,您不需要使用自己的資料訓練模型。本實驗室會使用預設模型 TimesFM 2.5。TimesFM 3.0 預先發布版現已推出。

  1. 在 us-central1 中建立 demand_intelligence 資料集。接著,在 historical_store_sales 資料表中填入三家商店 181 天的銷售資料 (543 列):
if ! bq --location=us-central1 show --dataset "${GOOGLE_CLOUD_PROJECT}:demand_intelligence" >/dev/null 2>&1; then
  bq mk --dataset --location=us-central1 "${GOOGLE_CLOUD_PROJECT}:demand_intelligence"
fi

cat << 'EOF' > /tmp/generate_data.sql
CREATE OR REPLACE TABLE `demand_intelligence.historical_store_sales` AS
SELECT
  store_id,
  DATE_ADD(DATE '2026-01-01', INTERVAL day_offset DAY) AS sale_date,
  ROUND(1000 + 500 * SIN(day_offset / 7.0) + (day_offset * 2.5) + (RAND() * 50), 2) AS units_sold,
  ROUND(50 + (RAND() * 10), 2) AS promotional_discount
FROM
  UNNEST(['STORE_NYC_01', 'STORE_LON_02', 'STORE_TYO_03']) AS store_id,
  UNNEST(GENERATE_ARRAY(0, 180)) AS day_offset;
EOF

bq --location=us-central1 query --use_legacy_sql=false < /tmp/generate_data.sql
  1. 使用 TimesFM 和 95% 預測區間,預測每間商店 (id_cols => ['store_id']) 未來 30 天的銷售量。接著查看 STORE_NYC_01 的前 5 個預測資料列:
cat << 'EOF' > /tmp/run_forecast.sql
CREATE OR REPLACE TABLE `demand_intelligence.q4_store_projections` AS
SELECT *
FROM AI.FORECAST(
  TABLE `demand_intelligence.historical_store_sales`,
  horizon => 30,
  context_window => 128,
  confidence_level => 0.95,
  model => 'TimesFM 2.5',
  timestamp_col => 'sale_date',
  data_col => 'units_sold',
  id_cols => ['store_id']
);
EOF

bq --location=us-central1 query --use_legacy_sql=false < /tmp/run_forecast.sql

bq --location=us-central1 query --use_legacy_sql=false \
  'SELECT store_id, forecast_timestamp, forecast_value, prediction_interval_lower_bound, prediction_interval_upper_bound FROM `demand_intelligence.q4_store_projections` WHERE store_id = "STORE_NYC_01" ORDER BY forecast_timestamp LIMIT 5;'

驗證

執行下列檢查,確認資料列數量。historical_store_sales 有 543 列 (3 間商店 × 181 天)。q4_store_projections 有 90 列 (3 間商店 × 30 天),且間隔界限有效:

HIST_ROWS=$(bq --location=us-central1 query --use_legacy_sql=false --format=csv --quiet \
  'SELECT COUNT(1) FROM `demand_intelligence.historical_store_sales`' | tail -n 1)
FORECAST_STATS=$(bq --location=us-central1 query --use_legacy_sql=false --format=csv --quiet \
  'SELECT COUNT(1) AS total_rows, COUNT(DISTINCT store_id) AS stores, COUNTIF(prediction_interval_upper_bound < prediction_interval_lower_bound OR forecast_value IS NULL) AS invalid_bounds FROM `demand_intelligence.q4_store_projections`' | tail -n 1)

if [[ "${HIST_ROWS}" != "543" || "${FORECAST_STATS}" != "90,3,0" ]]; then
  echo "ERROR: Step 4 verification failed (HIST_ROWS=${HIST_ROWS}, FORECAST_STATS=${FORECAST_STATS})" >&2
  exit 1
fi
echo "Step 4 Verification Passed: historical_store_sales=${HIST_ROWS} rows, q4_store_projections=${FORECAST_STATS} (rows,stores,invalid_bounds)."

輸出結果會與下列內容相似:

Step 4 Verification Passed: historical_store_sales=543 rows, q4_store_projections=90,3,0 (rows,stores,invalid_bounds).

您現在有 90 天的每日商店預測資料,預測區間為 95%,不需訓練模型即可建立。接著,您將使用連線,在多個資料列上呼叫生成式模型。

5. 執行批次推論並重試

預測功能會根據數字運作。現在,請將生成式模型套用至多個資料列的文字,這時配額和失敗資料列就會開始變得重要。

對數百萬列資料執行生成式 AI 函式時,BigQuery 會向 Agent Platform 傳送多項並行要求。如果沒有速率管理機制,這些工作負載就會超過配額並失敗。

BigQuery AI 函式會使用動態共用配額 (DSQ),平緩流量和批次提示的突增。此外,也會傳回每列的錯誤狀態。

DSQ 不保證單一查詢處理的資料列數量。BigQuery 會在生成式 AI 函式配額中,發布每項 AI 函式工作的預估資料列數。如果是大型資料表,請將工作拆分為多個查詢、儲存每項結果,並僅重試失敗的資料列,如這個步驟所示。

  1. 建立 demand_intelligence.customer_transcripts 資料表,其中包含三個客戶帳戶的 300 筆客服即時通訊轉錄稿:
cat << 'EOF' > /tmp/create_transcripts.sql
CREATE OR REPLACE TABLE `demand_intelligence.customer_transcripts` AS
SELECT
  GENERATE_UUID() AS interaction_id,
  customer_id,
  CASE MOD(id_num + cust_idx, 3)
    WHEN 0 THEN 'Customer requested immediate account cancellation due to repeated service outages. Extremely frustrated.'
    WHEN 1 THEN 'Customer enquired about upgrade pricing for the Q4 Enterprise tier. Very positive call.'
    ELSE 'Standard billing address update. Completed without issues.'
  END AS transcript_text,
  CURRENT_TIMESTAMP() AS interaction_time
FROM
  UNNEST(GENERATE_ARRAY(1, 100)) AS id_num,
  UNNEST(['CUST_1001', 'CUST_1002', 'CUST_1003']) AS customer_id WITH OFFSET AS cust_idx;
EOF

bq --location=us-central1 query --use_legacy_sql=false < /tmp/create_transcripts.sql
  1. 使用 AI.GENERATE 將每則轉錄稿的情緒分類。呼叫會設定 connection_id、endpoint 和 model_params,這些設定遵循 Agent Platform GenerateContentRequest 結構定義。思考詞元會計入max_output_tokens,因此如果限制過低,可能會傳回空白或不完整的結果。呼叫會設定 256 個權杖和最低思考程度。它會在名為 raw_predictions 的通用資料表運算式 (CTE) 中,對每個資料列執行一次,而外部查詢會讀取傳回的 STRUCT 的每個欄位:
cat << 'EOF' > /tmp/batch_inference.sql
CREATE OR REPLACE TABLE `demand_intelligence.scored_interactions` AS
WITH raw_predictions AS (
  SELECT
    interaction_id,
    customer_id,
    AI.GENERATE(
      prompt => CONCAT('Classify customer sentiment as CHURN_RISK, EXPANSION, or NEUTRAL. Return only label: ', transcript_text),
      connection_id => 'us-central1.bigquery_ai_conn',
      endpoint => 'gemini-3.5-flash-lite',
      model_params => JSON '{"generation_config": {"temperature": 0.0, "max_output_tokens": 256, "thinking_config": {"thinking_level": "MINIMAL"}}}'
    ) AS model_output
  FROM `demand_intelligence.customer_transcripts`
)
SELECT
  interaction_id,
  customer_id,
  model_output.result AS sentiment_label,
  model_output.status AS execution_status,
  INT64(model_output.full_response.usage_metadata.prompt_token_count) AS prompt_tokens,
  INT64(model_output.full_response.usage_metadata.candidates_token_count) AS output_tokens
FROM raw_predictions;
EOF

bq --location=us-central1 query --use_legacy_sql=false < /tmp/batch_inference.sql
  1. 請檢查資料列狀態,然後執行遞增重試模式。只會重新評估失敗的資料列,例如狀態為暫時性 RESOURCE_EXHAUSTED 的資料列。系統不會再次向您收取成功列 (execution_status = '' 或 NULL) 的費用:
bq --location=us-central1 query --use_legacy_sql=false \
  'SELECT execution_status, COUNT(1) AS row_count FROM `demand_intelligence.scored_interactions` GROUP BY execution_status;'

cat << 'EOF' > /tmp/incremental_retry.sql
-- Incremental Retry Pattern: Re-invoke AI.GENERATE ONLY on rows with non-empty error status
MERGE `demand_intelligence.scored_interactions` T
USING (
  SELECT
    s.interaction_id,
    AI.GENERATE(
      prompt => CONCAT('Classify customer sentiment as CHURN_RISK, EXPANSION, or NEUTRAL. Return only label: ', c.transcript_text),
      connection_id => 'us-central1.bigquery_ai_conn',
      endpoint => 'gemini-3.5-flash-lite',
      model_params => JSON '{"generation_config": {"temperature": 0.0, "max_output_tokens": 256, "thinking_config": {"thinking_level": "MINIMAL"}}}'
    ) AS retry_output
  FROM `demand_intelligence.scored_interactions` s
  JOIN `demand_intelligence.customer_transcripts` c
    ON s.interaction_id = c.interaction_id
  WHERE s.execution_status != ''
) R
ON T.interaction_id = R.interaction_id AND T.execution_status != ''
WHEN MATCHED THEN
  UPDATE SET
    sentiment_label = R.retry_output.result,
    execution_status = R.retry_output.status,
    prompt_tokens = INT64(R.retry_output.full_response.usage_metadata.prompt_token_count),
    output_tokens = INT64(R.retry_output.full_response.usage_metadata.candidates_token_count);
EOF

bq --location=us-central1 query --use_legacy_sql=false < /tmp/incremental_retry.sql

驗證

執行下列檢查,確認 scored_interactions 包含全部 300 個資料列、沒有錯誤狀態,且計費 prompt_tokens 的數量為正數:

DSQ_STATS=$(bq --location=us-central1 query --use_legacy_sql=false --format=csv --quiet "
SELECT
  COUNT(1) AS total_rows,
  COUNTIF(execution_status IS NULL OR execution_status = '') AS succeeded_rows,
  IF(SUM(prompt_tokens) > 0, 'TOKENS_OK', 'ZERO_TOKENS') AS token_status
FROM \`demand_intelligence.scored_interactions\`" | tail -n 1)

if [[ "${DSQ_STATS}" != "300,300,TOKENS_OK" ]]; then
  echo "ERROR: Step 5 verification failed (DSQ_STATS=${DSQ_STATS}, expected 300,300,TOKENS_OK)" >&2
  exit 1
fi
echo "Step 5 Verification Passed: scored_interactions=${DSQ_STATS} (total_rows,succeeded_rows,token_status)."

輸出結果會與下列內容相似:

Step 5 Verification Passed: scored_interactions=300,300,TOKENS_OK (total_rows,succeeded_rows,token_status).

現在,所有 300 份轉錄稿都有情緒標籤,且 MERGE 重試作業只會重新執行失敗的資料列。接著,您要限制傳送至模型的資料量。

6. 新增成本防護機制

批次推論會根據傳送至模型的每個資料列和詞元計費。在這個步驟中,您將在 SQL 中套用兩項護欄,並瞭解第三項專案層級護欄:

  • 具體化障礙模式:假設您使用 WHERE REGEXP_CONTAINS(...) 篩選 CTE 中的資料列,並將該 CTE 傳遞至 AI.GENERATE。篩選器可能不會先執行,因此模型可以處理每個基本資料列。先使用 CREATE TEMP TABLE 將篩選後的資料列寫入臨時資料表,可確保只有相符的資料列會傳送至模型。
  • 每列呼叫一次:為 .result 寫入 AI.GENERATE(...),再為 .full_response.usage_metadata 寫入一次,每列會呼叫遠端模型兩次。在 CTE (AS inference_payload) 中呼叫一次,並從該別名讀取這兩個欄位。CTE 不會具體化,因此如果您多次參照 CTE,或在後續查詢中重複使用輸出內容,請先將其寫入資料表。
  • 每日權杖配額:BigQuery 會限制每日生成式 AI 權杖數量,並為每個專案 (GenAiInputTokensPerDay、GenAiOutputTokensPerDay) 和專案中的每位使用者 (GenAiInputTokensPerUserPerDay、GenAiOutputTokensPerUserPerDay) 設定配額。輸出配額包含思考權杖。降低上限會設定每日支出上限。本實驗室不會變更這些設定,因為這些設定會套用至整個專案。如要設定,請參閱「控管生成式 AI 的成本」。

在正式環境中,請先簡化相同的提示,再呼叫 AI.GENERATE 並重新彙整結果,因為即使提示重複,每一列仍是獨立的模型呼叫。

  1. 執行受控管的管道。系統會寫入 candidate_records 暫存資料表,並為每個資料列呼叫一次模型:
cat << 'EOF' > /tmp/governed_finops_query.sql
-- 1. Materialization Barrier (Forces evaluation of filter BEFORE calling AI model)
CREATE TEMP TABLE candidate_records AS
SELECT interaction_id, customer_id, transcript_text
FROM `demand_intelligence.customer_transcripts`
WHERE REGEXP_CONTAINS(transcript_text, r'(?i)(cancellation|outages|frustrated)')
  AND LENGTH(transcript_text) > 20;

-- 2. One model call per row: call AI.GENERATE once and read every field from its result
CREATE OR REPLACE TABLE `demand_intelligence.actionable_churn_alerts` AS
WITH single_model_call AS (
  SELECT
    interaction_id,
    customer_id,
    AI.GENERATE(
      prompt => CONCAT('Extract key complaint in under 10 words: ', transcript_text),
      connection_id => 'us-central1.bigquery_ai_conn',
      endpoint => 'gemini-3.5-flash-lite',
      model_params => JSON '{"generation_config": {"temperature": 0.0, "max_output_tokens": 256, "thinking_config": {"thinking_level": "MINIMAL"}}}'
    ) AS inference_payload
  FROM candidate_records
)
SELECT
  interaction_id,
  customer_id,
  inference_payload.result AS extracted_complaint,
  INT64(inference_payload.full_response.usage_metadata.prompt_token_count) AS billed_prompt_tokens,
  INT64(inference_payload.full_response.usage_metadata.candidates_token_count) AS billed_output_tokens
FROM single_model_call;
EOF

bq --location=us-central1 query --use_legacy_sql=false < /tmp/governed_finops_query.sql

驗證

執行下列檢查,確認 AI.GENERATE 只處理了 300 筆客戶流失轉錄稿中相符的 100 筆,並記錄計費詞元:

FINOPS_STATS=$(bq --location=us-central1 query --use_legacy_sql=false --format=csv --quiet "
SELECT
  COUNT(1) AS total_evaluated_rows,
  COUNTIF(extracted_complaint IS NOT NULL AND LENGTH(extracted_complaint) > 0) AS valid_extractions,
  IF(SUM(billed_prompt_tokens + billed_output_tokens) > 0, 'BILLED_OK', 'ZERO_TOKENS') AS billing_audit
FROM \`demand_intelligence.actionable_churn_alerts\`" | tail -n 1)

if [[ "${FINOPS_STATS}" != "100,100,BILLED_OK" ]]; then
  echo "ERROR: Step 6 verification failed (FINOPS_STATS=${FINOPS_STATS}, expected 100,100,BILLED_OK)" >&2
  exit 1
fi
echo "Step 6 Verification Passed: actionable_churn_alerts=${FINOPS_STATS} (evaluated_rows,valid_extractions,billing_audit)."

輸出結果會與下列內容相似:

Step 6 Verification Passed: actionable_churn_alerts=100,100,BILLED_OK (evaluated_rows,valid_extractions,billing_audit).

現在,您有一個僅由 100 個相符資料列組成的 actionable_churn_alerts 資料表,每列都有一個模型呼叫。工作已完成,請清除資源。

7. 清除

為避免系統持續向您的 Google Cloud 帳戶收取費用,請刪除您在本程式碼實驗室中建立的資源。

在 Cloud Shell 中,刪除資料集、連線和暫時 SQL 檔案:

bq rm -r -f -d "${GOOGLE_CLOUD_PROJECT}:demand_intelligence"
bq rm --connection -f --location=us-central1 "${GOOGLE_CLOUD_PROJECT}.us-central1.bigquery_ai_conn"
rm -f /tmp/generate_data.sql /tmp/run_forecast.sql /tmp/create_transcripts.sql /tmp/batch_inference.sql /tmp/incremental_retry.sql /tmp/governed_finops_query.sql
echo "Cleanup of BigQuery AI & FinOps Guardrails environment complete."

專案中不會再有本程式碼實驗室的資料集或連結。

8. 恭喜

您大規模執行 BigQuery AI 函式,並將費用控制在可預測的範圍內。您學到了下列內容:

  • 啟用 BigQuery AI 函式所需的 API。
  • 透過連線和其服務帳戶 (而非使用者憑證),從 BigQuery 呼叫 Agent Platform 模型。
  • 使用 TimesFM 和 AI.FORECAST,不需訓練模型即可預測時間序列。
  • 使用 AI.GENERATE 執行批次推論,並只重試失敗的資料列。
  • 使用暫存資料表篩選器、每列單一模型呼叫和詞元設定,限制模型費用。

9. 相關程式碼實驗室