iT邦幫忙

2026 iThome 鐵人賽

DAY 13
0
Build on Google AI

將考國際證照的應用程式變成開源系列 第 19

學習筆記: 使用 Gemini 和 Cloud Run 中的 BigQuery MCP 伺服器建構及部署 AI 代理

  • 分享至 

  • xImage
  •  
  • 使用 Gemini 和 Cloud Run 中的 BigQuery MCP 伺服器建構及部署 AI 代理

https://codelabs.developers.google.com/codelabs/cloud-run/cloud-run-adk-gemini-bq-mcp#1

https://vta-qsx55luj.gca-americas.dev/

這是在 Google Cloud Shell 或本地端命令列介面 (CLI) 進行環境設定與需求的完整步驟與詳細說明:

1. 設定預設專案與 Cloud Run 區域

首先,您需要告訴 gcloud 指令列工具,接下來的操作都要針對哪一個專案以及在哪個地理區域執行。

設定您的專案 ID:

gcloud config set project YOUR_PROJECT_ID

  • 說明: 請務必將 YOUR_PROJECT_ID 替換為您在 Google Cloud 上的實際專案 ID。

設定 Cloud Run 區域:

gcloud config set run/region CLOUD-RUN-REGION

  • 說明:CLOUD-RUN-REGION 替換為支援 Cloud Run 的區域(例如 us-central1asia-east1 等)。

2. 設定環境變數

為了讓後續的指令操作更方便且不易出錯,您可以將以下指令寫入一個名為 env.sh 的腳本檔中。往後如果 Cloud Shell 重新啟動,只要執行 source env.sh 就能快速恢復環境變數設定。

# 從 gcloud 設定中自動抓取並設定 Cloud 專案 ID 與 Cloud Run 區域
export GOOGLE_CLOUD_PROJECT="${GOOGLE_CLOUD_PROJECT:-$(gcloud config get-value project -q)}"
export GOOGLE_CLOUD_REGION="${GOOGLE_CLOUD_REGION:-$(CR_REGION=$(gcloud config get-value run/region -q 2>/dev/null); echo "${CR_REGION:-us-central1}")}"

# 設定在 Agent Platform 中使用 Gemini API
export GOOGLE_GENAI_USE_ENTERPRISE="True"

# 使用全域 (global) 的 Gemini API 端點
export GOOGLE_CLOUD_LOCATION="global"

  • 說明:
  • 前兩段程式碼會自動去讀取您在「步驟 1」設定的專案 ID 與區域。如果讀取不到區域,則會預設給予 us-central1
  • 後兩段則是針對 Gemini API 的必要環境參數設定。
  • 安全提示: 如果您將這些變數儲存為 env.sh,請不要將該檔案提交到版本控制系統 (如 Git) 內。

3. 啟用必要的雲端服務 API

在開始建立與部署 Agent 之前,必須先在專案中開啟相關的 Google Cloud API。這個啟用過程大約需要 2 到 3 分鐘的時間。

gcloud services enable --project "${GOOGLE_CLOUD_PROJECT}" \
    run.googleapis.com \
    cloudbuild.googleapis.com \
    artifactregistry.googleapis.com \
    bigquery.googleapis.com \
    aiplatform.googleapis.com

  • 詳細服務說明:
  • run.googleapis.com:啟用 Cloud Run(用來託管與運行您的 AI Agent)。
  • cloudbuild.googleapis.com:啟用 Cloud Build(用來建置應用程式的容器映像檔)。
  • artifactregistry.googleapis.com:啟用 Artifact Registry(用來存放建置好的容器映像檔)。
  • bigquery.googleapis.com:啟用 BigQuery(作為資料來源與 MCP 伺服器互動的標的)。
  • aiplatform.googleapis.com:啟用 Vertex AI(提供 Gemini 模型等相關 AI 基礎架構服務)。

以下是執行的過程記錄:

Welcome to Cloud Shell! Type "help" to get started.
To set your Cloud Platform project in this session use gcloud config set project [PROJECT_ID].
You can view your projects by running gcloud projects list.
ALAN@cloudshell:~$ cd data_agent/
ALAN@cloudshell:~/data_agent$ ls
agent.py eval_set_1.evalset.json init.py pycache requirements.txt
ALAN@cloudshell:~/data_agent$ cat init.py
from . import agent
ALAN@cloudshell:~/data_agent$ cat agent.py
import os

from google.adk.agents import LlmAgent
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams

import google.auth
from google.auth.transport.requests import Request

Fetch Application Default Credentials (ADC)

to use as agent's own identity for accessing BigQuery MCP Server

