1. परिचय
इस कोडलैब में, आपको कॉफ़ी शॉप के लिए इंटरैक्टिव एआई बरिस्ता एजेंट बनाने का तरीका बताया गया है. Gemini Enterprise Agent Platform पर, Anthropic के Claude Opus 5 मॉडल के साथ Google की ओपन-सोर्स एजेंट डेवलपमेंट किट (एडीके) का इस्तेमाल किया जा रहा हो. एजेंट के सुझावों को बेहतर बनाने के लिए, मेन्यू को Firestore में सेव किया जाता है. साथ ही, काम के आइटम ढूंढने के लिए वेक्टर सर्च का इस्तेमाल किया जाता है. इस तकनीक को रिट्रीवल-ऑगमेंटेड जनरेशन (आरएजी) कहा जाता है. आखिर में, एजेंट को Streamlit चैट ऐप्लिकेशन में रैप किया जाता है और Identity-Aware Proxy (IAP) के पीछे Cloud Run पर डिप्लॉय किया जाता है.
आपको क्या करना होगा
- Model Garden में Claude Opus 5 को चालू करें.
- मेन्यू को Firestore डेटाबेस में सेव करें. साथ ही, हर आइटम के लिए वेक्टर एंबेडिंग का इस्तेमाल करें.
- ADK
LlmAgentऔर Claude की मदद से एक एआई एजेंट बनाएं. साथ ही, उसे मेन्यू खोजने वाला टूल दें. - एजेंट को Streamlit चैट ऐप्लिकेशन में रैप करें, जो बातचीत के इतिहास को मैनेज करता है.
- सोर्स से Cloud Run पर ऐप्लिकेशन डिप्लॉय करें और आईएपी की मदद से इसका ऐक्सेस सीमित करें.
- आरएजी ग्राउंडिंग, एलर्जी पैदा करने वाली चीज़ों के बारे में जानकारी, और लाइव मेन्यू अपडेट की सुविधा को टेस्ट करें.
आपको किन चीज़ों की ज़रूरत होगी
- Chrome जैसा कोई वेब ब्राउज़र.
- बिलिंग की सुविधा वाला Google क्लाउड प्रोजेक्ट.
- Model Garden में Claude मॉडल चालू करने की अनुमति. इसके लिए, आपके पास उपभोक्ता प्रोक्योरमेंट एनटाइटलमेंट मैनेजर की भूमिका (
roles/consumerprocurement.entitlementManager) होनी चाहिए. - Python की बुनियादी जानकारी.
यह कोडलैब, सभी लेवल के डेवलपर के लिए है. इसमें शुरुआती लेवल के डेवलपर भी शामिल हैं.
अनुमानित लागत: कुछ डॉलर या इससे कम. ज़्यादातर शुल्क, Claude के इस्तेमाल के लिए लिया जाता है. इसका बिल, इस्तेमाल किए गए टोकन के हिसाब से भेजा जाता है. मौजूदा दरों के लिए, Agent Platform की कीमत देखें.
2. शुरू करने से पहले
Google Cloud प्रोजेक्ट बनाना
- Google Cloud console में, कोई Google Cloud प्रोजेक्ट चुनें या बनाएं.
- पक्का करें कि आपके क्लाउड प्रोजेक्ट के लिए बिलिंग की सुविधा चालू हो. किसी प्रोजेक्ट के लिए बिलिंग की सुविधा चालू होने की पुष्टि करने का तरीका जानें.
Cloud Shell शुरू करना
- Google Cloud Console में सबसे ऊपर मौजूद, Cloud Shell चालू करें पर क्लिक करें.

- पुष्टि करने की प्रक्रिया की जांच करना:

