1. Introduzione
In questo codelab, creerai un agente AI Barista interattivo per un bar. Utilizzi l'Agent Development Kit (ADK) open source di Google con il modello Claude Opus 5 di Anthropic su Gemini Enterprise Agent Platform. Per fare il grounding dei suggerimenti dell'agente, archivia il menu in Firestore e utilizza Vector Search per trovare gli elementi pertinenti, una tecnica chiamata Retrieval-Augmented Generation (RAG). Infine, eseguirai il wrapping dell'agente in un'app di chat Streamlit e ne eseguirai il deployment in Cloud Run dietro Identity-Aware Proxy (IAP).
In questo lab proverai a:
- Abilita Claude Opus 5 in Model Garden.
- Archivia il menu in un database Firestore, con un vector embedding per ogni elemento.
- Crea un agente AI con ADK
LlmAgente Claude e forniscigli uno strumento che esegue ricerche nel menu. - Inserisci l'agente in un'applicazione di chat Streamlit che gestisce la cronologia delle conversazioni.
- Eseguire il deployment dell'app in Cloud Run dal codice sorgente e limitarne l'accesso con IAP.
- Testa il grounding RAG, la consapevolezza degli allergeni e gli aggiornamenti del menu in tempo reale.
Che cosa ti serve
- Un browser web come Chrome.
- Un progetto Google Cloud con la fatturazione abilitata.
- Autorizzazione ad abilitare i modelli Claude in Model Garden. È necessario il ruolo Consumer Procurement Entitlement Manager (
roles/consumerprocurement.entitlementManager). - Conoscenza di base di Python.
Questo codelab è rivolto a sviluppatori di tutti i livelli, inclusi i principianti.
Costo stimato: qualche dollaro statunitense o meno. La maggior parte del costo è l'utilizzo di Claude, che viene fatturato per token. Per le tariffe attuali, consulta Prezzi di Agent Platform.
2. Prima di iniziare
Crea un progetto Google Cloud
- Nella console Google Cloud, seleziona o crea un progetto cloud.
- Verifica che la fatturazione sia attivata per il tuo progetto Cloud. Scopri come verificare che la fatturazione sia abilitata per un progetto.
Avvia Cloud Shell
- Fai clic su Attiva Cloud Shell nella parte superiore della console Google Cloud.

- Verifica l'autenticazione:

