ติดตั้งใช้งาน RAG AI Agent ด้วย Claude ใน Streamlit โดยใช้ Google ADK, Firestore และ Cloud Run

1. บทนำ

ใน Codelab นี้ คุณจะได้สร้างตัวแทนบาริสต้า AI แบบอินเทอร์แอกทีฟสำหรับร้านกาแฟ คุณใช้ Agent Development Kit (ADK) แบบโอเพนซอร์สของ Google กับโมเดล Claude Opus 5 ของ Anthropic ใน Gemini Enterprise Agent Platform หากต้องการอิงข้อมูลคำแนะนำของ Agent คุณจะต้องจัดเก็บเมนูไว้ใน Firestore และใช้การค้นหาเวกเตอร์เพื่อค้นหารายการที่เกี่ยวข้อง ซึ่งเป็นเทคนิคที่เรียกว่า Retrieval-Augmented Generation (RAG) สุดท้าย คุณจะรวม Agent ไว้ในแอปแชท Streamlit และติดตั้งใช้งานใน Cloud Run หลัง Identity-Aware Proxy (IAP)

สิ่งที่คุณต้องทำ

  • เปิดใช้ Claude Opus 5 ใน Model Garden
  • จัดเก็บเมนูในฐานข้อมูล Firestore พร้อมการฝังเวกเตอร์สำหรับแต่ละรายการ
  • สร้าง AI Agent ด้วย ADK LlmAgent และ Claude แล้วมอบเครื่องมือที่ค้นหาเมนูให้
  • รวม Agent ไว้ในแอปพลิเคชันแชท Streamlit ที่จัดการประวัติการสนทนา
  • ทำให้แอปใช้งานได้ใน Cloud Run จากแหล่งที่มา และจำกัดการเข้าถึงแอปด้วย IAP
  • ทดสอบการอ้างอิง RAG, การรับรู้สารก่อภูมิแพ้ และการอัปเดตเมนูแบบเรียลไทม์

สิ่งที่คุณต้องมี

  • เว็บเบราว์เซอร์ เช่น Chrome
  • โปรเจ็กต์ Google Cloud ที่เปิดใช้การเรียกเก็บเงิน
  • สิทธิ์ในการเปิดใช้โมเดล Claude ใน Model Garden ซึ่งต้องใช้บทบาทผู้จัดการการให้สิทธิ์การจัดซื้อของผู้บริโภค (roles/consumerprocurement.entitlementManager)
  • มีความคุ้นเคยกับ Python ในระดับพื้นฐาน

Codelab นี้เหมาะสำหรับนักพัฒนาซอฟต์แวร์ทุกระดับ รวมถึงผู้เริ่มต้น

ค่าใช้จ่ายโดยประมาณ: ไม่เกิน 2-3 ดอลลาร์สหรัฐ ค่าใช้จ่ายส่วนใหญ่มาจากการใช้งาน Claude ซึ่งจะเรียกเก็บเงินต่อโทเค็น ดูอัตราปัจจุบันได้ที่ราคาของ Agent Platform

2. ก่อนเริ่มต้น

สร้างโปรเจ็กต์ Google Cloud

  1. ในคอนโซล Google Cloud ให้เลือกหรือสร้างโปรเจ็กต์ที่อยู่ในระบบคลาวด์ของ Google Cloud
  2. ตรวจสอบว่าได้เปิดใช้การเรียกเก็บเงินสำหรับโปรเจ็กต์ที่อยู่ในระบบคลาวด์แล้ว ดูวิธียืนยันว่าเปิดใช้การเรียกเก็บเงินในโปรเจ็กต์แล้ว

เริ่มต้น Cloud Shell

  1. คลิกเปิดใช้งาน Cloud Shell ที่ด้านบนของคอนโซล Google Cloud

เปิดใช้งาน Cloud Shell

  1. ยืนยันการตรวจสอบสิทธิ์:

ให้สิทธิ์ Cloud Shell

gcloud auth list
  1. ตรวจสอบว่าได้ตั้งค่าโปรเจ็กต์ที่ใช้งานอยู่แล้ว โดยทำดังนี้
gcloud config get project

หากรหัสโปรเจ็กต์ที่แสดงไม่ถูกต้องหรือไม่ได้ตั้งค่าไว้ ให้เรียกใช้คำสั่งต่อไปนี้

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

เปิดใช้ Claude Opus 5 ใน Model Garden

