Google ADK、Firestore、Cloud Run を使用して、Streamlit で Claude を使用する RAG AI エージェントをデプロイする

1. はじめに

この Codelab では、コーヒー ショップ向けのインタラクティブな AI バリスタ エージェントを構築します。Gemini Enterprise Agent Platform で、Google のオープンソースの Agent Development Kit(ADK)と Anthropic の Claude Opus 5 モデルを使用します。エージェントのレコメンデーションをグラウンディングするために、メニューを Firestore に保存し、ベクトル検索を使用して関連するアイテムを見つけます。この手法は、検索拡張生成(RAG)と呼ばれます。最後に、エージェントを Streamlit チャットアプリにラップし、Identity-Aware Proxy(IAP)の背後にある Cloud Run にデプロイします。

演習内容

  • Model Garden で Claude Opus 5 を有効にします。
  • メニューを Firestore データベースに保存し、各アイテムにベクトル エンベディングを付加する。
  • ADK LlmAgent と Claude を使用して AI エージェントを構築し、メニューを検索するツールをエージェントに提供します。
  • 会話履歴を管理する Streamlit チャット アプリケーションでエージェントをラップする。
  • ソースから Cloud Run にアプリをデプロイし、IAP でアプリへのアクセスを制限する。
  • RAG グラウンディング、アレルゲンに関する認識、メニューのライブ更新をテストします。

必要なもの

  • ウェブブラウザ(Chrome など)。
  • 課金を有効にした Google Cloud プロジェクト
  • Model Garden で Claude モデルを有効にする権限。これには、Consumer Procurement Entitlement 管理者のロール(roles/consumerprocurement.entitlementManager)が必要です。
  • Python の基本的な知識。

この Codelab は、初心者を含むあらゆるレベルのデベロッパーを対象としています。

推定費用: 数米ドル以下。費用のほとんどは Claude の使用料金で、トークンごとに請求されます。現在の料金については、Agent Platform の料金をご覧ください。

2. 始める前に

Google Cloud プロジェクトを作成する

  1. Google Cloud コンソールで、Google Cloud プロジェクトを選択または作成します。
  2. Cloud プロジェクトに対して課金が有効になっていることを確認します。プロジェクトで課金が有効になっていることを確認する方法をご覧ください。

Cloud Shell の起動

  1. Google Cloud コンソールの上部にある「Cloud Shell をアクティブにする」アイコンをクリックします。

Cloud Shell をアクティブにする

  1. 認証を確認します。

Cloud Shell の承認

gcloud auth list
  1. アクティブなプロジェクトが設定されていることを確認します。
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 モデルを呼び出す前に、プロジェクトで有効にする必要があります。

  1. Google Cloud コンソールで、Model Garden の Claude Opus 5 モデルカードを開きます。
  2. [有効にする] をクリックし、プロンプトに沿って Anthropic の利用規約に同意します。

次のステップで、モデルを呼び出せることを確認します。

3. プロジェクトをセットアップする

このステップでは、環境変数を初期化し、Python 仮想環境を使用して作業ディレクトリを作成し、Claude を呼び出せることを確認します。

  1. アクティブな 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]
  1. coffee-barista-agent という名前の新しいプロジェクト ディレクトリを作成して、そのディレクトリに移動します。
mkdir coffee-barista-agent && cd coffee-barista-agent
  1. Python 仮想環境を作成してアクティブにします。このサービス アカウントを使用して、Cloud Shell でスクリプトを実行します。
python3 -m venv .venv
source .venv/bin/activate
  1. Cloud Shell エディタで .gcloudignore を作成して開きます。このファイルにより、デプロイ時に仮想環境がアップロードから除外されます。
cloudshell edit .gcloudignore
  1. 次の内容をエディタに貼り付けて、ファイルを保存します。
# 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 Barista をグラウンディングし、存在しないアイテムを推奨しないようにするために、メニューを Firestore に保存します。各メニュー項目は、項目の意味を捉えた数値のリストであるベクトル エンベディングを取得します。実行時に、エージェントのツールは、お客様が求めているものに最も近い意味を持つアイテムを検索します。

Firestore データベースを作成する

次のコマンドを実行して、ネイティブ モードで coffee-menu という名前の Firestore データベースを作成します。

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

メニューデータを作成する

  1. Cloud Shell エディタで menu.json を作成して開きます。
cloudshell edit menu.json
  1. 次の 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"]
  }
]
  1. JSON ファイルの形式が正しいことを確認します。
cat menu.json | python3 -m json.tool > /dev/null && echo "Valid JSON!"

メニューデータを使用して Firestore をシードする

シーディング スクリプトは menu.json を読み取り、text-embedding-005 モデルを使用して各アイテムのエンベディングを作成し、各アイテムを menu コレクションに保存します。

  1. 仮想環境に Firestore と生成 AI のクライアント ライブラリをインストールします。
