1. 簡介
在本程式碼實驗室中,您將為咖啡店建構互動式 AI 咖啡師代理。您在 Gemini Enterprise Agent Platform 使用 Google 的開放原始碼 Agent Development Kit (ADK),搭配 Anthropic 的 Claude Opus 5 模型。為了確保代理提供的建議符合實際情況,您會將菜單儲存在 Firestore,並使用向量搜尋找出相關品項,這項技術稱為檢索增強生成 (RAG)。最後,您會將代理封裝至 Streamlit 即時通訊應用程式,並部署至 Cloud Run,由 Identity-Aware Proxy (IAP) 保護。
學習內容
- 在 Model Garden 啟用 Claude Opus 5。
- 將菜單儲存在 Firestore 資料庫中,並為每個品項建立向量嵌入。
- 使用 ADK
LlmAgent和 Claude 建構 AI 代理,並提供可搜尋菜單的工具。 - 將代理納入 Streamlit 對話應用程式,用於管理對話記錄。
- 從原始碼將應用程式部署至 Cloud Run,並使用 IAP 限制存取權。
- 測試 RAG 建立基準、過敏原資訊和即時菜單更新。
軟硬體需求
- 網路瀏覽器,例如 Chrome。
- 已啟用計費功能的 Google Cloud 專案。
- 可在 Model Garden 啟用 Claude 模型的權限。您必須具備用戶採購授權管理員角色 (
roles/consumerprocurement.entitlementManager),才能執行這項操作。 - 具備 Python 基本知識。
本程式碼實驗室適合各種程度的開發人員,包括初學者。
預估費用:幾美元或更少。大部分費用來自 Claude 用量,以詞元數量計費。如要瞭解目前的費率,請參閱「Agent Platform 定價」。
2. 事前準備
建立 Google Cloud 專案
- 在 Google Cloud 控制台中,選取或建立 Google Cloud 專案。
- 確認 Cloud 專案已啟用計費功能。瞭解如何確認專案已啟用計費功能。
啟動 Cloud Shell
- 點選 Google Cloud 控制台頂端的「啟用 Cloud Shell」。

- 驗證:

gcloud auth list
- 確認已設定有效專案:
gcloud config get project
如果顯示的專案 ID 不正確或未設定,請執行:
gcloud config set project <YOUR_PROJECT_ID>
啟用 API
執行下列指令,啟用所有必要 API:
gcloud services enable \
run.googleapis.com \
aiplatform.googleapis.com \
cloudbuild.googleapis.com \
artifactregistry.googleapis.com \
firestore.googleapis.com \
iap.googleapis.com
在 Model Garden 啟用 Claude Opus 5
您必須先在專案中啟用 Claude 模型,才能呼叫該模型。
- 在 Google Cloud 控制台,開啟 Model Garden 中的 Claude Opus 5 模型資訊卡。
- 按一下「啟用」,然後按照提示接受 Anthropic 的條款。
您將在下一個步驟確認是否能呼叫模型。
3. 設定專案
在這個步驟中,您將初始化環境變數、建立含有 Python 虛擬環境的目前使用的目錄,並確認可以呼叫 Claude。
- 在有效的 Cloud Shell 工作階段中,初始化下列專案環境變數:
export PROJECT_ID=$(gcloud config get-value project)
export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")
注意:請使用最近的區域
找出最靠近您的區域,然後在下列指令中,將 insert-region-here 替換為該區域。Cloud Run 服務和 Firestore 資料庫會使用這個區域。無論應用程式在何處執行,Claude 要求都會傳送至 Agent Platform 的 global 端點。
export REGION=[insert-region-here]
- 建立並變更為名為
coffee-barista-agent的新專案目錄:
mkdir coffee-barista-agent && cd coffee-barista-agent
- 建立並啟用 Python 虛擬環境。您將使用這個帳戶在 Cloud Shell 執行指令碼:
python3 -m venv .venv
source .venv/bin/activate
- 在 Cloud Shell 編輯器中建立並開啟
.gcloudignore。部署時,這個檔案會將虛擬環境排除在上傳範圍外:
cloudshell edit .gcloudignore
- 將下列內容貼到編輯器中,然後儲存檔案:
# Files excluded from `gcloud run deploy --source .` uploads.
# Cloud Build installs dependencies from requirements.txt, so the local
# virtualenv and Python bytecode caches are not needed in the container.
.gcloudignore
.git
.gitignore
.venv/
__pycache__/
*.pyc
.DS_Store
確認您可以呼叫 Claude
傳送測試要求至 Claude Opus 5:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://aiplatform.googleapis.com/v1/projects/$PROJECT_ID/locations/global/publishers/anthropic/models/claude-opus-5:rawPredict" \
-d '{
"anthropic_version": "vertex-2023-10-16",
"max_tokens": 100,
"messages": [{"role": "user", "content": "Hello, Claude!"}]
}'
回應是來自 claude-opus-5 的 JSON 訊息。content 清單結尾是包含 Claude 回覆的 text 區塊,開頭可能是 thinking 區塊。如果收到 404 錯誤,請確認您已在 Model Garden 啟用模型。
4. 在 Firestore 建立菜單資料庫
為了建立 AI 咖啡師的基準,避免推薦不存在的品項,您將菜單儲存在 Firestore 中。每個菜單品項都會取得向量嵌入,也就是擷取品項意義的數字清單。執行階段時,代理的工具會搜尋與顧客要求最相近的項目。
建立 Firestore 資料庫
執行下列指令,以原生模式建立名為 coffee-menu 的 Firestore 資料庫:
gcloud firestore databases create --database=coffee-menu --location=$REGION
建立菜單資料
- 在 Cloud Shell 編輯器中建立並開啟
menu.json:
cloudshell edit menu.json
- 將下列 JSON 內容貼到編輯器中,然後儲存檔案:
[
{
"name": "Espresso Solo",
"description": "A single shot of rich, bold espresso.",
"price": 2.50,
"tags": ["strong", "hot", "dairy-free", "sugar-free"],
"allergens": []
},
{
"name": "Oat Milk Honey Latte",
"description": "Creamy steamed oat milk with espresso and a touch of honey.",
"price": 5.00,
"tags": ["sweet", "hot", "dairy-free"],
"allergens": []
},
{
"name": "Cold Brew Coffee",
"description": "Smooth, slow-steeped cold brew served over ice.",
"price": 4.00,
"tags": ["strong", "cold", "dairy-free", "sugar-free"],
"allergens": []
},
{
"name": "Seasonal Pumpkin Latte",
"description": "Spiced pumpkin sauce, espresso, and steamed milk, topped with whipped cream.",
"price": 5.50,
"tags": ["sweet", "hot", "seasonal"],
"allergens": ["dairy"]
},
{
"name": "Classic Croissant",
"description": "Flaky, buttery traditional French pastry.",
"price": 3.50,
"tags": ["bakery", "savory"],
"allergens": ["wheat", "dairy"]
},
{
"name": "Vegan Blueberry Muffin",
"description": "Soft, sweet muffin packed with real blueberries, entirely plant-based.",
"price": 3.75,
"tags": ["bakery", "sweet", "dairy-free", "vegan"],
"allergens": ["wheat"]
},
{
"name": "Nitro Cold Brew",
"description": "Cold brew infused with nitrogen for a super smooth, creamy head.",
"price": 4.50,
"tags": ["strong", "cold", "dairy-free", "sugar-free"],
"allergens": []
},
{
"name": "Iced Caramel Macchiato",
"description": "Chilled milk and vanilla syrup marked with espresso and caramel drizzle.",
"price": 5.25,
"tags": ["sweet", "cold"],
"allergens": ["dairy"]
}
]
- 確認 JSON 檔案格式正確:
cat menu.json | python3 -m json.tool > /dev/null && echo "Valid JSON!"
將菜單資料填入 Firestore
播種指令碼會讀取 menu.json,使用 text-embedding-005 模型為每個項目建立嵌入,並將每個項目儲存至 menu 集合。
- 在虛擬環境中安裝 Firestore 和生成式 AI 用戶端程式庫:
pip install google-cloud-firestore==2.27.0 google-genai==2.11.0
- 在 Cloud Shell 編輯器中建立並開啟
seed.py:
cloudshell edit seed.py
- 將下列程式碼貼到
seed.py:
# seed.py
# ==============================================================================
# FIRESTORE DATABASE SEEDER & VECTOR EMBEDDING GENERATOR
# ------------------------------------------------------------------------------
# This script reads the local `menu.json` file, generates a vector embedding
# for each menu item's name and description using the `text-embedding-005`
# model on Gemini Enterprise Agent Platform, and uploads the enriched documents
# to the Cloud Firestore `coffee-menu` database (under the `menu` collection).
# This enables semantic/vector search over the coffee shop menu.
# ==============================================================================
import json
import os
from google import genai
from google.cloud import firestore
from google.cloud.firestore_v1.vector import Vector
# Initialize Firestore client targeting the 'coffee-menu' database
db = firestore.Client(database="coffee-menu")
# Initialize the Gen AI client on Agent Platform (vertexai=True) for embeddings
client = genai.Client(
vertexai=True,
project=os.environ.get("PROJECT_ID"),
location=os.environ.get("REGION", "us-central1")
)
# Load local menu items from JSON file
with open("menu.json", "r") as f:
menu_items = json.load(f)
for item in menu_items:
# Use the name as the document ID
doc_id = item["name"].lower().replace(" ", "-")
# Generate text embedding using Gemini Enterprise Agent Platform text-embedding-005 model
text_to_embed = f"{item['name']}: {item['description']}"
response = client.models.embed_content(
model="text-embedding-005",
contents=text_to_embed,
)
embedding = response.embeddings[0].values
# Add embedding vector to the menu item data
item["embedding"] = Vector(embedding)
# Save the enriched menu item document to the 'menu' collection in Firestore
db.collection("menu").document(doc_id).set(item)
print("Firestore menu collection seeded with vector embeddings successfully!")
- 執行指令碼:
python3 seed.py
建立向量索引
如要對菜單執行向量搜尋,請在 embedding 欄位建立向量索引。text-embedding-005 模型會建立 768 個維度的嵌入,因此索引會使用相同維度:
gcloud firestore indexes composite create \
--collection-group=menu \
--query-scope=COLLECTION \
--database=coffee-menu \
--field-config=field-path=embedding,vector-config='{"dimension":"768", "flat": "{}"}' \
--async
--async 旗標會立即傳回,而索引會在背景建構,可能需要幾分鐘的時間。您可以繼續進行下一個步驟。在步驟 7 測試代理前,請執行下列指令,確認索引 STATE 為 READY:
gcloud firestore indexes composite list --database=coffee-menu
💬 討論:即時資料庫和向量搜尋
為什麼要將選單儲存在 Firestore,而不是
menu.json
檔案?
如果菜單儲存在容器映像檔中,每次有任何變更 (例如新增季節性飲品或更新價格),都必須重新建構及部署應用程式。有了 Firestore,咖啡店經理可以隨時更新菜單,代理程式也會在下次要求時看到變更。
向量搜尋也能縮減提示大小。get_menu 工具不會將整個菜單傳送給 Claude,而是只傳回與顧客要求最相近的三個品項。即使菜單從 8 項增加到 500 項,Claude 每次搜尋仍只會收到幾項,因此能降低詞元成本和延遲時間。
5. 建構 ADK 代理
現在要建構代理。您定義了搜尋 Firestore 的 get_menu() 工具,並將其傳遞給使用 Claude 的 LlmAgent。
- 在 Cloud Shell 編輯器中建立並開啟
requirements.txt:
cloudshell edit requirements.txt
- 將下列依附元件貼到編輯器中,然後儲存檔案:
google-adk==2.2.0
streamlit==1.56.0
google-cloud-firestore==2.27.0
google-genai==2.11.0
anthropic[vertex]==1.8.0
anthropic[vertex] 是 Anthropic 的 SDK,支援 Agent Platform。ADK 會使用這項資訊呼叫 Claude。
- 在 Cloud Shell 編輯器中建立並開啟
agent.py:
cloudshell edit agent.py
- 將下列程式碼貼到
agent.py:
# agent.py
# ==============================================================================
# AI BACKEND & AGENT LOGIC (Google ADK)
# ------------------------------------------------------------------------------
# This file defines the core AI Barista Agent, its system instructions/persona,
# and the tools it can use (like searching the menu in Firestore). It exports
# an ADK `App` object that can be invoked by a frontend UI (such as app.py) or
# deployed.
# ==============================================================================
import json
import os
import google.auth
from google.adk.agents import LlmAgent
from google.adk.models.anthropic_llm import Claude
# [START get_menu]
from google import genai
from google.cloud import firestore
from google.cloud.firestore_v1.base_vector_query import DistanceMeasure
from google.cloud.firestore_v1.vector import Vector
def get_menu(query: str) -> str:
"""Retrieves coffee shop menu items matching the user's query.
Args:
query: The search query or preference to find matching menu items.
Returns:
str: A JSON string representing the list of top matching menu items.
"""
try:
# Initialize clients
db = firestore.Client(database="coffee-menu")
client = genai.Client()
# Generate embedding for the search query
response = client.models.embed_content(
model="text-embedding-005",
contents=query,
)
query_vector = response.embeddings[0].values
# Search the Firestore database using Vector Search
results = db.collection("menu").find_nearest(
vector_field="embedding",
query_vector=Vector(query_vector),
distance_measure=DistanceMeasure.COSINE,
limit=3,
).stream()
menu_data = []
for doc in results:
item = doc.to_dict()
# Remove embedding field to save tokens
item.pop("embedding", None)
menu_data.append(item)
return json.dumps(menu_data)
except Exception as e:
return json.dumps({"error": f"Could not retrieve menu: {str(e)}"})
# [END get_menu]
# Claude on Gemini Enterprise Agent Platform
# ------------------------------------------------------------------------------
# The agent runs on Anthropic's Claude (Opus 5 by default) through Gemini
# Enterprise Agent Platform, authenticated with Application Default Credentials.
# Newer Claude models are served from the `global` endpoint, so the location is
# set on the model's resource name. This keeps it independent of
# GOOGLE_CLOUD_LOCATION, which the embedding client in get_menu() uses.
# The model must be enabled for your project in Model Garden.
CLAUDE_MODEL = os.environ.get("CLAUDE_MODEL", "claude-opus-5")
CLAUDE_LOCATION = os.environ.get("CLAUDE_LOCATION", "global")
def _get_project_id() -> str:
"""Returns GOOGLE_CLOUD_PROJECT, falling back to the ADC default project."""
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
if not project_id:
_, project_id = google.auth.default()
if not project_id:
raise ValueError(
"Set GOOGLE_CLOUD_PROJECT to the project where Claude is enabled."
)
return project_id
# Creating this Claude object doesn't call Claude. It records which model to
# use, and ADK makes the calls through Anthropic's SDK when the agent runs.
#
# Use a Claude instance, not a model-name string. ADK only recognizes
# claude-3-* and claude-*-4* strings on its own, so model="claude-opus-5"
# fails with "Model claude-opus-5 not found."
claude_model = Claude(
model=(
f"projects/{_get_project_id()}/locations/{CLAUDE_LOCATION}"
f"/publishers/anthropic/models/{CLAUDE_MODEL}"
)
)
# Create the barista agent
barista_agent = LlmAgent(
name="barista_agent",
# Pass the Claude instance from above. On each turn, ADK sends the
# conversation to Claude and runs any tools that Claude asks for.
model=claude_model,
instruction="""You are a friendly barista at ☕ Coffee Shop.
Your job is to recommend drinks and pastries to customers based on their preferences.
Rules you MUST follow:
1. You must recommend items ONLY from the menu returned by get_menu().
2. Do NOT recommend or suggest any item that is not present in the menu.
3. If a user's preference is vague or unclear, ask exactly ONE friendly clarifying question to narrow down what they want (e.g., cold or hot, sweet or strong, coffee or pastry).
4. Be warm and welcoming, but remain professional.
5. Ground your recommendations in the actual tags, descriptions, and allergens listed in the menu (e.g., if a user is dairy-free, recommend ONLY items tagged 'dairy-free' or with no dairy allergens).
""",
tools=[get_menu]
)
from google.adk.apps import App
# Define the App object
app = App(
name="coffee_barista_app",
root_agent=barista_agent
)
- 在 Cloud Shell 編輯器中建立並開啟
app.py:
cloudshell edit app.py
- 將下列程式碼貼到
app.py:
# app.py
# ==============================================================================
# WEB FRONTEND & USER INTERFACE (Streamlit)
# ------------------------------------------------------------------------------
# This file builds the interactive web UI for the Coffee Shop Barista Bot.
# Responsibilities:
# 1. Renders the visual layout, coffee-themed header, and sidebar menu cards.
# 2. Manages per-user session state (session_id, chat message history).
# 3. Connects user chat inputs to the ADK `app` imported from `agent.py`
# using `InMemoryRunner` and displays the AI's responses.
# ==============================================================================
import streamlit as st
import json
# Set page config for a premium look
st.set_page_config(
page_title="☕ Coffee Shop - Barista Bot",
page_icon="☕",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS to make the header sticky (adapts to light/dark themes)
st.markdown("""
<style>
div[data-testid="element-container"]:has(.header-container),
div.element-container:has(.header-container) {
position: sticky;
top: 2.875rem;
z-index: 999;
background-color: transparent;
padding-bottom: 10px;
}
</style>
""", unsafe_allow_html=True)
# App Header (using inline styles for the permanent coffee theme look)
st.markdown("""
<div class="header-container" style="text-align: center; padding: 20px; background: linear-gradient(135deg, #8B5E3C, #6F4E37); color: white; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.1);">
<h1 style="margin: 0; font-size: 2.5rem; font-weight: 700; color: white;">☕ ☕ Coffee Shop</h1>
<p style="margin: 5px 0 0 0; font-size: 1.1rem; opacity: 0.9; color: white;">Your friendly AI Barista is ready to help you find the perfect drink or pastry!</p>
</div>
""", unsafe_allow_html=True)
# Load Menu for the sidebar
# [START load_menu]
from google.cloud import firestore
try:
db = firestore.Client(database="coffee-menu")
docs = db.collection("menu").stream()
menu_items = []
for doc in docs:
item = doc.to_dict()
item.pop("embedding", None)
menu_items.append(item)
except Exception as e:
st.error(f"Error loading menu from Firestore: {e}")
menu_items = []
# [END load_menu]
# Sidebar Menu & Configuration
with st.sidebar:
st.markdown("## ☕ Coffee Shop Menu")
st.markdown("Explore our offerings and ask the barista for recommendations.")
st.markdown("---")
for item in menu_items:
with st.container(border=True):
st.markdown(f"**{item['name']}** • **${item['price']:.2f}**")
st.caption(item['description'])
# Tags & Allergens as native badges
tags = " ".join([f"`{t}`" for t in item.get("tags", [])])
if tags:
st.markdown(tags)
allergens = ", ".join(item.get("allergens", []))
if allergens:
st.markdown(f"⚠️ *Allergens: {allergens}*")
# Chat Interface
if "session_id" not in st.session_state:
import uuid
st.session_state.session_id = str(uuid.uuid4())
if "runner" not in st.session_state:
from google.adk.runners import InMemoryRunner
from agent import app
st.session_state.runner = InMemoryRunner(app=app)
if "messages" not in st.session_state:
st.session_state.messages = [
{"role": "assistant", "content": "Welcome to ☕ Coffee Shop! What can I get started for you today?"}
]
# Display existing messages
for msg in st.session_state.messages:
with st.chat_message(msg["role"]):
st.markdown(msg["content"])
# User Input
if prompt := st.chat_input("Ask for recommendations (e.g., 'What dairy-free pastries do you have?')"):
# Display user message
with st.chat_message("user"):
st.markdown(prompt)
st.session_state.messages.append({"role": "user", "content": prompt})
# Generate response
with st.chat_message("assistant"):
try:
import asyncio
# Run the ADK runner asynchronously using asyncio.run
async def fetch_response():
return await st.session_state.runner.run_debug(
prompt,
session_id=st.session_state.session_id
)
res_events = asyncio.run(fetch_response())
# Show each text part as its own paragraph (Claude often sends a short
# preamble before calling a tool), and skip "thought" parts so the
# model's internal reasoning is never displayed.
response_text = "\n\n".join([
part.text
for event in res_events
if event.content and event.content.parts
for part in event.content.parts
if part.text and not part.thought
])
st.markdown(response_text)
st.session_state.messages.append({"role": "assistant", "content": response_text})
except Exception as e:
st.error(f"Apologies, I ran into an error: {e}")
💬 討論:代理如何呼叫 Claude?
請注意,agent.py 絕不會直接呼叫 Claude,也不會使用 API 金鑰。Claude 物件只會記錄要使用的模型。代理執行時,ADK 會透過 Anthropic 的 SDK 在 Agent Platform 呼叫 Claude,並使用應用程式預設憑證進行驗證。在 Cloud Run 中,這就是服務的身分。
Claude 有兩項專屬細節:
- 傳遞
Claude執行個體,而非模型名稱。ADK 只能自行辨識claude-3-*和claude-*-4*模型名稱。如果設定model="claude-opus-5",代理會失敗並顯示Model claude-opus-5 not found。 - 略過思考部分。Claude Opus 5 可在回覆前,以思考區塊的形式呈現推論過程。ADK 會將這些內容傳遞給應用程式,並將
part.thought設為True,而app.py會略過這些內容,因此顧客只會看到答案。
💬 討論:記憶體狀態和實際工作環境儲存庫
儲存在 Streamlit
st.session_state
在使用者關閉瀏覽器分頁後,是否會保留?
不會。st.session_state 完全在記憶體中,且僅適用於有效的瀏覽器連線。如果使用者重新整理頁面或關閉分頁,與咖啡師的對話記錄就會消失。
如果是正式版應用程式,您需要將 ADK 執行工具連結至永久工作階段儲存庫。ADK 提供內建服務抽象化 (例如 SessionService),可輕鬆儲存及接續對話記錄,即使重新載入頁面或切換裝置也沒問題。
6. 將代理部署至 Cloud Run
您將使用 Cloud Run 內建的 Buildpack,直接從原始碼部署 Streamlit 應用程式。為遵循最小權限原則,您將使用專屬的自訂服務帳戶建立及部署,而非使用預設的 Compute Engine 服務帳戶。
- 建立專屬服務帳戶:
gcloud iam service-accounts create barista-agent-sa \
--description="Service account for Coffee Barista ADK agent on Cloud Run" \
--display-name="Barista Agent Service Account"
- 將 Agent Platform 使用者角色 (
roles/aiplatform.user) 授予新的服務帳戶。這個角色可讓應用程式呼叫 Claude 和嵌入模型:
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:barista-agent-sa@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/aiplatform.user"
- 將 Cloud Datastore 使用者角色 (
roles/datastore.user) 授予服務帳戶。這個角色可讓應用程式從 Firestore 讀取菜單:
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:barista-agent-sa@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/datastore.user"
注意:雖然您使用的是原生模式的 Firestore,但 Google Cloud 會使用 Cloud Datastore IAM 角色控管 Firestore 的存取權。
- 使用
gcloud run deploy部署服務。--iap旗標會將 Identity-Aware Proxy 放在應用程式前方,因此只有您授予存取權的使用者才能使用:
gcloud run deploy coffee-barista \
--source . \
--region $REGION \
--no-allow-unauthenticated \
--iap \
--labels dev-tutorial=codelab-streamlit-rag-adk-claude \
--command "/cnb/lifecycle/launcher" \
--args "sh,-c,python3 -m streamlit run app.py --server.port=\$PORT --server.address=0.0.0.0" \
--service-account "barista-agent-sa@$PROJECT_ID.iam.gserviceaccount.com" \
--set-env-vars GOOGLE_GENAI_USE_ENTERPRISE=TRUE,GOOGLE_CLOUD_PROJECT=$PROJECT_ID,GOOGLE_CLOUD_LOCATION=global,CLAUDE_MODEL=claude-opus-5
- 允許 IAP 叫用服務:
gcloud run services add-iam-policy-binding coffee-barista \
--region $REGION \
--member="serviceAccount:service-$PROJECT_NUMBER@gcp-sa-iap.iam.gserviceaccount.com" \
--role="roles/run.invoker"
- 透過 IAP 授予帳戶應用程式存取權:
gcloud iap web add-iam-policy-binding \
--resource-type=cloud-run \
--service=coffee-barista \
--region=$REGION \
--member="user:$(gcloud config get-value account)" \
--role="roles/iap.httpsResourceAccessor"
- 在部署指令的輸出內容中,找出服務網址。
💬 討論:從來源部署、IAM 安全性和 IAP
我們使用 Cloud Run 部署
gcloud run deploy --source
,不必建立 Dockerfile。Cloud Run 如何知道要建構及執行 Python 應用程式?
Cloud Run 會在背景使用 buildpack 分析原始碼。偵測到 requirements.txt 和 Python 來源檔案時,系統會建構含有 Python 執行階段和依附元件的容器。--command 和 --args 旗標會指示容器在 Cloud Run 提供的通訊埠上啟動 Streamlit。
為什麼要建立
barista-agent-sa
服務帳戶,而非預設的 Compute Engine 服務帳戶?
預設 Compute Engine 服務帳戶通常具備廣泛的編輯者權限。如果應用程式有安全性錯誤,攻擊者可能會利用這些權限讀取、變更或刪除專案中的其他資源。專屬服務帳戶僅具備應用程式所需的兩個角色:在 Agent Platform 呼叫模型,以及讀取 Firestore。
為什麼要將應用程式置於 IAP 後方,而不是允許未經驗證的存取?
每則即時通訊訊息都會呼叫 Claude,Claude 使用費會計入專案。有了 IAP,使用者必須使用 Google 帳戶登入,而且只有您授予「受 IAP 保護的網頁應用程式使用者」角色 (roles/iap.httpsResourceAccessor) 的使用者才能使用應用程式。
7. 測試代理
在網路瀏覽器中開啟 Cloud Run 服務網址,並使用 Google 帳戶登入。接著向 AI 咖啡師提問,測試其基準和安全限制。
- 菜單內要求:詢問:「推薦濃郁的熱飲。」預期結果:代理推薦 Espresso Solo。
- 非菜單陷阱:詢問:「你們有抹茶星冰樂嗎?」預期結果:代理有禮貌地拒絕,並說明菜單上沒有這項商品。
- 過敏原相關要求:詢問:「我有乳糖不耐症,可以點什麼?」預期結果:代理只推薦不含乳製品的品項,例如燕麥奶蜂蜜拿鐵、單份濃縮咖啡或冷萃咖啡。不會推薦季節限定南瓜拿鐵、冰焦糖瑪奇朵或經典可頌。
更新選單,不需重新部署
如要確認代理是否以即時資料庫為基準,請直接在 Firestore 新增菜單項目,並確認代理是否會推薦該項目。
- 在 Cloud Shell 中,從已啟用虛擬環境的
coffee-barista-agent目錄執行下列指令,將新文件新增至menu集合:
python3 -c "
import os
from google import genai
from google.cloud import firestore
from google.cloud.firestore_v1.vector import Vector
db = firestore.Client(database='coffee-menu')
client = genai.Client(
vertexai=True,
project=os.environ.get('PROJECT_ID'),
location=os.environ.get('REGION', 'us-central1')
)
name = 'Matcha Green Tea Latte'
desc = 'Creamy steamed oat milk infused with premium Japanese matcha powder.'
res = client.models.embed_content(
model='text-embedding-005',
contents=f'{name}: {desc}'
)
embedding = res.embeddings[0].values
db.collection('menu').document('matcha-latte').set({
'name': name,
'description': desc,
'price': 5.50,
'tags': ['sweet', 'hot', 'dairy-free'],
'allergens': [],
'embedding': Vector(embedding)
})
print('Successfully added Matcha Latte with vector embeddings!')
"
- 在瀏覽器中重新整理應用程式,清除對話工作階段,並載入新的資料庫狀態。
- 請注意,抹茶拿鐵現在會顯示在側欄選單中。
- 向聊天機器人提問:「你們有抹茶飲品嗎?」
代理會推薦新的抹茶拿鐵,並附上您剛才新增的說明和價格。您並未重新建構或重新部署應用程式,這表示代理是以運作中的 Firestore 資料庫為基礎。
8. 清除
如要避免系統持續向您的 Google Cloud Billing 帳戶收取費用,請刪除您建立的資源。
刪除 Cloud Run 服務:
gcloud run services delete coffee-barista --region $REGION --quiet
刪除 gcloud run deploy 從原始碼建構並儲存在 Artifact Registry 的容器映像檔:
gcloud artifacts docker images delete \
$REGION-docker.pkg.dev/$PROJECT_ID/cloud-run-source-deploy/coffee-barista \
--delete-tags --quiet
刪除自訂服務帳戶:
gcloud iam service-accounts delete barista-agent-sa@$PROJECT_ID.iam.gserviceaccount.com --quiet
刪除 Firestore 資料庫:
gcloud firestore databases delete --database=coffee-menu --quiet
選用步驟:刪除整個專案。⚠️ 只有在您為本實驗室建立專屬專案時,才需要執行這項操作。
gcloud projects delete $PROJECT_ID
9. 恭喜
恭喜!您已使用 Claude、Google 的 ADK、Firestore 和 Cloud Run,建構並部署檢索增強生成 (RAG) AI 咖啡師代理。
目前所學內容
- 使用
Claude模型類別,從 ADK 呼叫 Gemini Enterprise Agent Platform 上的 Claude 模型。 - 使用向量搜尋,以即時 Firestore 資料建立代理基準。
- 運用 ADK
LlmAgent和InMemoryRunner。 - 在 Streamlit 建立有狀態的對話體驗。
- 使用最小權限服務帳戶和 IAP,從原始碼將 Streamlit 部署至 Cloud Run。