คุณต้องเปิดใช้โมเดล Claude ในโปรเจ็กต์ก่อนจึงจะเรียกใช้ได้

  1. ในคอนโซล Google Cloud ให้เปิดการ์ดโมเดล Claude Opus 5 ใน Model Garden
  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 จะส่งไปยังปลายทาง global ของ Agent Platform ไม่ว่าแอปของคุณจะทำงานที่ใดก็ตาม

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. สร้างและเปิด .gcloudignore ใน Cloud Shell Editor ไฟล์นี้จะเก็บสภาพแวดล้อมเสมือนไว้นอกการอัปโหลดเมื่อคุณทำให้ใช้งานได้
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!"}]
  }'

การตอบกลับเป็นข้อความ JSON จาก claude-opus-5 รายการ content จะลงท้ายด้วยบล็อก text ที่มีการตอบกลับของ Claude และอาจขึ้นต้นด้วยบล็อก thinking หากพบข้อผิดพลาด 404 ให้ตรวจสอบว่าคุณได้เปิดใช้โมเดลใน Model Garden แล้ว

4. สร้างฐานข้อมูลเมนูใน Firestore

คุณจัดเก็บเมนูไว้ใน Firestore เพื่อเป็นข้อมูลอ้างอิงสำหรับบาริสต้า AI และป้องกันไม่ให้แนะนำรายการที่ไม่มีอยู่ รายการเมนูแต่ละรายการจะได้รับการฝังเวกเตอร์ ซึ่งเป็นรายการตัวเลขที่แสดงความหมายของรายการนั้น ในรันไทม์ เครื่องมือของ Agent จะค้นหารายการที่มีความหมายใกล้เคียงกับสิ่งที่ลูกค้าขอมากที่สุด

สร้างฐานข้อมูล Firestore

เรียกใช้คำสั่งต่อไปนี้เพื่อสร้างฐานข้อมูล Firestore ชื่อ coffee-menu ในโหมดเนทีฟ

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

สร้างข้อมูลเมนู

  1. สร้างและเปิด menu.json ในเครื่องมือแก้ไข Cloud Shell โดยทำดังนี้
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 และ Gen AI ในสภาพแวดล้อมเสมือนจริง โดยทำดังนี้
pip install google-cloud-firestore==2.27.0 google-genai==2.11.0
  1. สร้างและเปิด seed.py ในเครื่องมือแก้ไข Cloud Shell โดยทำดังนี้
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 จะแสดงผลทันทีขณะที่ดัชนีสร้างขึ้นในเบื้องหลัง ซึ่งอาจใช้เวลา 2-3 นาที คุณสามารถดำเนินการในขั้นตอนถัดไปได้ ก่อนทดสอบ Agent ในขั้นตอนที่ 7 ให้เรียกใช้คำสั่งต่อไปนี้และตรวจสอบว่าดัชนี STATE เป็น READY

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

ทำไมจึงจัดเก็บเมนูใน Firestore แทนที่จะเป็น

menu.json

ภายในแอป

หากเมนูอยู่ในอิมเมจคอนเทนเนอร์ การเปลี่ยนแปลงทุกอย่าง เช่น เครื่องดื่มตามฤดูกาลใหม่หรือการอัปเดตราคา จะต้องสร้างและทำให้แอปใช้งานได้อีกครั้ง แต่เมื่อใช้ Firestore ผู้จัดการร้านกาแฟจะอัปเดตเมนูได้ทุกเมื่อ และ Agent จะเห็นการเปลี่ยนแปลงในคำขอถัดไป

นอกจากนี้ การค้นหาเวกเตอร์ยังช่วยให้พรอมต์มีขนาดเล็กด้วย แทนที่จะส่งเมนูทั้งหมดไปยัง Claude เครื่องมือ get_menu จะแสดงเฉพาะรายการ 3 รายการที่ใกล้เคียงกับคำขอของลูกค้ามากที่สุด หากเมนูเพิ่มขึ้นจาก 8 รายการเป็น 500 รายการ Claude จะยังคงได้รับเพียงไม่กี่รายการต่อการค้นหา ซึ่งจะช่วยให้ต้นทุนโทเค็นและเวลาในการตอบสนองต่ำ

5. สร้าง Agent ของ ADK

ตอนนี้คุณจะสร้าง Agent คุณกำหนดเครื่องมือ get_menu() ที่ค้นหา Firestore และส่งไปยัง LlmAgent ที่ใช้ Claude

  1. สร้างและเปิด requirements.txt ในเครื่องมือแก้ไข Cloud Shell โดยทำดังนี้
cloudshell edit requirements.txt
  1. วางทรัพยากร Dependency ต่อไปนี้ลงในเครื่องมือแก้ไข แล้วบันทึกไฟล์
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] คือ SDK ของ Anthropic ที่รองรับ Agent Platform ADK จะใช้คีย์นี้เพื่อเรียกใช้ Claude

  1. สร้างและเปิด agent.py ในเครื่องมือแก้ไข Cloud Shell โดยทำดังนี้
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. สร้างและเปิด app.py ในเครื่องมือแก้ไข Cloud Shell โดยทำดังนี้
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}")