_application_default_credentials, project_id = google.auth.default()
_request = Request()
_application_default_credentials.refresh(_request)

Retrieve Google Cloud project to use.

project_id = os.getenv("GOOGLE_CLOUD_PROJECT", project_id)
if not project_id:
raise ValueError("GOOGLE_CLOUD_PROJECT environment variable is not set.")

Builds authentication headers for MCP Server requests,

and refreshes credentials if needed.

def _adc_auth_header_provider(context = None) -> dict[str, str]:
if not _application_default_credentials.valid:
_application_default_credentials.refresh(_request)

return {
    "Authorization": f"Bearer {_application_default_credentials.token}",
    "x-goog-user-project": project_id
}

Initialize the MCP Toolset with the connection parameters

bigquery_toolset = McpToolset(
connection_params=StreamableHTTPConnectionParams(
url="https://bigquery.googleapis.com/mcp",
tool_filter=[
'get_dataset_info',
'list_table_ids',
'get_table_info',
# Using readonly is a security measure to prevent accidental data modification.
'execute_sql_readonly',
]
),
header_provider=_adc_auth_header_provider # Auth header provider function
)

Configure the agent

system_instruction = f"""
You are a helpful assistant that can answer questions about data in BigQuery.
To answer the user's question, use data you have access to by using tools list_table_ids and get_table_info.
Your data is in bigquery-public-data.new_york_citibike dataset (Citi Bike trips and stations in the NYC area.)

Plan of action:
0. ALWAYS start by analyzing dataset.

  1. Analyze your data, investigate schema and dimensions by querying distrinct values of columns using execute_sql_readonly.
    Output information about tables, columns, their data types and sets of values (for dimensions).
    Note which columns can be joined or used in aggregations/filters, and what type conversion may be needed for joining or aggregating.
    DO NOT MAKE ASSUMPTIONS ABOUT DATA (structure, type, values, relationships) BASED ON YOUR PRIOR KNOWLEDGE. ALWAYS VERIFY YOUR ASSUMPTIONS.
  2. Understand and interpret the user's question.
  3. Formulate a plan to answer the user's question.
  4. Write a SQL query to retrieve relevant data in necessary form.
    This is where you must pay extra attention to column types and dimensions' sets of values.
  5. Retrieve data by generating BigQuery SQL and using execute_sql_readonly.
    Always use Dry Run to verify SQL correctness.
    Use {project_id} to run BigQuery queries (project_id parameter of execute_sql_readonly).

Do not use LaTeX in your responses. When giving a final answer, use Markdown.
"""

root_agent = LlmAgent(
model="gemini-3.6-flash",
name="data_agent",
instruction=system_instruction,
description="A helpful assistant that can answer questions using NYC Citibike data.",
tools=[bigquery_toolset]
)

ALAN@cloudshell:~/data_agent$ cat requirements.txt
echo -e "google-adk==2.4.\nmcp==1.29." > data_agent/requirements.txt

ALAN@cloudshell:~/data_agent$

ALAN@cloudshell:~ (ALAN)$ cd ~
ALAN@cloudshell:~ (ALAN)$ uv tool run --with "mcp==1.29." --from "google-adk[mcp]==2.4." adk web --allow_origins="*" --port 8080 .

您有哪些數據?

我擁有 紐約 Citi Bike(紐約市共享單車) 的數據集(位於 BigQuery bigquery-public-data.new_york_citibike)。

數據集主要包含以下兩張資料表:

  1. 騎乘紀錄表 (citibike_trips)
    包含 2013 年 7 月 1 日至 2018 年 5 月 31 日 期間,總計 58,937,715 筆 的單車騎乘紀錄。

時間與騎乘時長:
tripduration:騎乘時間(秒)
starttime / stoptime:借車與還車時間(紐約當地時間 DATETIME)
站點資訊:
start_station_id / start_station_name / start_station_latitude / start_station_longitude:起點站 ID、名稱、緯度、經度
end_station_id / end_station_name / end_station_latitude / end_station_longitude:終點站 ID、名稱、緯度、經度
車輛與用戶資訊:
bikeid:單車編號
usertype:用戶類型(Subscriber 年度會員 / Customer 24小時或7天單日/短期用戶)
birth_year:用戶出生年份
gender:性別(male 男性、female 女性、unknown 未知)
customer_plan:用戶計費方案名稱
2. 站點資訊表 (citibike_stations)
包含 2,509 個 共享單車站點的詳細位置與設施狀態資訊。

