1. Overview
Running foundation models directly in SQL lets data teams work without moving data to separate inference services. BigQuery AI functions generate text (AI.GENERATE), classify (AI.CLASSIFY), and forecast time series (AI.FORECAST) inside the data warehouse.
In this codelab, you use these functions at scale on sample retail data. You forecast store sales, classify customer chats in bulk, and add the guardrails that keep model costs predictable.
What you'll learn
- How to enable the APIs that BigQuery AI functions need.
- How to call Agent Platform models from BigQuery through a connection and its service account, instead of user credentials.
- How to forecast time series without training a model, using TimesFM and
AI.FORECAST. - How to run batch inference with
AI.GENERATEand retry only the rows that failed. - How to limit model costs with a temporary table filter, a single model call per row, and token settings.
What you'll do
- Enable the BigQuery, BigQuery Connection, BigQuery Reservation, and Agent Platform APIs.
- Create a regional BigQuery connection (
bigquery_ai_conn) and grant its service account the Agent Platform User role. - Create sample store sales data and a 30-day forecast table (
q4_store_projections). - Classify 300 customer chat transcripts into a
scored_interactionstable, with an incremental retry. - Build a governed
actionable_churn_alertstable that sends only matching rows to the model.
What you'll need
- A Google Cloud project with billing enabled, and permission to create the resources in this codelab.
- Cloud Shell, which includes the
gcloudandbqcommand-line tools. - Basic familiarity with SQL and the command line. You don't need prior experience with BigQuery AI functions, TimesFM, or Agent Platform.
Challenges this codelab solves
Challenge | How this codelab solves it |
Scheduled BigQuery AI jobs fail under end-user credentials, and teams need to block unbudgeted ad hoc | Create the AI connection: Creates a Cloud resource connection, grants |
Regulated workloads must keep the dataset and connection in the same region. | Create the AI connection and Forecast sales with TimesFM: Create the connection and the dataset in the same region ( |
Teams want zero-shot time series forecasting in SQL without training a model per SKU. | Forecast sales with TimesFM: Runs |
Scaling | Run batch inference with retries: Captures row-level |
Selecting | Run batch inference with retries and Add cost guardrails: Call |
A filter outside a CTE that calls | Add cost guardrails: Applies the materialization barrier pattern ( |
2. Set up the environment
Start by preparing your project: the environment variables and the APIs that the rest of the codelab uses.
In Cloud Shell, set your project and region, then enable the BigQuery, BigQuery Connection, BigQuery Reservation, and Gemini Enterprise Agent Platform (Agent Platform) APIs:
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}"
Verification
Run the following check to confirm that all four APIs are enabled in your project:
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}."
The output is similar to the following:
Step 2 Verification Passed: 4/4 BigQuery and Vertex AI APIs enabled in <PROJECT_ID>.
Your project now has the four APIs enabled. Next, you give BigQuery its own identity for calling Agent Platform models.
3. Create the AI connection
The generative AI functions in this codelab call Agent Platform models, so set up the identity that makes those calls first.
Without an explicit connection, BigQuery AI functions use the credentials of the user who submits the query. Scheduled queries and automated pipelines then fail with authentication errors. Granting analysts roles/aiplatform.user directly also lets them run unbudgeted ad hoc AI.GENERATE calls.
In this step, you create a regional BigQuery Cloud resource connection in us-central1. You grant its service account the Agent Platform User (roles/aiplatform.user) role, so end users don't call Agent Platform directly.
- Create the connection in
us-central1, read its generated service account, and grant itroles/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
Verification
Run the following check to confirm that the us-central1.bigquery_ai_conn connection exists and that its service account has the roles/aiplatform.user role on the project:
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."
The output is similar to the following:
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.
You now have a regional bigquery_ai_conn connection whose service account can call Agent Platform models. Before you use it, you try the AI function that needs no connection: a forecast.
4. Forecast sales with TimesFM
Forecasting is the simplest place to start, because it needs no trained model and no prompt.
Forecasting usually means training a separate model, such as ARIMA, Prophet, or XGBoost, for each product or customer segment. AI.FORECAST uses Google Research's TimesFM, a time series foundation model. It produces zero-shot forecasts, which means it needs no training on your data. This lab uses the default model, TimesFM 2.5. TimesFM 3.0 is available in Preview.
- Create the
demand_intelligencedataset inus-central1. Then fill thehistorical_store_salestable with 181 days of sales for three stores (543 rows):
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
- Forecast the next 30 days for each store (
id_cols => ['store_id']) with TimesFM and 95% prediction intervals. Then view the first 5 forecast rows forSTORE_NYC_01:
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;'
Verification
Run the following check to confirm the row counts. historical_store_sales has 543 rows (3 stores × 181 days). q4_store_projections has 90 rows (3 stores × 30 days) with valid interval bounds:
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)."
The output is similar to the following:
Step 4 Verification Passed: historical_store_sales=543 rows, q4_store_projections=90,3,0 (rows,stores,invalid_bounds).
You now have 90 daily store forecasts with 95% prediction intervals, built without training a model. Next, you use the connection to call a generative model on many rows.
5. Run batch inference with retries
Forecasting worked on numbers. Now apply a generative model to text across many rows, which is where quotas and failed rows start to matter.
When you run generative AI functions over millions of rows, BigQuery sends many concurrent requests to Agent Platform. Without rate management, these workloads exceed quotas and fail.
BigQuery AI functions use dynamic shared quota (DSQ) to smooth bursts of traffic and batch prompts. They also return an error status for each row.
DSQ doesn't guarantee how many rows a single query processes. BigQuery publishes estimated rows per job for each AI function in Generative AI functions quotas. For large tables, split the work across several queries, save each result, and retry only the rows that failed, as this step shows.
- Create the
demand_intelligence.customer_transcriptstable with 300 customer service chat transcripts for three customer accounts:
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
- Classify the sentiment of each transcript with
AI.GENERATE. The call setsconnection_id,endpoint, andmodel_params, which follow the Agent PlatformGenerateContentRequestschema. Thought tokens count towardmax_output_tokens, so a very small limit can return an empty or cut-off result. The call sets 256 tokens and the minimal thinking level. It runs once per row inside a common table expression (CTE) namedraw_predictions, and the outer query reads every field of the returnedSTRUCT:
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
- Check the row statuses, then run the incremental retry pattern. It re-evaluates only rows that failed, for example with a transient
RESOURCE_EXHAUSTEDstatus. Rows that succeeded (execution_status = ''orNULL) aren't billed again:
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
Verification
Run the following check to confirm that scored_interactions has all 300 rows, no error statuses, and a positive count of billed 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)."
The output is similar to the following:
Step 5 Verification Passed: scored_interactions=300,300,TOKENS_OK (total_rows,succeeded_rows,token_status).
You now have sentiment labels for all 300 transcripts, with a MERGE retry that reruns only failed rows. Next, you limit how much data reaches the model.
6. Add cost guardrails
Batch inference bills for every row and token that reaches the model. In this step, you apply two guardrails in SQL and learn a third, project-level one:
- Materialization barrier pattern: Suppose you filter rows in a CTE with
WHERE REGEXP_CONTAINS(...)and pass that CTE toAI.GENERATE. The filter might not run first, so the model can process every base row. Writing the filtered rows to a temporary table withCREATE TEMP TABLEfirst means only matching rows reach the model. - One call per row: Writing
AI.GENERATE(...)once for.resultand again for.full_response.usage_metadatacalls the remote model twice per row. Call it once in a CTE (AS inference_payload) and read both fields from that alias. CTEs aren't materialized, so if you reference the CTE more than once or reuse the output in later queries, write it to a table first. - Daily token quotas: BigQuery caps generative AI tokens per day with quotas for each project (
GenAiInputTokensPerDay,GenAiOutputTokensPerDay) and for each user in a project (GenAiInputTokensPerUserPerDay,GenAiOutputTokensPerUserPerDay). Output quotas include thought tokens. Lowering them sets a hard daily spend ceiling. This lab doesn't change them, because they apply to the whole project. To set them, see Control costs for generative AI.
In production, also deduplicate identical prompts before you call AI.GENERATE and join the results back, because each row is a separate model call even when its prompt repeats.
- Run the governed pipeline. It writes the
candidate_recordstemporary table and makes one model call per row:
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
Verification
Run the following check to confirm that AI.GENERATE processed only the 100 matching churn transcripts out of 300, and recorded billed tokens:
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)."
The output is similar to the following:
Step 6 Verification Passed: actionable_churn_alerts=100,100,BILLED_OK (evaluated_rows,valid_extractions,billing_audit).
You now have an actionable_churn_alerts table built from only the 100 matching rows, with one model call per row. Your work is complete, so clean up the resources.
7. Clean up
To avoid ongoing charges to your Google Cloud account, delete the resources that you created in this codelab.
In Cloud Shell, delete the dataset, the connection, and the temporary SQL files:
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."
Your project no longer has the dataset or connection from this codelab.
8. Congratulations
You ran BigQuery AI functions at scale and kept their cost predictable. You learned how to:
- Enable the APIs that BigQuery AI functions need.
- Call Agent Platform models from BigQuery through a connection and its service account, instead of user credentials.
- Forecast time series without training a model, using TimesFM and
AI.FORECAST. - Run batch inference with
AI.GENERATEand retry only the rows that failed. - Limit model costs with a temporary table filter, a single model call per row, and token settings.
9. Related codelabs
- Multimodal analytics and zero-shot forecasting with Google Cloud: more zero-shot forecasting with BigQuery.
- Semantic Analysis in BigQuery with managed AI functions and SQL: an introduction to BigQuery managed AI functions.