💬 การสนทนา: Agent เรียกใช้ Claude อย่างไร

โปรดทราบว่า agent.py ไม่เคยเรียกใช้ Claude โดยตรง และไม่ได้ใช้คีย์ API ออบเจ็กต์ Claude จะบันทึกเฉพาะรูปแบบที่จะใช้เท่านั้น เมื่อ Agent ทำงาน ADK จะเรียกใช้ Claude ใน Agent Platform ผ่าน SDK ของ Anthropic และตรวจสอบสิทธิ์ด้วยข้อมูลรับรองเริ่มต้นของแอปพลิเคชัน ใน Cloud Run ข้อมูลประจำตัวดังกล่าวคือข้อมูลประจำตัวของบริการ

รายละเอียด 2 รายการที่เจาะจงสำหรับ 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 จะข้ามข้อมูลเหล่านี้เพื่อให้ลูกค้าเห็นเฉพาะคำตอบ

💬 การสนทนา: สถานะหน่วยความจำและที่เก็บข้อมูลเวอร์ชันที่ใช้งานจริง

ประวัติการแชทที่จัดเก็บไว้ใน

st.session_state

ยังคงอยู่เมื่อผู้ใช้ปิดแท็บเบราว์เซอร์หรือไม่

ไม่ ไม่ได้ st.session_state อยู่ในหน่วยความจำทั้งหมดและไม่ซ้ำกันสำหรับการเชื่อมต่อเบราว์เซอร์ที่ใช้งานอยู่ หากผู้ใช้รีเฟรชหน้าเว็บหรือปิดแท็บ ประวัติการสนทนากับบาริสต้าจะหายไป

สำหรับแอปพลิเคชันเวอร์ชันที่ใช้งานจริง คุณจะต้องเชื่อมต่อรันเนอร์ ADK กับที่เก็บเซสชันแบบถาวร ADK มีนามธรรมของบริการในตัว (เช่น SessionService) ที่ช่วยให้บันทึกและกลับมาดูประวัติการแชทต่อได้ง่ายๆ แม้จะโหลดหน้าเว็บซ้ำและใช้อุปกรณ์ต่างๆ

6. ติดตั้งใช้งาน Agent ใน Cloud Run

