Deploy a RAG AI Agent with Claude in Streamlit using Google ADK, Firestore, and Cloud Run

1. Introduction

In this codelab, you build an interactive AI Barista agent for a coffee shop. You use Google's open-source Agent Development Kit (ADK) with Anthropic's Claude Opus 5 model on Gemini Enterprise Agent Platform. To ground the agent's recommendations, you store the menu in Firestore and use vector search to find the relevant items, a technique called Retrieval-Augmented Generation (RAG). Finally, you wrap the agent in a Streamlit chat app and deploy it to Cloud Run behind Identity-Aware Proxy (IAP).

What you'll do

  • Enable Claude Opus 5 in Model Garden.
  • Store the menu in a Firestore database, with a vector embedding for each item.
  • Build an AI agent with the ADK LlmAgent and Claude, and give it a tool that searches the menu.
  • Wrap the agent in a Streamlit chat application that manages conversation history.
  • Deploy the app to Cloud Run from source, and restrict access to it with IAP.
  • Test RAG grounding, allergen awareness, and live menu updates.

What you'll need

  • A web browser such as Chrome.
  • A Google Cloud project with billing enabled.
  • Permission to enable Claude models in Model Garden. This requires the Consumer Procurement Entitlement Manager role (roles/consumerprocurement.entitlementManager).
  • Basic familiarity with Python.

This codelab is for developers of all levels, including beginners.

Estimated cost: A few US dollars or less. Most of the cost is Claude usage, which is billed per token. For current rates, see Agent Platform pricing.

2. Before you begin

Create a Google Cloud project

  1. In the Google Cloud console, select or create a Google Cloud project.
  2. Make sure that billing is enabled for your Cloud project. Learn how to confirm billing is enabled on a project.

Start Cloud Shell

  1. Click Activate Cloud Shell at the top of the Google Cloud console.

Activate Cloud Shell

  1. Verify authentication:

Authorize Cloud Shell

gcloud auth list
  1. Confirm your active project is set:
gcloud config get project

If the project ID shown is not correct or none is set, run:

gcloud config set project <YOUR_PROJECT_ID>

Enable APIs

Run this command to enable all the required APIs:

gcloud services enable \
  run.googleapis.com \
  aiplatform.googleapis.com \
  cloudbuild.googleapis.com \
  artifactregistry.googleapis.com \
  firestore.googleapis.com \
  iap.googleapis.com

Enable Claude Opus 5 in Model Garden

You must enable a Claude model in your project before you can call it.

  1. In the Google Cloud console, open the Claude Opus 5 model card in Model Garden.
  2. Click Enable, and then follow the prompts to accept Anthropic's terms.

You'll confirm that you can call the model in the next step.

3. Set up your project

In this step, you initialize environment variables, create a working directory with a Python virtual environment, and confirm that you can call Claude.

  1. In your active Cloud Shell session, initialize the following project environment variables:
export PROJECT_ID=$(gcloud config get-value project)
export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")

Note: Use closest region

Find your closest region and replace insert-region-here with it in the following command. Your Cloud Run service and Firestore database use this region. Claude requests go to Agent Platform's global endpoint, wherever your app runs.

export REGION=[insert-region-here]
  1. Create and change into a new project directory named coffee-barista-agent:
mkdir coffee-barista-agent && cd coffee-barista-agent
  1. Create and activate a Python virtual environment. You'll use it to run scripts in Cloud Shell:
python3 -m venv .venv
source .venv/bin/activate
  1. Create and open .gcloudignore in the Cloud Shell Editor. This file keeps the virtual environment out of the upload when you deploy:
cloudshell edit .gcloudignore
  1. Paste the following content into the editor and save the 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

Verify that you can call Claude

Send a test request to 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!"}]
  }'

The response is a JSON message from claude-opus-5. Its content list ends with a text block that contains Claude's reply, and it might start with a thinking block. If you get a 404 error, check that you enabled the model in Model Garden.

4. Create the menu database in Firestore

To ground the AI Barista and prevent it from recommending items that don't exist, you store the menu in Firestore. Each menu item gets a vector embedding: a list of numbers that captures the item's meaning. At runtime, the agent's tool searches for the items that are closest in meaning to what the customer asks for.

Create the Firestore database

Run the following command to create a Firestore database named coffee-menu in Native mode:

