วิธีติดตั้งใช้งานแอปฟรอนท์เอนด์ Gradio ที่เรียกใช้ตัวแทน ADK แบ็กเอนด์ ซึ่งทั้ง 2 อย่างทำงานบน Cloud Run

1. บทนำ

ภาพรวม

ใน Codelab นี้ คุณจะทำให้ Agent ของ ADK ใช้งานได้ใน Cloud Run เป็นบริการแบ็กเอนด์ จากนั้นจึงทำให้ส่วนหน้าของ Gradio สำหรับ Agent ของ ADK ใช้งานได้เป็นบริการ Cloud Run ที่ 2 Codelab นี้แสดงวิธีกำหนดให้มีการตรวจสอบสิทธิ์ในบริการ Agent ของ ADK และทำการเรียกที่ผ่านการตรวจสอบสิทธิ์ไปยังบริการดังกล่าวจากบริการส่วนหน้าของ Gradio

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

  • วิธีติดตั้งใช้งานเอเจนต์ ADK ใน Cloud Run
  • วิธีติดตั้งใช้งานแอป Gradio ใน Cloud Run
  • วิธีโทรจากบริการหนึ่งไปยังอีกบริการหนึ่งที่ตรวจสอบสิทธิ์แล้วใน Cloud Run

2. เปิดใช้ API

ก่อนอื่น ให้ตั้งค่าโปรเจ็กต์ Google Cloud

gcloud config set project <YOUR_PROJECT_ID>

คุณยืนยันโปรเจ็กต์ Google Cloud ได้โดยเรียกใช้คำสั่งต่อไปนี้

gcloud config get-value project

Codelab นี้กำหนดให้เปิดใช้ API ต่อไปนี้

gcloud services enable run.googleapis.com \
    compute.googleapis.com \
    run.googleapis.com \
    cloudbuild.googleapis.com \
    artifactregistry.googleapis.com \
    aiplatform.googleapis.com

3. การตั้งค่าและข้อกำหนด

ในส่วนนี้ คุณจะสร้างบัญชีบริการ 2 บัญชีและมอบบทบาท IAM ที่เหมาะสมให้ บริการ Cloud Run แต่ละบริการจะมีบัญชีบริการของตัวเอง

ก่อนอื่น ให้ตั้งค่าตัวแปรสภาพแวดล้อมสำหรับ Codelab นี้ ซึ่งจะใช้ตลอดทั้ง Codelab

export PROJECT_ID=<YOUR_PROJECT_ID>
export REGION=<YOUR_REGION>

export SERVICE_ACCOUNT_ADK="adk-agent-cr"
export SERVICE_ACCOUNT_ADDRESS_ADK=$SERVICE_ACCOUNT_ADK@$PROJECT_ID.iam.gserviceaccount.com

export SERVICE_ACCOUNT_GRADIO="adk-agent-gradio"
export SERVICE_ACCOUNT_ADDRESS_GRADIO=$SERVICE_ACCOUNT_GRADIO@$PROJECT_ID.iam.gserviceaccount.com

export AGENT_APP_NAME="multi_tool_agent"

จากนั้นสร้างบัญชีบริการสำหรับตัวแทน ADK

gcloud iam service-accounts create $SERVICE_ACCOUNT_ADK \
--display-name="Service account for adk agent on cloud run"

และให้บทบาท "ผู้ใช้ Vertex AI" แก่บัญชีบริการ ADK

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$SERVICE_ACCOUNT_ADDRESS_ADK" \
  --role="roles/aiplatform.user"

ตอนนี้ให้สร้างบัญชีบริการสำหรับส่วนหน้าของ Gradio

gcloud iam service-accounts create $SERVICE_ACCOUNT_GRADIO \
  --display-name="Service account for gradio frontend cloud run"

และมอบบทบาทผู้เรียกใช้ Cloud Run ให้กับส่วนหน้าของ Gradio ซึ่งจะช่วยให้เรียกใช้ Agent ประเภท ADK ที่โฮสต์ใน Cloud Run ได้

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$SERVICE_ACCOUNT_ADDRESS_GRADIO" \
  --role="roles/run.invoker"

4. สร้างแอป ADK