gcloud auth list
- Verifica che il progetto attivo sia impostato:
gcloud config get project
Se l'ID progetto visualizzato non è corretto o non è impostato, esegui:
gcloud config set project <YOUR_PROJECT_ID>
Abilita API
Esegui questo comando per abilitare tutte le API richieste:
gcloud services enable \
run.googleapis.com \
aiplatform.googleapis.com \
cloudbuild.googleapis.com \
artifactregistry.googleapis.com \
firestore.googleapis.com \
iap.googleapis.com
Abilita Claude Opus 5 in Model Garden
Devi abilitare un modello Claude nel tuo progetto prima di poterlo chiamare.
- Nella console Google Cloud, apri la scheda del modello Claude Opus 5 in Model Garden.
- Fai clic su Abilita e segui le istruzioni per accettare i termini di Anthropic.
Nel passaggio successivo, verificherai che puoi chiamare il modello.
3. Configura il progetto
In questo passaggio, inizializzerai le variabili di ambiente, creerai una directory di lavoro con un ambiente virtuale Python e verificherai di poter chiamare Claude.
- Nella sessione attiva di Cloud Shell, inizializza le seguenti variabili di ambiente del progetto:
export PROJECT_ID=$(gcloud config get-value project)
export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")
Nota: utilizza la regione più vicina
Trova la regione più vicina e sostituisci insert-region-here con questa nel comando seguente. Il servizio Cloud Run e il database Firestore utilizzano questa regione. Le richieste di Claude vengono inviate all'endpoint global di Agent Platform, indipendentemente da dove viene eseguita l'app.
export REGION=[insert-region-here]
- Crea e spostati in una nuova directory di progetto denominata
coffee-barista-agent:
mkdir coffee-barista-agent && cd coffee-barista-agent
- Crea e attiva un ambiente virtuale Python. Lo utilizzerai per eseguire script in Cloud Shell:
python3 -m venv .venv
source .venv/bin/activate
- Crea e apri
.gcloudignorenell'editor di Cloud Shell. Questo file impedisce l'upload dell'ambiente virtuale durante il deployment:
cloudshell edit .gcloudignore
- Incolla i contenuti seguenti nell'editor e salva il file:
# 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
Verifica di poter chiamare Claude
Invia una richiesta di test a 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!"}]
}'
La risposta è un messaggio JSON di claude-opus-5. L'elenco content termina con un blocco text che contiene la risposta di Claude e potrebbe iniziare con un blocco thinking. Se ricevi un errore 404, verifica di aver abilitato il modello in Model Garden.
4. Crea il database del menu in Firestore
Per fornire un contesto all'AI Barista e impedire che consigli articoli che non esistono, memorizzi il menu in Firestore. Ogni voce di menu riceve un vector embedding: un elenco di numeri che acquisisce il significato della voce. In fase di runtime, lo strumento dell'agente cerca gli articoli con il significato più vicino a quello richiesto dal cliente.
Crea il database Firestore
Esegui questo comando per creare un database Firestore denominato coffee-menu in modalità Native:
gcloud firestore databases create --database=coffee-menu --location=$REGION
Crea i dati del menu
- Crea e apri
menu.jsonnell'editor di Cloud Shell:
cloudshell edit menu.json
- Incolla i seguenti contenuti JSON nell'editor e salva il file:
[
{
"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"]
}
]
- Verifica che il file JSON sia formattato correttamente:
cat menu.json | python3 -m json.tool > /dev/null && echo "Valid JSON!"
Inserisci i dati del menu in Firestore
Lo script di seeding legge menu.json, crea un embedding per ogni elemento con il modello text-embedding-005 e salva ogni elemento nella raccolta menu.
- Installa le librerie client di Firestore e AI generativa nel tuo ambiente virtuale:
pip install google-cloud-firestore==2.27.0 google-genai==2.11.0
- Crea e apri
seed.pynell'editor di Cloud Shell:
cloudshell edit seed.py
- Incolla il seguente codice in
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!")
- Esegui lo script:
python3 seed.py
Crea l'indice vettoriale
Per eseguire ricerche vettoriali sul menu, crea un indice vettoriale nel campo embedding. Il modello text-embedding-005 crea embedding con 768 dimensioni, quindi l'indice utilizza la stessa dimensione:
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
Il flag --async restituisce immediatamente il risultato mentre l'indice viene creato in background, il che può richiedere alcuni minuti. Puoi continuare con il passaggio successivo. Prima di testare l'agente nel passaggio 7, esegui il comando seguente e verifica che l'indice STATE sia READY:
gcloud firestore indexes composite list --database=coffee-menu
💬 Discussione: database live e Vector Search
Perché archiviare il menu in Firestore anziché in un
menu.json
all'interno dell'app?
Se il menu si trova nell'immagine container, ogni modifica, come una nuova bevanda stagionale o un aggiornamento dei prezzi, richiede la ricostruzione e il deployment dell'app. Con Firestore, i gestori del bar possono aggiornare il menu in qualsiasi momento e l'agente vede la modifica alla richiesta successiva.
Vector Search mantiene anche i prompt di piccole dimensioni. Anziché inviare l'intero menu a Claude, lo strumento get_menu restituisce solo i tre elementi più vicini alla richiesta del cliente. Se il menu passa da 8 a 500 elementi, Claude riceve comunque solo alcuni elementi per ricerca, il che mantiene bassi i costi dei token e la latenza.
5. Crea l'agente ADK
Ora creerai l'agente. Definisci uno strumento get_menu() che esegue ricerche in Firestore e lo passi a un LlmAgent che utilizza Claude.
- Crea e apri
requirements.txtnell'editor di Cloud Shell:
cloudshell edit requirements.txt
- Incolla le seguenti dipendenze nell'editor e salva il file:
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] è l'SDK di Anthropic con supporto per Agent Platform. ADK lo utilizza per chiamare Claude.
- Crea e apri
agent.pynell'editor di Cloud Shell:
cloudshell edit agent.py
- Incolla il seguente codice in
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
)
- Crea e apri
app.pynell'editor di Cloud Shell:
cloudshell edit app.py
- Incolla il seguente codice in
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}")
💬 Discussione: in che modo l'agente chiama Claude?
Tieni presente che agent.py non chiama mai Claude direttamente e non utilizza una chiave API. L'oggetto Claude registra solo il modello da utilizzare. Quando l'agente viene eseguito, ADK chiama Claude su Agent Platform tramite l'SDK di Anthropic e si autentica con le Credenziali predefinite dell'applicazione. In Cloud Run, si tratta dell'identità del servizio.
Due dettagli sono specifici di Claude:
- Passa un'istanza
Claude, non un nome di modello. ADK riconosce solo i nomi dei modelliclaude-3-*eclaude-*-4*. Se impostimodel="claude-opus-5", l'agente non va a buon fine conModel claude-opus-5 not found. - Salta le parti del pensiero. Claude Opus 5 può restituire il suo ragionamento sotto forma di blocchi di pensiero prima della risposta. ADK li trasmette all'app come parti con
part.thoughtimpostato suTrueeapp.pyli ignora in modo che i clienti vedano solo la risposta.
💬 Discussion: Memory State & Production Stores
Does the chat history stored inside Streamlit's
st.session_state
persistono quando un utente chiude la scheda del browser?
No, non funziona. st.session_state è completamente in memoria e univoco per la connessione del browser attiva. Se un utente aggiorna la pagina o chiude la scheda, la cronologia delle conversazioni con il barista viene persa.
Per un'applicazione di produzione, devi connettere l'esecutore ADK a un archivio di sessioni permanente. ADK fornisce astrazioni di servizi integrate (come SessionService) che semplificano il salvataggio e il ripristino della cronologia chat tra ricaricamenti di pagina e dispositivi.
6. Esegui il deployment dell'agente in Cloud Run
Eseguirai il deployment dell'applicazione Streamlit direttamente dall'origine utilizzando i buildpack integrati di Cloud Run. Per seguire il principio del privilegio minimo, creerai ed eseguirai il deployment utilizzando un service account personalizzato dedicato anziché il service account Compute Engine predefinito.
- Crea un service account dedicato:
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"
- Concedi il ruolo Agent Platform User (
roles/aiplatform.user) al nuovo service account. Questo ruolo consente all'app di chiamare Claude e il modello di embedding:
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:barista-agent-sa@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/aiplatform.user"
- Concedi il ruolo Cloud Datastore User (
roles/datastore.user) al service account. Questo ruolo consente all'app di leggere il menu da Firestore:
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:barista-agent-sa@$PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/datastore.user"
Nota: anche se utilizzi Firestore in modalità Native, Google Cloud utilizza i ruoli IAM di Cloud Datastore per controllare l'accesso a Firestore.
- Esegui il deployment del servizio utilizzando
gcloud run deploy. Il flag--iapposiziona Identity-Aware Proxy davanti all'app, in modo che solo le persone a cui concedi l'accesso possano utilizzarla:
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
- Consenti a IAP di richiamare il servizio:
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"
- Concedi al tuo account l'accesso all'app tramite 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"
- Individua l'URL del servizio nell'output del comando di deployment.
💬 Discussion: Deploying from Source, IAM Security, and IAP
Abbiamo eseguito il deployment in Cloud Run utilizzando
gcloud run deploy --source
senza creare un Dockerfile. In che modo Cloud Run ha capito come creare ed eseguire la nostra app Python?
Cloud Run utilizza i buildpack in background per analizzare il codice sorgente. Quando rileva i file di origine requirements.txt e Python, crea un container con un runtime Python e le tue dipendenze. I flag --command e --args indicano al container di avviare Streamlit sulla porta fornita da Cloud Run.
Perché abbiamo creato le
barista-agent-sa
service account instead of using the default Compute Engine service account?
Il service account predefinito di Compute Engine dispone spesso di ampie autorizzazioni Editor. Se l'app presentava un bug di sicurezza, un malintenzionato potrebbe utilizzare queste autorizzazioni per leggere, modificare o eliminare altre risorse nel progetto. Il service account dedicato ha solo i due ruoli necessari all'app: chiamare i modelli su Agent Platform e leggere da Firestore.
Perché proteggere l'app con IAP anziché consentire l'accesso non autenticato?
Ogni messaggio chat chiama Claude e l'utilizzo di Claude viene fatturato al tuo progetto. Con IAP, gli utenti devono accedere con il proprio Account Google e solo le persone a cui concedi il ruolo Utente app web protetta da IAP (roles/iap.httpsResourceAccessor) possono utilizzare l'app.
7. Testa l'agente
Apri l'URL del servizio Cloud Run in un browser web e accedi con il tuo Account Google. Poi, fai domande all'AI Barista per testare il grounding e i vincoli di sicurezza.
- Richiesta dal menu: chiedi: "Consigliami qualcosa di forte e caldo".Risultato previsto: l'agente consiglia l'Espresso Solo.
- Trappola fuori menu: chiedi: "Avete un frappuccino al matcha?"Risposta prevista: l'agente rifiuta educatamente e spiega che non è nel menu.
- Richiesta relativa agli allergeni: chiedi: "Sono intollerante al lattosio, cosa posso prendere?"Risultato previsto: l'agente consiglia solo prodotti senza lattosio, come il latte di avena e miele, l'espresso singolo o il caffè cold brew. Non consiglia il Seasonal Pumpkin Latte, l'Iced Caramel Macchiato o il Classic Croissant.
Aggiorna il menu senza rifare il deployment
Per verificare che l'agente sia basato sul database attivo, aggiungi un nuovo elemento del menu direttamente in Firestore e controlla che l'agente lo consigli.
- In Cloud Shell, dalla directory
coffee-barista-agentcon l'ambiente virtuale attivo, esegui questo comando per aggiungere un nuovo documento alla raccoltamenu:
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!')
"
- Aggiorna l'app nel browser per cancellare la sessione di chat e caricare il nuovo stato del database.
- Noterai che il Matcha Green Tea Latte ora appare nel menu della barra laterale.
- Chiedi al chatbot: "Avete bevande al matcha?"
L'agente consiglia il nuovo Matcha Green Tea Latte, con la descrizione e il prezzo che hai appena aggiunto. Non hai ricreato l'app o rifatto il deployment, il che conferma che l'agente è basato sul tuo database Firestore in produzione.
8. Esegui la pulizia
Per evitare addebiti continui sul tuo account di fatturazione Google Cloud, elimina le risorse che hai creato.
Elimina il servizio Cloud Run:
gcloud run services delete coffee-barista --region $REGION --quiet
Elimina l'immagine container creata da gcloud run deploy dal tuo codice sorgente e archiviata in Artifact Registry:
gcloud artifacts docker images delete \
$REGION-docker.pkg.dev/$PROJECT_ID/cloud-run-source-deploy/coffee-barista \
--delete-tags --quiet
Elimina il service account personalizzato:
gcloud iam service-accounts delete barista-agent-sa@$PROJECT_ID.iam.gserviceaccount.com --quiet
Elimina il database Firestore:
gcloud firestore databases delete --database=coffee-menu --quiet
Passaggio facoltativo: elimina l'intero progetto. ⚠️ Esegui questa operazione SOLO se hai creato un progetto dedicato per questo lab.
gcloud projects delete $PROJECT_ID
9. Complimenti
Complimenti! Hai creato ed eseguito il deployment di un agente AI Barista con RAG (Retrieval-Augmented Generation) utilizzando Claude, l'ADK di Google, Firestore e Cloud Run.
Che cosa hai imparato
- Chiamata dei modelli Claude su Gemini Enterprise Agent Platform dall'ADK con la classe di modelli
Claude. - Grounding di un agente nei dati Firestore in tempo reale con Vector Search.
- Utilizzo di ADK
LlmAgenteInMemoryRunner. - Creazione di esperienze di chat stateful in Streamlit.
- Deployment di Streamlit in Cloud Run dall'origine, con un service account con privilegi minimi e IAP.