คุณจะติดตั้งใช้งานแอปพลิเคชัน Streamlit โดยตรงจากแหล่งที่มาโดยใช้ Buildpack ในตัวของ Cloud Run หากต้องการปฏิบัติตามหลักการให้สิทธิ์ขั้นต่ำที่สุด คุณจะต้องสร้างและทำให้ใช้งานได้โดยใช้บัญชีบริการที่กำหนดเองโดยเฉพาะ แทนที่จะใช้บัญชีบริการ 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 (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 จะใช้บทบาท IAM ของ Cloud Datastore เพื่อควบคุมการเข้าถึง 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. ค้นหา URL ของบริการในเอาต์พุตของคำสั่ง deploy

💬 การสนทนา: การติดตั้งใช้งานจากแหล่งที่มา, การรักษาความปลอดภัย IAM และ IAP

เราติดตั้งใช้งานใน Cloud Run โดยใช้

gcloud run deploy --source

โดยไม่ต้องสร้าง Dockerfile Cloud Run ทราบวิธีสร้างและเรียกใช้แอป Python ของเราได้อย่างไร

Cloud Run ใช้ Buildpack เบื้องหลังเพื่อวิเคราะห์ซอร์สโค้ด เมื่อตรวจพบ requirements.txt และไฟล์ต้นฉบับ Python ระบบจะสร้างคอนเทนเนอร์ที่มีรันไทม์ Python และทรัพยากร Dependency ของคุณ แฟล็ก --command และ --args จะบอกให้คอนเทนเนอร์เริ่ม Streamlit ในพอร์ตที่ Cloud Run มีให้

เหตุใดเราจึงสร้าง

barista-agent-sa

แทนการใช้บัญชีบริการ Compute Engine เริ่มต้น

บัญชีบริการ Compute Engine เริ่มต้นมักมีสิทธิ์ผู้แก้ไขในวงกว้าง หากแอปมีข้อบกพร่องด้านความปลอดภัย ผู้โจมตีอาจใช้สิทธิ์เหล่านั้นเพื่ออ่าน เปลี่ยนแปลง หรือลบทรัพยากรอื่นๆ ในโปรเจ็กต์ได้ บัญชีบริการเฉพาะมีเพียง 2 บทบาทที่แอปต้องการ ได้แก่ การเรียกใช้โมเดลใน Agent Platform และการอ่านจาก Firestore

ทำไมจึงต้องวางแอปไว้หลัง IAP แทนที่จะอนุญาตให้เข้าถึงโดยไม่ตรวจสอบสิทธิ์

ข้อความแชททุกข้อความจะเรียกใช้ Claude และระบบจะเรียกเก็บเงินค่าใช้งาน Claude จากโปรเจ็กต์ของคุณ เมื่อใช้ IAP ผู้ใช้ต้องลงชื่อเข้าใช้ด้วยบัญชี Google และมีเพียงผู้ที่คุณให้บทบาทผู้ใช้เว็บแอปที่รักษาความปลอดภัยด้วย IAP (roles/iap.httpsResourceAccessor) เท่านั้นที่จะใช้แอปได้

7. ทดสอบ Agent

เปิด URL ของบริการ Cloud Run ในเว็บเบราว์เซอร์ แล้วลงชื่อเข้าใช้ด้วยบัญชี Google จากนั้นถามคำถาม AI Barista เพื่อทดสอบการอ้างอิงข้อมูลและข้อจำกัดด้านความปลอดภัย

  1. คำขอในเมนู: ถาม: "แนะนำเครื่องดื่มที่เข้มและร้อนหน่อย"สิ่งที่คาดหวัง: Agent แนะนำเอสเพรสโซโซโล
  2. การทดสอบรายการที่ไม่อยู่ในเมนู: ถามว่า "มีมัทฉะแฟรปเป้ไหม" ผลลัพธ์ที่คาดหวัง: ตัวแทนปฏิเสธอย่างสุภาพและอธิบายว่าไม่มีในเมนู
  3. คำขอที่คำนึงถึงสารก่อภูมิแพ้: ถาม: "ฉันแพ้แล็กโตส ฉันจะสั่งอะไรได้บ้าง"สิ่งที่คาดหวัง: ตัวแทนจะแนะนำเฉพาะรายการที่ไม่มีผลิตภัณฑ์จากนม เช่น ลาเต้น้ำผึ้งนมข้าวโอ๊ต เอสเพรสโซโซโล หรือกาแฟสกัดเย็น แต่จะไม่แนะนำ Seasonal Pumpkin Latte, Iced Caramel Macchiato หรือ Classic Croissant

อัปเดตเมนูโดยไม่ต้องทำให้ใช้งานได้อีกครั้ง

หากต้องการยืนยันว่า Agent มีข้อมูลอ้างอิงในฐานข้อมูลแบบเรียลไทม์ ให้เพิ่มรายการเมนูใหม่ใน Firestore โดยตรง แล้วตรวจสอบว่า Agent แนะนำรายการดังกล่าว

  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. โปรดสังเกตว่าตอนนี้มัทฉะกรีนทีลาเต้ปรากฏในเมนูแถบด้านข้างแล้ว
  3. ถามแชทบ็อต: "คุณมีเครื่องดื่มมัทฉะไหม"

ตัวแทนจะแนะนำมัทฉะกรีนทีลาเต้ใหม่ พร้อมคำอธิบายและราคาที่คุณเพิ่งเพิ่ม คุณไม่ได้สร้างหรือทำให้แอปใช้งานได้อีกครั้ง ซึ่งเป็นการยืนยันว่า Agent ได้รับการสนับสนุนในฐานข้อมูล 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. ขอแสดงความยินดี

ยินดีด้วย คุณได้สร้างและติดตั้งใช้งาน Agent บาริสต้า AI ที่มีความสามารถในการดึงข้อมูลมาเสริม (Retrieval-Augmented Generation หรือ RAG) โดยใช้ Claude, ADK ของ Google, Firestore และ Cloud Run แล้ว

สิ่งที่คุณได้เรียนรู้

  • การเรียกใช้โมเดล Claude ในแพลตฟอร์ม Agent ของ Gemini Enterprise จาก ADK ด้วยคลาสโมเดล Claude
  • การอิงข้อมูลของ Agent ตามข้อมูล Firestore แบบเรียลไทม์ด้วยการค้นหาเวกเตอร์
  • การใช้ LlmAgent และ InMemoryRunner ของ ADK
  • การสร้างประสบการณ์การแชทแบบเก็บสถานะใน Streamlit
  • การทำให้ Streamlit ใช้งานได้ใน Cloud Run จากแหล่งที่มา โดยใช้บัญชีบริการที่มีสิทธิ์ขั้นต่ำที่สุดและ IAP

เอกสารอ้างอิง