ในขั้นตอนถัดไป คุณจะสร้างโค้ดสำหรับแอปพลิเคชันเริ่มต้นอย่างรวดเร็วของ ADK

หมายเหตุ: เมื่อสิ้นสุดแล็บ โครงสร้างไฟล์ควรมีลักษณะดังนี้

- codelab-gradio-adk  <-- you'll deploy the ADK agent from here
  - gradio-frontend  <-- you'll deploy the gradio app from here
    - app.py
    - requirements.txt
  - multi_tool_agent
    - __init__.py
    - agent.py
    - requirements.txt

ก่อนอื่น ให้สร้างไดเรกทอรีสำหรับ Codelab โดยรวม

mkdir codelab-gradio-adk
cd codelab-gradio-adk

ตอนนี้ให้สร้างไดเรกทอรีสำหรับบริการตัวแทน ADK

mkdir multi_tool_agent && cd multi_tool_agent

สร้างไฟล์ __init__.py ที่มีเนื้อหาต่อไปนี้

from . import agent

วิธีสร้างไฟล์ requirements.txt

google-adk

สร้างไฟล์ชื่อ agent.py

import datetime
from zoneinfo import ZoneInfo
from google.adk.agents import Agent

def get_weather(city: str) -> dict:
    """Retrieves the current weather report for a specified city.

    Args:
        city (str): The name of the city for which to retrieve the weather report.

    Returns:
        dict: status and result or error msg.
    """
    if city.lower() == "new york":
        return {
            "status": "success",
            "report": (
                "The weather in New York is sunny with a temperature of 25 degrees"
                " Celsius (77 degrees Fahrenheit)."
            ),
        }
    else:
        return {
            "status": "error",
            "error_message": f"Weather information for '{city}' is not available.",
        }


def get_current_time(city: str) -> dict:
    """Returns the current time in a specified city.

    Args:
        city (str): The name of the city for which to retrieve the current time.

    Returns:
        dict: status and result or error msg.
    """

    if city.lower() == "new york":
        tz_identifier = "America/New_York"
    else:
        return {
            "status": "error",
            "error_message": (
                f"Sorry, I don't have timezone information for {city}."
            ),
        }

    tz = ZoneInfo(tz_identifier)
    now = datetime.datetime.now(tz)
    report = (
        f'The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}'
    )
    return {"status": "success", "report": report}


root_agent = Agent(
    name="weather_time_agent",
    model="gemini-2.5-flash",
    description=(
        "Agent to answer questions about the time and weather in a city."
    ),
    instruction=(
        "You are a helpful agent who can answer user questions about the time and weather in a city."
    ),
    tools=[get_weather, get_current_time],
)

5. ทําให้ Agent ประเภท ADK ใช้งานได้

ในส่วนนี้ คุณจะทำให้ Agent ประเภท ADK ใช้งานได้ใน Cloud Run จากนั้นคุณจะยืนยันว่าการติดตั้งใช้งานทำงานได้โดยใช้ UI เว็บสำหรับนักพัฒนาซอฟต์แวร์ที่ ADK จัดเตรียมไว้ สุดท้าย คุณจะต้องมีการเรียกใช้ที่ได้รับการตรวจสอบสิทธิ์ไปยังบริการนี้

ไปยังโฟลเดอร์หลัก

หมายเหตุ: โค้ดตัวแทน ADK ต้องมีโฟลเดอร์ multi_tool_agent เป็นโฟลเดอร์รูท

cd ..

ก่อนอื่น ให้สร้างบริการ Cloud Run โดยทำดังนี้

หมายเหตุ: --with_ui ไม่บังคับสำหรับการทดสอบด้วย UI สำหรับนักพัฒนาแอป ดังที่แสดงในขั้นตอนถัดไป

หมายเหตุ: คำสั่ง -- ช่วยให้คุณส่งสถานะบรรทัดคำสั่งไปยังคำสั่ง gcloud run deploy ที่อยู่เบื้องหลังได้

หมายเหตุ: uvx --from จะเรียกใช้คำสั่งจากแพ็กเกจ google-adk โดย uvx จะสร้างสภาพแวดล้อมเสมือนชั่วคราว ติดตั้ง google-adk ลงในสภาพแวดล้อมนั้น เรียกใช้คำสั่งที่ระบุ แล้วจึงปิดสภาพแวดล้อม