站點基本資訊與位置:
station_id:站點唯一識別碼(STRING 類型)
name / short_name:站點名稱與簡稱
latitude / longitude:站點經緯度
region_id:所屬區域/行政區 ID
容量與即時狀態:
capacity:站點車位總數
num_bikes_available / num_bikes_disabled:可用單車數 / 損壞單車數
num_docks_available / num_docks_disabled:可用空車位數 / 損壞車位數
is_installed / is_renting / is_returning:是否已安裝、是否提供租車、是否提供還車
rental_methods:支援的支付/租借方式
last_reported:站點狀態最後回報時間
💡 資料關聯提示: 若需要將 citibike_trips 與 citibike_stations 進行關聯(JOIN),請注意 citibike_trips 中的站點 ID(如 start_station_id)為 INTEGER 數字類型,而 citibike_stations 中的 station_id 為 STRING 字串類型,需使用 CAST(start_station_id AS STRING) 進行轉型。

We have budget for 3 coffee trucks. We want to find the best city bike stations to place our coffee trucks. 請用台灣中文回覆

根據 NYC Citi Bike 的歷史騎乘數據分析,咖啡車(Coffee Truck)的核心目標客群為早晨通勤族(週一至週五 06:00 - 10:00)。此時段人流量大、顧客購買咖啡的意願與頻率最高,且超過 93% 為每天往返的訂閱會員(Subscriber),具備極高的複購率。

綜合早晨尖峰總流量、目的地/出發地轉乘特性以及**地理位置不重複(避免自相殘殺)**的考量,建議將 3 輛咖啡車分別部署於以下 3 個最佳站點:

☕ 建議擺放位置與數據分析

  1. 第一輛咖啡車:中央車站入口(Grand Central Area)
    推薦站點: Pershing Square North / E 42 St & Vanderbilt Ave (Station ID: 519)
    早晨尖峰流量: 約 287,424 次(全紐約第 1 名)
    總騎乘次數: 超過 1,062,000 次
    會員比例: 93.8%
    選址優勢: 位於紐約中央車站(Grand Central Terminal)正門口,是曼哈頓東區最大的交通樞紐。每天早晨有數萬名搭乘火車與地鐵的上班族在此出站轉乘單車或步行,是擺放咖啡車的黃金首選。
  2. 第二輛咖啡車:賓州車站樞紐(Penn Station Area)
    推薦站點: 8 Ave & W 31 St (Station ID: 521)
    早晨尖峰流量: 約 166,213 次(全紐約第 3 名)
    總騎乘次數: 約 500,000 次
    會員比例: 93.4%
    選址優勢: 位於賓州車站(Penn Station)與 Moynihan Train Hall 出口處。數據顯示該站點早晨有高達 136,000+ 次 的「騎乘借出(Starts)」,代表大量從長島鐵路(LIRR)、紐澤西捷運(NJ Transit)下車的通勤族在此租車。在他們取車或出站時提供現煮咖啡,轉換率極高。
  3. 第三輛咖啡車:中城東區金融商辦區(Midtown East Office District)
    推薦站點: E 47 St & Park Ave (Station ID: 359)
    早晨尖峰流量: 約 191,818 次(全紐約第 2 名)
    總騎乘次數: 約 450,000 次
    會員比例: 95.5%(所有熱門站點中最高)
    選址優勢: 位於公園大道(Park Avenue)頂級商辦大樓聚落。數據顯示該站點早晨有超過 69%(132,600+ 次) 的騎乘為「還車目的地(Ends)」,代表上班族騎車抵達公司門口。咖啡車停放於此,能精準攔截準備步行進入辦公大樓的白領高消費族群。
    📊 3 輛咖啡車配置總結表
    咖啡車編號 站點名稱 主要客群與區域 早晨尖峰流量 (6-10 AM) 會員比例 最佳營運策略
    1 號車 Pershing Square North (E 42 St & Vanderbilt Ave) 中央車站轉乘族 287,424 93.8% 主打快速外帶、高流量外帶咖啡
    2 號車 8 Ave & W 31 St 賓州車站火車/地鐵出站族 166,213 93.4% 主打出站即買、搭配輕食早餐組合
    3 號車 E 47 St & Park Ave 公園大道商辦大樓抵達族 191,818 95.5% 主打精品咖啡、高單價高品質特調
    💡 備選地點(如需替代方案):

Union Square 聯合廣場 / 熨斗區: E 17 St & Broadway (Station ID: 497) 或 Broadway & E 22 St (Station ID: 402)
優勢:全天候人潮均高,除了早晨通勤外,午餐與下午茶時段亦有穩定客源。


上一篇
test-spec : integration-tests , e2e-tests , test-matrix
下一篇
ui-ux , design-system , screen-specifications , interaction-patterns
系列文
將考國際證照的應用程式變成開源25
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言