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) 進行環境設定與需求的完整步驟與詳細說明:
首先,您需要告訴 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-central1 或 asia-east1 等)。為了讓後續的指令操作更方便且不易出錯,您可以將以下指令寫入一個名為 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"
us-central1。env.sh,請不要將該檔案提交到版本控制系統 (如 Git) 內。在開始建立與部署 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
_application_default_credentials, project_id = google.auth.default()
_request = Request()
_application_default_credentials.refresh(_request)
project_id = os.getenv("GOOGLE_CLOUD_PROJECT", project_id)
if not project_id:
raise ValueError("GOOGLE_CLOUD_PROJECT environment variable is not set.")
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
}
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
)
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.
execute_sql_readonly.execute_sql_readonly.{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)。
數據集主要包含以下兩張資料表:
時間與騎乘時長:
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 個最佳站點:
☕ 建議擺放位置與數據分析
Union Square 聯合廣場 / 熨斗區: E 17 St & Broadway (Station ID: 497) 或 Broadway & E 22 St (Station ID: 402)
優勢:全天候人潮均高,除了早晨通勤外,午餐與下午茶時段亦有穩定客源。