uvx --from google-adk \
adk deploy cloud_run \
    --project=$PROJECT_ID \
    --region=$REGION \
    --service_name=adk-agent-cr \
    --with_ui \
    ./multi_tool_agent \
    -- \
    --service-account=$SERVICE_ACCOUNT_ADDRESS_ADK \
    --allow-unauthenticated

จากนั้นบันทึก URL เป็นตัวแปรสภาพแวดล้อมที่คุณจะใช้ในส่วนที่ 2 ของ Codelab นี้

AGENT_SERVICE_URL=$(gcloud run services describe adk-agent-cr --region $REGION --format 'value(status.url)')

ตอนนี้ลองใช้เอเจนต์

เปิด URL ของบริการในเว็บเบราว์เซอร์แล้วถามว่า tell me about the weather in new york คุณควรเห็นคำตอบที่คล้ายกับ "อากาศในนิวยอร์กมีแดดจัดและอุณหภูมิ 25 องศาเซลเซียส (77 องศาฟาเรนไฮต์)"

สุดท้ายคือรักษาความปลอดภัยของเอเจนต์

ตอนนี้เรามาทำให้การเข้าถึง Agent ปลอดภัยกัน ในส่วนถัดไป คุณจะทำให้บริการ Cloud Run ใช้งานได้ ซึ่งจะทำการเรียกที่ผ่านการตรวจสอบสิทธิ์ไปยังบริการแบ็กเอนด์นี้

gcloud run services remove-iam-policy-binding adk-agent-cr \
  --member="allUsers" \
  --role="roles/run.invoker" \
  --region=$REGION

6. ติดตั้งใช้งานส่วนหน้าของ Gradio

ในขั้นตอนนี้ คุณจะได้สร้างส่วนหน้าของ Gradio สำหรับเอเจนต์ ADK

หมายเหตุ: คุณสามารถมีแอป Gradio ในบริการเดียวกันกับตัวแทน ADK ได้ Codelab นี้มีบริการ 2 รายการแยกกันเพื่อแสดงวิธีทำการเรียกบริการไปยังบริการที่ได้รับการตรวจสอบสิทธิ์ใน Cloud Run

ก่อนอื่น ให้สร้างแอปข้างโฟลเดอร์ multi_tool_agent

mkdir gradio-frontend && cd gradio-frontend

จากนั้นสร้างไฟล์ requirements.txt ที่มีข้อมูลต่อไปนี้

gradio
requests
google-auth

ตอนนี้ให้สร้างไฟล์ app.py

import gradio as gr
import requests
import json
import uuid
import os
import google.auth.transport.requests
import google.oauth2.id_token

# https://weather-time-service2-392295011265.us-west4.run.app
BASE_URL = os.environ.get("AGENT_SERVICE_URL")

# multi_tool_agent
APP_NAME = os.environ.get("AGENT_APP_NAME")

# Generate a unique user ID for each session of the Gradio app
USER_ID = f"gradio-user-{uuid.uuid4()}"

# API Endpoints
CREATE_SESSION_URL = f"{BASE_URL}/apps/{APP_NAME}/users/{USER_ID}/sessions"
RUN_SSE_URL = f"{BASE_URL}/run_sse"

def get_id_token():
    """Get an ID token to authenticate with the other Cloud Run service."""
    audience = BASE_URL
    request = google.auth.transport.requests.Request()
    id_token = google.oauth2.id_token.fetch_id_token(request, audience)
    return id_token

def create_session() -> str | None:
    """Creates a new session and returns the session ID."""
    try:
        id_token = get_id_token()
        headers = {"Authorization": f"Bearer {id_token}"}
        response = requests.post(CREATE_SESSION_URL, headers=headers)
        response.raise_for_status()
        return response.json().get("id")
    except Exception as e:
        print(f"Error creating session: {e}")
        return None

