1. 简介
在此 Codelab 中,您将为一家咖啡店构建一个交互式 AI 咖啡师智能体。您在 Gemini Enterprise Agent Platform 上将 Google 的开源智能体开发套件 (ADK) 与 Anthropic 的 Claude Opus 5 模型搭配使用。为了让智能体能够提供基于事实的推荐,您需要将菜单存储在 Firestore 中,并使用 Vector Search 来查找相关商品,这种技术称为检索增强生成 (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 模型的权限。这需要 Consumer Procurement Entitlement Manager 角色 (
roles/consumerprocurement.entitlementManager)。 - 基本熟悉 Python。
本 Codelab 适合各种水平的开发者,包括新手。
预计费用:几美元或更少。大部分费用来自 Claude 用量,按 token 计费。如需了解当前费率,请参阅 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 Editor 中创建并打开
.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 Editor 中创建并打开
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 Editor 中创建并打开
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
创建向量索引
如需对菜单运行 Vector Search,请在 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,咖啡店经理可以随时更新菜单,而代理会在下次请求时看到更改。
Vector Search 还能让提示保持简短。get_menu 工具不会将整个菜单发送给 Claude,而是仅返回与客户请求最接近的三道菜。即使菜单从 8 项增加到 500 项,Claude 每次搜索仍只会收到几项,从而保持较低的 token 费用和延迟时间。
5. 构建 ADK 智能体
现在,您将构建代理。您定义一个用于搜索 Firestore 的 get_menu() 工具,并将其传递给使用 Claude 的 LlmAgent。
- 在 Cloud Shell Editor 中创建并打开
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 Editor 中创建并打开
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 Editor 中创建并打开
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 User 角色 (
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 User 角色 (
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 服务账号通常拥有宽泛的 Editor 权限。如果应用存在安全漏洞,攻击者可能会利用这些权限读取、更改或删除项目中的其他资源。该专属服务账号仅拥有应用所需的两个角色:在 Agent Platform 上调用模型,以及从 Firestore 读取数据。
为什么将应用置于 IAP 之后,而不是允许未经身份验证的访问?
每条聊天消息都会调用 Claude,Claude 用量会计入您的项目。借助 IAP,用户必须使用其 Google 账号登录,并且只有您授予 IAP-secured Web 应用用户角色 (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 结算账号持续收取费用,请删除您创建的资源。
删除 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 模型。 - 使用 Vector Search,让智能体以实时 Firestore 数据为依据。
- 利用 ADK
LlmAgent和InMemoryRunner。 - 在 Streamlit 中打造有状态的对话体验。
- 使用最小权限服务账号和 IAP,从源代码将 Streamlit 部署到 Cloud Run。