gcloud firestore databases create --database=coffee-menu --location=$REGION

Create the menu data

  1. Create and open menu.json in the Cloud Shell Editor:
cloudshell edit menu.json
  1. Paste the following JSON content into the editor and save the 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"]
  }
]
  1. Verify that the JSON file is correctly formatted:
cat menu.json | python3 -m json.tool > /dev/null && echo "Valid JSON!"

Seed Firestore with the menu data

The seeding script reads menu.json, creates an embedding for each item with the text-embedding-005 model, and saves each item to the menu collection.

  1. Install the Firestore and Gen AI client libraries in your virtual environment:
pip install google-cloud-firestore==2.27.0 google-genai==2.11.0
  1. Create and open seed.py in the Cloud Shell Editor:
cloudshell edit seed.py
  1. Paste the following code to 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!")
  1. Run the script:
python3 seed.py

Create the vector index

To run vector searches on the menu, create a vector index on the embedding field. The text-embedding-005 model creates embeddings with 768 dimensions, so the index uses the same dimension:

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

The --async flag returns right away while the index builds in the background, which can take a few minutes. You can continue with the next step. Before you test the agent in step 7, run the following command and check that the index STATE is READY:

gcloud firestore indexes composite list --database=coffee-menu

Why store the menu in Firestore instead of in a

menu.json

file inside the app?

If the menu lives in the container image, every change, such as a new seasonal drink or a price update, requires rebuilding and redeploying the app. With Firestore, coffee shop managers can update the menu at any time, and the agent sees the change on the next request.

Vector search also keeps prompts small. Instead of sending the whole menu to Claude, the get_menu tool returns only the three items closest to the customer's request. If the menu grows from 8 items to 500, Claude still receives only a few items per search, which keeps token costs and latency low.

5. Build the ADK agent

Now you'll build the agent. You define a get_menu() tool that searches Firestore, and you pass it to an LlmAgent that uses Claude.

  1. Create and open requirements.txt in the Cloud Shell Editor:
cloudshell edit requirements.txt
  1. Paste the following dependencies into the editor and save the 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] is Anthropic's SDK with support for Agent Platform. ADK uses it to call Claude.

  1. Create and open agent.py in the Cloud Shell Editor:
cloudshell edit agent.py
  1. Paste the following code to 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
)
  1. Create and open app.py in the Cloud Shell Editor:
cloudshell edit app.py
  1. Paste the following code to 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}")

💬 Discussion: How does the agent call Claude?

Notice that agent.py never calls Claude directly, and it doesn't use an API key. The Claude object only records which model to use. When the agent runs, ADK calls Claude on Agent Platform through Anthropic's SDK, and it authenticates with Application Default Credentials. On Cloud Run, that's the service's identity.

Two details are specific to Claude:

  • Pass a Claude instance, not a model name. ADK only recognizes claude-3-* and claude-*-4* model names by itself. If you set model="claude-opus-5", the agent fails with Model claude-opus-5 not found.
  • Skip thought parts. Claude Opus 5 can return its reasoning as thinking blocks before its answer. ADK passes these to the app as parts with part.thought set to True, and app.py skips them so that customers see only the answer.

💬 Discussion: Memory State & Production Stores

Does the chat history stored inside Streamlit's

st.session_state

persist when a user closes their browser tab?

No, it doesn't. st.session_state is completely in-memory and unique to the active browser connection. If a user refreshes the page or closes the tab, their conversation history with the barista is lost.

For a production application, you would connect the ADK runner to a persistent session store. ADK provides built-in service abstractions (like SessionService) that make it simple to save and resume chat history across page reloads and devices.

6. Deploy the agent to Cloud Run

You will deploy the Streamlit application directly from source using Cloud Run's built-in buildpacks. To follow the principle of least privilege, you will create and deploy using a dedicated custom service account rather than using the default Compute Engine service account.

  1. Create a dedicated service account:
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"
  1. Grant the Agent Platform User role (roles/aiplatform.user) to the new service account. This role lets the app call Claude and the embedding model:
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:barista-agent-sa@$PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/aiplatform.user"
  1. Grant the Cloud Datastore User role (roles/datastore.user) to the service account. This role lets the app read the menu from Firestore:
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:barista-agent-sa@$PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/datastore.user"