gcloud auth list
- पुष्टि करें कि आपका ऐक्टिव प्रोजेक्ट सेट है:
gcloud config get project
अगर दिखाया गया प्रोजेक्ट आईडी सही नहीं है या कोई आईडी सेट नहीं है, तो यह कमांड चलाएं:
gcloud config set project <YOUR_PROJECT_ID>
एपीआई चालू करें
सभी ज़रूरी एपीआई चालू करने के लिए, यह कमांड चलाएं:
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 मॉडल को कॉल करने से पहले, आपको उसे अपने प्रोजेक्ट में चालू करना होगा.
- Google Cloud Console में, Model Garden में जाकर Claude Opus 5 मॉडल कार्ड खोलें.
- चालू करें पर क्लिक करें. इसके बाद, Anthropic की शर्तें स्वीकार करने के लिए, स्क्रीन पर दिए गए निर्देशों का पालन करें.
अगले चरण में, आपको यह पुष्टि करनी होगी कि मॉडल को कॉल किया जा सकता है.
3. अपना प्रोजेक्ट सेट अप करना
इस चरण में, एनवायरमेंट वैरिएबल को शुरू किया जाता है. साथ ही, Python वर्चुअल एनवायरमेंट के साथ एक वर्किंग डायरेक्ट्री बनाई जाती है. इसके बाद, यह पुष्टि की जाती है कि Claude को कॉल किया जा सकता है.
- अपने चालू 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]
coffee-barista-agentनाम की नई प्रोजेक्ट डायरेक्ट्री बनाएं और उसमें जाएं:
mkdir coffee-barista-agent && cd coffee-barista-agent
- Python वर्चुअल एनवायरमेंट बनाएं और उसे चालू करें. Cloud Shell में स्क्रिप्ट चलाने के लिए, इसका इस्तेमाल किया जाएगा:
python3 -m venv .venv
source .venv/bin/activate
- Cloud Shell Editor में
.gcloudignoreबनाएं और खोलें. यह फ़ाइल, डिप्लॉय करते समय वर्चुअल एनवायरमेंट को अपलोड होने से रोकती है:
cloudshell edit .gcloudignore
- एडिटर में यह कॉन्टेंट चिपकाएं और फ़ाइल सेव करें:
# 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 सूची, text ब्लॉक पर खत्म होती है. इसमें Claude का जवाब शामिल होता है. साथ ही, यह thinking ब्लॉक से शुरू हो सकती है. अगर आपको 404 गड़बड़ी का मैसेज मिलता है, तो देखें कि आपने Model Garden में मॉडल को चालू किया है या नहीं.
4. Firestore में मेन्यू डेटाबेस बनाना
एआई बरिस्ता को ग्राउंड करने और उसे ऐसे आइटम का सुझाव देने से रोकने के लिए जो मौजूद नहीं हैं, मेन्यू को Firestore में सेव करें. हर मेन्यू आइटम को एक वेक्टर एंबेडिंग मिलती है: संख्याओं की एक सूची, जो आइटम के मतलब को कैप्चर करती है. रनटाइम के दौरान, एजेंट का टूल उन आइटम को खोजता है जो ग्राहक की क्वेरी से सबसे ज़्यादा मिलते-जुलते हैं.
Firestore डेटाबेस बनाना
नेटिव मोड में coffee-menu नाम का Firestore डेटाबेस बनाने के लिए, यह कमांड चलाएं:
gcloud firestore databases create --database=coffee-menu --location=$REGION
मेन्यू का डेटा बनाना
- Cloud Shell Editor में
menu.jsonबनाएं और खोलें:
cloudshell edit menu.json
- एडिटर में यह 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"]
}
]
- पुष्टि करें कि JSON फ़ाइल सही तरीके से फ़ॉर्मैट की गई हो:
cat menu.json | python3 -m json.tool > /dev/null && echo "Valid JSON!"
मेन्यू के डेटा के साथ Firestore को सीड करना
सीडिंग स्क्रिप्ट, menu.json को पढ़ती है. इसके बाद, text-embedding-005 मॉडल का इस्तेमाल करके हर आइटम के लिए एक एंबेडिंग बनाती है और हर आइटम को menu कलेक्शन में सेव करती है.
- अपने वर्चुअल एनवायरमेंट में, Firestore और जेन एआई की क्लाइंट लाइब्रेरी इंस्टॉल करें:
pip install google-cloud-firestore==2.27.0 google-genai==2.11.0
- Cloud Shell Editor में
seed.pyबनाएं और खोलें:
cloudshell edit seed.py
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!")
- स्क्रिप्ट चलाएं:
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 फ़्लैग तुरंत नतीजे दिखाता है, जबकि इंडेक्स बैकग्राउंड में बनता है. इसमें कुछ मिनट लग सकते हैं. अगले चरण पर जाएं. सातवें चरण में एजेंट की जांच करने से पहले, यहां दिया गया कमांड चलाएं और देखें कि इंडेक्स 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 को पास किया है.
- Cloud Shell Editor में
requirements.txtबनाएं और खोलें:
cloudshell edit requirements.txt
- एडिटर में ये डिपेंडेंसी चिपकाएं और फ़ाइल सेव करें:
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], Anthropic का SDK टूल है. यह Agent Platform के साथ काम करता है. ADK इसका इस्तेमाल Claude को कॉल करने के लिए करता है.
- Cloud Shell Editor में
agent.pyबनाएं और खोलें:
cloudshell edit agent.py
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
)
- Cloud Shell Editor में
app.pyबनाएं और खोलें:
cloudshell edit app.py
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 को कभी भी सीधे तौर पर कॉल नहीं करता है. साथ ही, यह एपीआई पासकोड का इस्तेमाल नहीं करता है. Claude ऑब्जेक्ट सिर्फ़ यह रिकॉर्ड करता है कि किस मॉडल का इस्तेमाल करना है. जब एजेंट चलता है, तो ADK, Anthropic के SDK टूल के ज़रिए Agent Platform पर Claude को कॉल करता है. साथ ही, ऐप्लिकेशन के डिफ़ॉल्ट क्रेडेंशियल की मदद से पुष्टि करता है. Cloud Run पर, यह सेवा की पहचान होती है.
Claude के लिए दो खास बातें हैं:
- मॉडल के नाम के बजाय,
Claudeका इंस्टेंस पास करें. एडीके सिर्फ़claude-3-*औरclaude-*-4*मॉडल के नामों को पहचानता है.model="claude-opus-5"सेट करने पर, एजेंटModel claude-opus-5 not foundके साथ काम नहीं करता. - सोचने की प्रोसेस के हिस्सों को स्किप करना. Claude Opus 5, जवाब देने से पहले अपने तर्क को थिंकिंग ब्लॉक के तौर पर दिखा सकता है. एडीके, इन्हें ऐप्लिकेशन को हिस्सों के तौर पर पास करता है. इसमें
part.thoughtकोTrueपर सेट किया जाता है. साथ ही,app.pyइन्हें स्किप कर देता है, ताकि ग्राहकों को सिर्फ़ जवाब दिखे.
💬 बातचीत: मेमोरी स्टेट और प्रोडक्शन स्टोर
क्या Streamlit के
st.session_state
क्या उपयोगकर्ता के ब्राउज़र टैब बंद करने पर भी, कुकी बनी रहती है?
नहीं, ऐसा नहीं है. st.session_state पूरी तरह से इन-मेमोरी है और चालू ब्राउज़र कनेक्शन के लिए यूनीक है. अगर कोई उपयोगकर्ता पेज को रीफ़्रेश करता है या टैब बंद करता है, तो बरिस्ता के साथ हुई बातचीत का इतिहास मिट जाता है.
प्रोडक्शन ऐप्लिकेशन के लिए, ADK रनर को पर्सिस्टेंट सेशन स्टोर से कनेक्ट करना होगा. एडीके में पहले से मौजूद सर्विस एब्स्ट्रैक्शन (जैसे, SessionService) होते हैं. इनकी मदद से, पेज को फिर से लोड करने और अलग-अलग डिवाइसों पर चैट का इतिहास सेव करने और उसे फिर से शुरू करने में आसानी होती है.
6. एजेंट को Cloud Run पर डिप्लॉय करना
Cloud Run के पहले से मौजूद बिल्डपैक का इस्तेमाल करके, Streamlit ऐप्लिकेशन को सीधे सोर्स से डिप्लॉय किया जाएगा. कम से कम अधिकारों के सिद्धांत का पालन करने के लिए, Compute Engine के डिफ़ॉल्ट सेवा खाते का इस्तेमाल करने के बजाय, कस्टम सेवा खाते का इस्तेमाल करके फ़ंक्शन बनाए और डिप्लॉय किए जाएंगे.
- एक खास सेवा खाता बनाएं:
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"
- नए सेवा खाते को एजेंट प्लैटफ़ॉर्म के उपयोगकर्ता की भूमिका (
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"
- सेवा खाते को 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, Firestore के ऐक्सेस को कंट्रोल करने के लिए, Cloud Datastore के आईएएम रोल का इस्तेमाल करता है.
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
- 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"
- 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"
- डिप्लॉय कमांड के आउटपुट में, सेवा का यूआरएल ढूंढें.
💬 चर्चा: सोर्स, आईएएम सिक्योरिटी, और आईएपी से डिप्लॉय करना
हमने का इस्तेमाल करके, Cloud Run पर डिप्लॉय किया
gcloud run deploy --source
Dockerfile बनाए बिना. 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 के इस्तेमाल का शुल्क, आपके प्रोजेक्ट के लिए लिया जाता है. आईएपी की मदद से, उपयोगकर्ताओं को अपने Google खाते से साइन इन करना होगा. साथ ही, सिर्फ़ वे लोग ऐप्लिकेशन का इस्तेमाल कर सकते हैं जिन्हें आपने आईएपी से सुरक्षित वेब ऐप्लिकेशन के उपयोगकर्ता की भूमिका (roles/iap.httpsResourceAccessor) दी है.
7. एजेंट को टेस्ट करना
किसी वेब ब्राउज़र में Cloud Run सेवा का यूआरएल खोलें और अपने Google खाते से साइन इन करें. इसके बाद, एआई बरिस्ता से सवाल पूछें, ताकि यह जांचा जा सके कि वह ग्राउंडिंग और सुरक्षा से जुड़ी पाबंदियों का पालन कर रहा है या नहीं.
- मेन्यू में मौजूद आइटम के बारे में अनुरोध: कहें: "मुझे कोई स्ट्रॉन्ग और गर्म ड्रिंक बताओ."उम्मीद के मुताबिक जवाब: एजेंट, Espresso Solo का सुझाव देता है.
- मेन्यू से बाहर के आइटम के बारे में पूछना: यह पूछें: "क्या आपके पास माचा फ़्रैपुचीनो है?"उम्मीद के मुताबिक जवाब: एजेंट विनम्रता से मना करे और बताए कि यह मेन्यू में नहीं है.
- एलर्जी पैदा करने वाली चीज़ों के बारे में जानकारी देने का अनुरोध: पूछें: "मुझे लैक्टोज़ से एलर्जी है, मुझे क्या मिल सकता है?"उम्मीद के मुताबिक जवाब: एजेंट सिर्फ़ डेयरी-फ़्री आइटम का सुझाव देता है. जैसे, ओट मिल्क हनी लाटे, एस्प्रेसो सोलो या कोल्ड ब्रू कॉफ़ी. यह सीज़नल पम्पकिन लाटे, आइस कैरमल मैकियाटो या क्लासिक क्रोइसैंट का सुझाव नहीं देता.
मेन्यू को फिर से डिप्लॉय किए बिना अपडेट करना
यह पुष्टि करने के लिए कि एजेंट, लाइव डेटाबेस में मौजूद डेटा के आधार पर जवाब दे रहा है, सीधे Firestore में एक नया मेन्यू आइटम जोड़ें. इसके बाद, देखें कि एजेंट उसका सुझाव देता है या नहीं.
- 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!')
"
- चैट सेशन को मिटाने और डेटाबेस की नई स्थिति को लोड करने के लिए, अपने ब्राउज़र में ऐप्लिकेशन को रीफ़्रेश करें.
- ध्यान दें कि माचा ग्रीन टी लाटे अब साइडबार मेन्यू में दिख रहा है.
- चैटबॉट से पूछें: "क्या आपके पास माचा ड्रिंक हैं?"
एजेंट, नई माचा ग्रीन टी लाटे का सुझाव देता है. साथ ही, वह ब्यौरा और कीमत भी बताता है जो आपने अभी-अभी जोड़ी है. आपने ऐप्लिकेशन को फिर से नहीं बनाया या डिप्लॉय नहीं किया. इससे यह पुष्टि होती है कि एजेंट आपके लाइव 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 का इस्तेमाल करके, Retrieval-Augmented Generation (RAG) एआई बरिस्ता एजेंट बना लिया है और उसे डिप्लॉय कर दिया है.
आपने क्या सीखा
Claudeमॉडल क्लास का इस्तेमाल करके, ADK से Gemini Enterprise Agent Platform पर Claude मॉडल को कॉल करना.- वेक्टर सर्च की मदद से, एजेंट को Firestore के लाइव डेटा से ग्राउंड करना.
- एडीके
LlmAgentऔरInMemoryRunnerका इस्तेमाल करना. - Streamlit में स्टेटफ़ुल चैट अनुभव बनाना.
- सोर्स से Cloud Run पर Streamlit को डिप्लॉय करना. इसके लिए, कम से कम अनुमतियों वाले सेवा खाते और आईएपी का इस्तेमाल करना.