pip install google-cloud-firestore==2.27.0 google-genai==2.11.0
  1. Cloud Shell エディタで seed.py を作成して開きます。
cloudshell edit seed.py
  1. 次のコードを 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. スクリプトを実行します。
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 に送信するのではなく、お客様のリクエストに最も近い 3 つのアイテムのみを返します。メニューが 8 項目から 500 項目に増えても、Claude が検索ごとに受け取る項目は数個のみであるため、トークン費用とレイテンシを低く抑えることができます。

5. ADK エージェントをビルドする

次に、エージェントを構築します。Firestore を検索する get_menu() ツールを定義し、Claude を使用する LlmAgent に渡します。

  1. Cloud Shell エディタで requirements.txt を作成して開きます。
cloudshell edit requirements.txt
  1. 次の依存関係をエディタに貼り付けて、ファイルを保存します。
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] は、Agent Platform をサポートする Anthropic の SDK です。ADK はこれを使用して Claude を呼び出す。

  1. Cloud Shell エディタで agent.py を作成して開きます。
cloudshell edit agent.py
  1. 次のコードを 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. Cloud Shell エディタで app.py を作成して開きます。
cloudshell edit app.py
  1. 次のコードを 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 では、これがサービスの ID になります。

Claude に固有の詳細は次の 2 つです。

  • モデル名ではなく、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 サービス アカウントを使用するのではなく、専用のカスタム サービス アカウントを使用して作成とデプロイを行います。

  1. 専用のサービス アカウントを作成します。
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. 新しいサービス アカウントに 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"
  1. サービス アカウントに 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 へのアクセスを制御します。

  1. 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
  1. 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"
  1. 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. deploy コマンドの出力でサービス URL を見つけます。

💬 ディスカッション: ソースからのデプロイ、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 サービス アカウントには、広範な編集権限が付与されていることがよくあります。アプリにセキュリティ バグがある場合、攻撃者はこれらの権限を使用して、プロジェクト内の他のリソースを読み取り、変更、削除できます。専用のサービス アカウントには、アプリに必要な 2 つのロール(Agent Platform でモデルを呼び出すロールと、Firestore から読み取るロール)のみが付与されています。

未認証のアクセスを許可するのではなく、アプリを IAP の背後に配置する理由は何ですか?

チャット メッセージごとに Claude が呼び出され、Claude の使用料金がプロジェクトに請求されます。IAP を使用する場合、ユーザーは Google アカウントでログインする必要があります。また、IAP で保護されたウェブアプリ ユーザーのロール(roles/iap.httpsResourceAccessor)を付与したユーザーのみがアプリを使用できます。

7. エージェントをテストする

ウェブブラウザで Cloud Run サービスの URL を開き、Google アカウントでログインします。次に、AI Barista に質問して、グラウンディングと安全性の制約をテストします。

  1. メニュー内のリクエスト: 「濃くて温かいものを教えてください」と尋ねます。エージェントはエスプレッソ ソロをおすすめします。
  2. メニュー外のトラップ: 質問: 「抹茶フラペチーノはありますか?」期待される結果: エージェントは丁寧に断り、メニューにないことを説明します。
  3. アレルギー対応のリクエスト: 質問: 「乳糖不耐症なのですが、何が注文できますか?」期待される結果: エージェントは、オーツミルク ハニーラテ、エスプレッソ ソロ、コールドブリュー コーヒーなど、乳製品不使用のメニューのみを提案します。季節限定のパンプキン ラテ、アイス キャラメル マキアート、クラシック クロワッサンはおすすめしていません。

再デプロイせずにメニューを更新する

エージェントがライブ データベースにグラウンディングされていることを確認するには、Firestore に新しいメニュー項目を直接追加し、エージェントがそれを推奨することを確認します。

  1. 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!')
"
  1. ブラウザでアプリを更新して、チャット セッションをクリアし、新しいデータベースの状態を読み込みます。
  2. サイドバー メニューに Matcha Green Tea Latte が表示されていることを確認します。
  3. chatbot に「抹茶のドリンクはありますか?」と尋ねます。

エージェントは、追加したばかりの説明と価格を使用して、新しい抹茶ラテをおすすめします。アプリを再ビルドまたは再デプロイしていないため、エージェントが本番環境の 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 モデルを呼び出す。
  • ベクトル検索を使用して、ライブ Firestore データでエージェントをグラウンディングする。
  • ADK の LlmAgent と InMemoryRunner を利用する。
  • Streamlit でステートフルなチャット エクスペリエンスを作成する。
  • 最小権限のサービス アカウントと IAP を使用して、ソースから Cloud Run に Streamlit をデプロイする。

リファレンス ドキュメント