Note: Although you're using Firestore in Native mode, Google Cloud uses the Cloud Datastore IAM roles to control access to Firestore.

  1. Deploy the service using gcloud run deploy. The --iap flag puts Identity-Aware Proxy in front of the app, so only people that you grant access can use it:
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
  1. Allow IAP to invoke the service:
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"
  1. Give your account access to the app through 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"
  1. Locate the service URL in the output of the deploy command.

💬 Discussion: Deploying from Source, IAM Security, and IAP

We deployed to Cloud Run using

gcloud run deploy --source

without creating a Dockerfile. How did Cloud Run figure out how to build and run our Python app?

Cloud Run uses buildpacks under the hood to analyze your source code. When it detects requirements.txt and Python source files, it builds a container with a Python runtime and your dependencies. The --command and --args flags tell the container to start Streamlit on the port that Cloud Run provides.

Why did we create the

barista-agent-sa

service account instead of using the default Compute Engine service account?

The default Compute Engine service account often has broad Editor permissions. If the app had a security bug, an attacker could use those permissions to read, change, or delete other resources in your project. The dedicated service account has only the two roles that the app needs: calling models on Agent Platform, and reading from Firestore.

Why put the app behind IAP instead of allowing unauthenticated access?

Every chat message calls Claude, and Claude usage is billed to your project. With IAP, users must sign in with their Google account, and only people that you grant the IAP-secured Web App User role (roles/iap.httpsResourceAccessor) can use the app.

7. Test the agent

Open the Cloud Run service URL in a web browser and sign in with your Google account. Then ask the AI Barista questions to test its grounding and safety constraints.

  1. In-menu request: Ask: "Recommend something strong and warm."Expected: The agent recommends the Espresso Solo.
  2. Out-of-menu trap: Ask: "Do you have a matcha frappuccino?"Expected: The agent politely declines and explains that it isn't on the menu.
  3. Allergen-aware request: Ask: "I'm lactose intolerant, what can I get?"Expected: The agent recommends only dairy-free items, such as the Oat Milk Honey Latte, Espresso Solo, or Cold Brew Coffee. It doesn't recommend the Seasonal Pumpkin Latte, Iced Caramel Macchiato, or Classic Croissant.

Update the menu without redeploying

To confirm that the agent is grounded in the live database, add a new menu item directly in Firestore, and check that the agent recommends it.

  1. In Cloud Shell, from the coffee-barista-agent directory with the virtual environment active, run the following command to add a new document to the menu collection:
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!')
"
  1. Refresh the app in your browser to clear the chat session and load the new database state.
  2. Notice that the Matcha Green Tea Latte now appears in the sidebar menu.
  3. Ask the chatbot: "Do you have any matcha drinks?"

The agent recommends the new Matcha Green Tea Latte, with the description and price that you just added. You didn't rebuild or redeploy the app, which confirms that the agent is grounded in your live Firestore database.

8. Clean up

To avoid ongoing charges to your Google Cloud billing account, delete the resources that you created.

Delete the Cloud Run service:

gcloud run services delete coffee-barista --region $REGION --quiet

Delete the container image that gcloud run deploy built from your source code and stored in Artifact Registry:

gcloud artifacts docker images delete \
  $REGION-docker.pkg.dev/$PROJECT_ID/cloud-run-source-deploy/coffee-barista \
  --delete-tags --quiet

Delete the custom service account:

gcloud iam service-accounts delete barista-agent-sa@$PROJECT_ID.iam.gserviceaccount.com --quiet

Delete the Firestore database:

gcloud firestore databases delete --database=coffee-menu --quiet

Optional step: Delete the entire project. ⚠️ ONLY do this if you created a dedicated project for this lab.

gcloud projects delete $PROJECT_ID

9. Congratulations

Congratulations! You have built and deployed a Retrieval-Augmented Generation (RAG) AI Barista agent using Claude, Google's ADK, Firestore, and Cloud Run.

What you've learned

  • Calling Claude models on Gemini Enterprise Agent Platform from ADK with the Claude model class.
  • Grounding an agent in live Firestore data with vector search.
  • Utilizing the ADK LlmAgent and InMemoryRunner.
  • Creating stateful chat experiences in Streamlit.
  • Deploying Streamlit to Cloud Run from source, with a least-privilege service account and IAP.

Reference docs