Google ADK, Firestore, Cloud Run을 사용하여 Streamlit에서 Claude로 RAG AI 에이전트 배포하기

1. 소개

이 Codelab에서는 커피숍을 위한 대화형 AI 바리스타 에이전트를 빌드합니다. Gemini Enterprise Agent Platform에서 Anthropic의 Claude Opus 5 모델과 함께 Google의 오픈소스 에이전트 개발 키트 (ADK)를 사용합니다. 에이전트의 추천을 그라운딩하기 위해 메뉴를 Firestore에 저장하고 벡터 검색을 사용하여 관련 항목을 찾습니다. 이 기법을 검색 증강 생성 (RAG)이라고 합니다. 마지막으로 에이전트를 Streamlit 채팅 앱으로 래핑하고 IAP (Identity-Aware Proxy) 뒤의 Cloud Run에 배포합니다.

실습할 내용

  • Model Garden에서 Claude Opus 5를 사용 설정합니다.
  • 각 항목의 벡터 임베딩과 함께 Firestore 데이터베이스에 메뉴를 저장합니다.
  • ADK LlmAgent 및 Claude를 사용하여 AI 에이전트를 빌드하고 메뉴를 검색하는 도구를 제공합니다.
  • 대화 기록을 관리하는 Streamlit 채팅 애플리케이션에 에이전트를 래핑합니다.
  • 소스에서 Cloud Run에 앱을 배포하고 IAP를 사용하여 앱에 대한 액세스를 제한합니다.
  • RAG 그라운딩, 알레르기 유발 물질 인식, 실시간 메뉴 업데이트를 테스트합니다.

필요한 항목

  • 웹브라우저(예: Chrome)
  • 결제가 사용 설정된 Google Cloud 프로젝트.
  • Model Garden에서 Claude 모델을 사용 설정할 수 있는 권한입니다. 이를 위해서는 소비자 조달 사용 권한 관리자 역할 (roles/consumerprocurement.entitlementManager)이 필요합니다.
  • Python에 대한 기본 지식

이 Codelab은 초보자를 포함한 모든 수준의 개발자를 대상으로 합니다.

예상 비용: 몇 달러(USD) 이하 비용의 대부분은 토큰당 청구되는 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 바리스타를 그라운딩하고 존재하지 않는 항목을 추천하지 않도록 하려면 메뉴를 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를 사용하면 커피숍 관리자가 언제든지 메뉴를 업데이트할 수 있으며 에이전트는 다음 요청에서 변경사항을 확인할 수 있습니다.

벡터 검색은 프롬프트를 작게 유지합니다. 전체 메뉴를 Claude에 전송하는 대신 get_menu 도구는 고객의 요청과 가장 가까운 세 가지 항목만 반환합니다. 메뉴가 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와 관련된 두 가지 세부정보는 다음과 같습니다.

  • 모델 이름이 아닌 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의 기본 제공 빌드팩을 사용하여 소스에서 직접 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 플래그는 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을 찾습니다.

💬 토론: 소스에서 배포, IAM 보안, IAP

Cloud Run에 배포할 때

gcloud run deploy --source

를 빌드할 수 있습니다. Cloud Run은 어떻게 Python 앱을 빌드하고 실행하는 방법을 알아냈을까요?

Cloud Run은 백그라운드에서 빌드팩을 사용하여 소스 코드를 분석합니다. requirements.txt 및 Python 소스 파일을 감지하면 Python 런타임 및 종속 항목이 있는 컨테이너를 빌드합니다. --command 및 --args 플래그는 Cloud Run에서 제공하는 포트에서 Streamlit을 시작하도록 컨테이너에 지시합니다.

을 만든 이유

barista-agent-sa

기본 Compute Engine 서비스 계정 대신 서비스 계정을 사용하는 것이 좋습니다.

기본 Compute Engine 서비스 계정에는 광범위한 편집자 권한이 있는 경우가 많습니다. 앱에 보안 버그가 있는 경우 공격자는 이러한 권한을 사용하여 프로젝트의 다른 리소스를 읽거나 변경하거나 삭제할 수 있습니다. 전용 서비스 계정에는 앱에 필요한 두 가지 역할, 즉 Agent Platform에서 모델을 호출하는 역할과 Firestore에서 읽는 역할만 있습니다.

인증되지 않은 액세스를 허용하는 대신 IAP 뒤에 앱을 배치하는 이유는 무엇인가요?

모든 채팅 메시지는 Claude를 호출하며 Claude 사용량은 프로젝트에 청구됩니다. IAP를 사용하면 사용자는 Google 계정으로 로그인해야 하며, IAP 보안 웹 앱 사용자 역할 (roles/iap.httpsResourceAccessor)을 부여한 사용자만 앱을 사용할 수 있습니다.

7. 에이전트 테스트

웹브라우저에서 Cloud Run 서비스 URL을 열고 Google 계정으로 로그인합니다. 그런 다음 AI 바리스타에게 질문하여 그라운딩 및 안전 제약 조건을 테스트합니다.

  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. 챗봇에게 "말차 음료가 있나요?"라고 질문합니다.

에이전트가 방금 추가한 설명과 가격으로 새로운 말차 그린티 라떼를 추천합니다. 앱을 다시 빌드하거나 재배포하지 않았으므로 에이전트가 라이브 Firestore 데이터베이스에 그라운딩되어 있음을 확인할 수 있습니다.

8. 삭제

Google Cloud Billing 계정에 요금이 계속 청구되지 않도록 하려면 만든 리소스를 삭제하세요.

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에서 스테이트풀(Stateful) 채팅 환경 만들기
  • 최소 권한 서비스 계정 및 IAP를 사용하여 소스에서 Cloud Run에 Streamlit을 배포합니다.

참조 문서