def query_agent(prompt: str):
    """Sends a prompt to the agent and returns the streamed response."""
    session_id = create_session()
    if not session_id:
        return "Error: Could not create a session."

    id_token = get_id_token()
    headers = {
        "Content-Type": "application/json",
        "Accept": "text/event-stream",
        "Authorization": f"Bearer {id_token}",
    }
    payload = {
        "app_name": APP_NAME,
        "user_id": USER_ID,
        "session_id": session_id,
        "new_message": {"role": "user", "parts": [{"text": prompt}]},
        "streaming": True
    }

    full_response = ""
    try:
        with requests.post(RUN_SSE_URL, headers=headers, json=payload, stream=True) as response:
            response.raise_for_status()
            for chunk in response.iter_lines():
                if chunk and chunk.decode('utf-8').startswith('data:'):
                    json_data = chunk.decode('utf-8')[len('data:'):].strip()
                    try:
                        data = json.loads(json_data)
                        text = data.get("content", {}).get("parts", [{}])[0].get("text", "")
                        if text:
                            full_response = text
                    except json.JSONDecodeError:
                        pass # Ignore chunks that are not valid JSON
        return full_response
    except requests.exceptions.RequestException as e:
        return f"An error occurred: {e}"

iface = gr.Interface(
    fn=query_agent,
    inputs=gr.Textbox(lines=2, placeholder="e.g., What's the weather in new york?"),
    outputs="text",
    title="Weather and Time Agent",
    description="Ask a question about the weather or time in a specific location.",
)

if __name__ == "__main__":
    iface.launch()

7. ทําให้แอป Gradio ใช้งานได้และทดสอบ

ในขั้นตอนนี้ คุณจะติดตั้งใช้งานแอป Gradio ส่วนหน้าใน Cloud Run

ตรวจสอบว่าคุณอยู่ในไดเรกทอรีแอป Gradio

pwd

คุณควรเห็น codelab-gradio-adk/gradio-frontend

ตอนนี้ให้ทำให้แอป Gradio ใช้งานได้

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

gcloud run deploy my-adk-gradio-frontend \
--source . \
--region $REGION \
--allow-unauthenticated \
--set-env-vars AGENT_SERVICE_URL=$AGENT_SERVICE_URL,AGENT_APP_NAME=$AGENT_APP_NAME \
--service-account=$SERVICE_ACCOUNT_ADDRESS_GRADIO

เมื่อติดตั้งใช้งานแล้ว ให้ถาม what's the weather in new york? แล้วคุณจะได้รับคำตอบที่คล้ายกับ The weather in New York is sunny with a temperature of 25 degrees Celsius (77 degrees Fahrenheit).

8. ยินดีด้วย

ขอแสดงความยินดีที่ทำ Codelab นี้เสร็จสมบูรณ์

เราขอแนะนำให้อ่านเอกสารเกี่ยวกับโฮสติ้งแอปและเอเจนต์ AI

สิ่งที่เราได้พูดถึงไปแล้ว

  • วิธีติดตั้งใช้งานเอเจนต์ ADK ใน Cloud Run
  • วิธีติดตั้งใช้งานแอป Gradio ใน Cloud Run
  • วิธีโทรจากบริการหนึ่งไปยังอีกบริการหนึ่งที่ตรวจสอบสิทธิ์แล้วใน Cloud Run

9. ล้างข้อมูล

หากต้องการหลีกเลี่ยงการเรียกเก็บเงินโดยไม่ตั้งใจ เช่น หากมีการเรียกใช้บริการ Cloud Run โดยไม่ตั้งใจมากกว่าการจัดสรรการเรียกใช้ Cloud Run รายเดือนในระดับฟรี คุณสามารถลบบริการ Cloud Run ที่สร้างไว้ในขั้นตอนที่ 6 ได้

หากต้องการลบบริการ Cloud Run ให้ไปที่ Cloud Console ของ Cloud Run ที่ https://console.cloud.google.com/run แล้วลบบริการ my-adk-gradio-frontend และ adk-agent-cr

หากต้องการลบทั้งโปรเจ็กต์ ให้ไปที่จัดการทรัพยากร เลือกโปรเจ็กต์ที่คุณสร้างในขั้นตอนที่ 2 แล้วเลือก "ลบ" หากลบโปรเจ็กต์ คุณจะต้องเปลี่ยนโปรเจ็กต์ใน Cloud SDK คุณดูรายการโปรเจ็กต์ทั้งหมดที่พร้อมใช้งานได้โดยเรียกใช้ gcloud projects list