ทําให้ Agent ที่มีคอนเทนเนอร์ใช้งานได้ใน Agent Runtime

1. ภาพรวม

Agent Runtime (เดิมคือ Agent Engine) มีสภาพแวดล้อมรันไทม์ที่มีการจัดการซึ่งออกแบบมาเพื่อการติดตั้งใช้งาน การเรียกใช้ และการปรับขนาด AI Agent อย่างมีประสิทธิภาพ โดยค่าเริ่มต้น แพลตฟอร์มจะรวมซอร์สโค้ดและการอ้างอิงโดยอัตโนมัติในระหว่างกระบวนการติดตั้งใช้งาน

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

Codelab นี้อธิบายกระบวนการตั้งแต่ต้นจนจบในการสร้างคอนเทนเนอร์ของเอเจนต์ที่สร้างด้วย Google Agent Development Kit (ADK), การกำหนดค่าสิทธิ์ที่จำเป็นของ Google Cloud และการติดตั้งใช้งานใน Agent Runtime โดยใช้ Python SDK หรือ Terraform

Codelab นี้จะแนะนำคุณเกี่ยวกับสิ่งต่อไปนี้

  1. การสร้าง Agent Python โดยใช้ Google Agent Development Kit (ADK)
  2. การห่อหุ้ม Agent ในแอปพลิเคชัน FastAPI
  3. การทำคอนเทนเนอร์แอปพลิเคชันด้วย Docker
  4. การกำหนดค่าสิทธิ์ของ Google Cloud
  5. การทําให้ Agent ที่มีคอนเทนเนอร์ใช้งานได้และทดสอบใน Agent Runtime

ขั้นตอนการสร้างและการติดตั้งใช้งาน

แผนภาพต่อไปนี้แสดงเวิร์กโฟลว์ของขั้นตอนการสร้างและการติดตั้งใช้งานที่คุณจะดำเนินการด้วยตนเองในโค้ดแล็บนี้

แผนภาพโฟลว์ CI/CD

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

  • โปรเจ็กต์ Google Cloud ที่เปิดใช้การเรียกเก็บเงิน
  • สิทธิ์เข้าถึง Cloud Shell (แนะนำ) หรือสภาพแวดล้อมการพัฒนาในเครื่องที่ติดตั้ง gcloud และ docker
  • มีความรู้พื้นฐานเกี่ยวกับ Python และ Docker

2. การตั้งค่าสภาพแวดล้อม

ก่อนเริ่มต้น คุณต้องเปิดใช้ API ที่จำเป็นและกำหนดค่าสภาพแวดล้อม

ขั้นตอนที่ 1: เปิด Cloud Shell

คลิกปุ่มเปิดใช้งาน Cloud Shell ที่ด้านขวาบนของ Google Cloud Console

Cloud Shell

ขั้นตอนที่ 2: กำหนดค่าตัวแปรสภาพแวดล้อม

ใน Cloud Shell ให้ตั้งค่ารหัสโปรเจ็กต์และกำหนดตัวแปรสภาพแวดล้อมหลักที่ใช้ตลอด Codelab นี้ แทนที่ "YOUR_PROJECT_ID" ด้วยรหัสโปรเจ็กต์ Google Cloud จริงของคุณ

gcloud config set project "YOUR_PROJECT_ID"
export PROJECT_ID=$(gcloud config get-value project)
export LOCATION="us-central1"
export MODEL="gemini-3.1-flash-lite"
export MODEL_REGION="global"

ตัวแปรเหล่านี้จะกำหนดการตั้งค่าการติดตั้งใช้งานเป้าหมาย

  • PROJECT_ID: ตัวระบุที่ไม่ซ้ำกันของโปรเจ็กต์ Google Cloud ที่จะใช้เป็นที่อยู่ของทรัพยากร Gemini Enterprise Agent Platform และ Artifact Registry ทั้งหมด
  • LOCATION: ภูมิภาคทางภูมิศาสตร์ (เช่น us-central1) ที่โฮสต์ที่เก็บและภาระงานรันไทม์
  • MODEL: เวอร์ชันโมเดล Gemini (เช่น gemini-3.1-flash-lite) ที่โหลดโดยบริบทของ Agent
  • MODEL_REGION: ภูมิภาคปลายทางของโมเดล ตั้งค่าที่นี่เป็น "global" เพื่อเรียกใช้โมเดล Gemini จากปลายทางส่วนกลาง

ขั้นตอนที่ 3: เปิดใช้ API

เปิดใช้ Google Cloud APIs ที่จำเป็น

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

ขั้นตอนที่ 4: ติดตั้ง SDK

ติดตั้ง Vertex AI SDK ที่รองรับ Agent Engine และ ADK โดยทำดังนี้

pip install --upgrade "google-cloud-aiplatform[agent_engines,adk]>=1.144"

3. การตั้งค่าไฟล์ต้นฉบับ

ในขั้นตอนนี้ คุณจะได้สร้างโครงสร้างและโค้ดสำหรับเอเจนต์

ภาพรวมโครงสร้างไดเรกทอรี

เมื่อสิ้นสุด Codelab นี้ ไฟล์ของคุณจะได้รับการจัดระเบียบภายใต้ลำดับชั้นของพื้นที่ทำงานต่อไปนี้

weather-agent-byoc/
├── Dockerfile                  # Container definition
├── deploy_byoc.py              # Python SDK deployment script
├── main.py                     # FastAPI server wrapper
├── query_agent.py              # Verify / query script
├── requirements.txt            # Python dependencies

├── weather_agent/              # Agent source module
   ├── __init__.py             # Package declaration
   ├── agent.py                # Agent & mock tools logic
   └── config.json             # Environment config variables

└── terraform/                  # Terraform configuration files
    ├── main.tf
    ├── outputs.tf
    ├── providers.tf
    ├── terraform.tfvars
    └── variables.tf

ขั้นตอนที่ 1: สร้างไดเรกทอรี

เริ่มต้นในไดเรกทอรีหลักและสร้างโครงสร้างพื้นที่ทำงานโดยทำดังนี้

cd ~
mkdir -p weather-agent-byoc/weather_agent
cd weather-agent-byoc

ขั้นตอนที่ 2: สร้างไฟล์การกำหนดค่า

เรียกใช้คำสั่งต่อไปนี้ใน Cloud Shell เพื่อเขียนพารามิเตอร์การกำหนดค่าลงใน weather_agent/config.json โดยตรง คำสั่งนี้จะแทนที่ตัวแปรด้วยค่าสภาพแวดล้อมโดยอัตโนมัติ

cat <<EOF > weather_agent/config.json
{
    "PROJECT_ID": "${PROJECT_ID}",
    "LOCATION": "${LOCATION}",
    "MODEL": "${MODEL}",
    "MODEL_REGION": "${MODEL_REGION}"
}
EOF

ขั้นตอนที่ 3: กำหนดเอเจนต์

เรียกใช้สคริปต์ต่อไปนี้เพื่อเขียนการกำหนดค่าเอเจนต์และตรรกะเครื่องมือจำลองไปยัง weather_agent/agent.py

cat << 'EOF' > weather_agent/agent.py
import json
import random
from google.adk.agents import Agent
from google.adk.models.google_llm import Gemini
from functools import cached_property
from google.genai import Client

# Load config
llm_config = json.load(open("weather_agent/config.json"))
PROJECT_ID = llm_config["PROJECT_ID"]
MODEL = llm_config["MODEL"]
MODEL_REGION = llm_config["MODEL_REGION"]

# Override Gemini class for global endpoint compatibility
class GlobalGemini(Gemini):
  @cached_property
  def api_client(self) -> Client:
    return Client(vertexai=True, location="global")

# Define Tool
def get_temperature(place: str) -> str:
    '''Returns the current temperature of a given place.

    Args:
        place: The name of the city or location.

    Returns:
        str: A string describing the temperature.
    '''
    temp = random.randint(-10, 40)
    return f"The current temperature in {place} is {temp}°C."

# Initialize LLM
llm_model = GlobalGemini(model=MODEL) if MODEL_REGION == "global" else Gemini(model=MODEL)

# Initialize Agent
root_agent = Agent(
    model=llm_model,
    name='weather_agent',
    description='An agent that provides temperature information for locations.',
    instruction='You are a helpful assistant that can provide the current temperature for any given place using the get_temperature tool.',
    tools=[get_temperature],
)
EOF

สร้าง __init__.py เปล่าเพื่อทำให้ weather_agent เป็นแพ็กเกจ Python

touch weather_agent/__init__.py

ขั้นตอนที่ 4: สร้าง Wrapper ของ FastAPI

เรียกใช้สคริปต์ต่อไปนี้เพื่อเขียนการกำหนดค่าจุดแรกเข้าของเซิร์ฟเวอร์ FastAPI ไปยัง main.py

cat << 'EOF' > main.py
import inspect
import json
import logging
import os
from typing import Any, Dict, Optional
import uvicorn
import vertexai
from weather_agent.agent import root_agent
from fastapi import FastAPI, encoders, responses, Request
from vertexai import agent_engines

app = FastAPI()

config_json = json.load(open("weather_agent/config.json"))
PROJECT_ID = config_json["PROJECT_ID"]
LOCATION = config_json["LOCATION"]
MODEL_REGION = config_json["MODEL_REGION"]

vertexai.init(project=PROJECT_ID, location=MODEL_REGION)
adk_app = agent_engines.AdkApp(agent=root_agent)

def _encode_chunk_to_json(chunk):
  try:
    json_chunk = encoders.jsonable_encoder(chunk)
    return json.dumps(json_chunk) + "\n"
  except Exception:
    logging.exception("Failed to encode chunk")
    return None

async def json_generator(output):
  async for chunk in output:
    encoded_chunk = _encode_chunk_to_json(chunk)
    if encoded_chunk is None:
      break
    yield encoded_chunk

async def _invoke_callable_or_raise(invocation_callable, invocation_payload):
  if inspect.iscoroutinefunction(invocation_callable):
    return await invocation_callable(**invocation_payload)
  else:
    return invocation_callable(**invocation_payload)

@app.post("/api/reasoning_engine")
async def query(request: Request) -> responses.JSONResponse:
    request_json = await request.json()
    class_method = request_json.get("class_method")
    input_val = request_json.get("input")
    method = getattr(adk_app, class_method)
    output = await _invoke_callable_or_raise(method, input_val or {})
    try:
      json_serialized_content = encoders.jsonable_encoder({"output": output})
    except ValueError as encoding_error:
      logging.exception("Failed to encode response")
      raise encoding_error
    return responses.JSONResponse(content=json_serialized_content)

@app.post("/api/stream_reasoning_engine")
async def stream_query(request: Request) -> responses.StreamingResponse:
    request_json = await request.json()
    class_method = request_json.get("class_method")
    input_val = request_json.get("input")
    method = getattr(adk_app, class_method)
    output = await _invoke_callable_or_raise(method, input_val or {})
    return responses.StreamingResponse(
        content=json_generator(output),
        media_type="application/json",
    )

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
EOF

ขั้นตอนที่ 5: กำหนดทรัพยากร Dependency

เขียนทรัพยากร Dependency ของ Python ที่จำเป็นลงใน requirements.txt

cat << 'EOF' > requirements.txt
fastapi
uvicorn
vertexai
google-cloud-aiplatform[agent_engines,adk]>=1.144
pydantic
EOF

4. การขนส่งด้วยตู้คอนเทนเนอร์

ตอนนี้ให้กำหนดวิธีแพ็กเกจ Agent ลงในคอนเทนเนอร์

ขั้นตอนที่ 1: สร้าง Dockerfile

สร้าง Dockerfile ในรูทของไดเรกทอรีโปรเจ็กต์เพื่อระบุวิธีสร้างแอปพลิเคชัน FastAPI

cat << 'EOF' > Dockerfile
FROM python:3.11-slim

WORKDIR /app

COPY weather_agent/ /app/weather_agent/
COPY main.py .
COPY requirements.txt .
RUN pip install -r requirements.txt

CMD ["sh", "-c", "uvicorn main:app --host 0.0.0.0 --port $PORT"]
EOF

5. ตั้งค่า Artifact Registry และ Cloud Build

คุณต้องมีที่เก็บเพื่อจัดเก็บอิมเมจคอนเทนเนอร์และสิทธิ์ในการพุช

ขั้นตอนที่ 1: สร้างที่เก็บ

กำหนดชื่อที่เก็บและสร้างที่เก็บ Docker ภายใน Artifact Registry โดยใช้ตัวแปรสภาพแวดล้อมที่กำหนดไว้ในระหว่างการกำหนดค่า

export REPOSITORY_NAME="agents-repo"

gcloud artifacts repositories create $REPOSITORY_NAME \
    --project=$PROJECT_ID \
    --repository-format=docker \
    --location=$LOCATION \
    --description="Docker repository for Agents"

ขั้นตอนที่ 2: กำหนดค่าสิทธิ์ของบัญชีบริการ

ให้สิทธิ์บัญชีบริการ Compute เริ่มต้นในการพุชอิมเมจไปยัง Artifact Registry

ก่อนอื่นให้รับหมายเลขโปรเจ็กต์โดยทำดังนี้

export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")

มอบบทบาทโดยทำดังนี้

# Allow pushing to Artifact Registry
gcloud projects add-iam-policy-binding $PROJECT_ID \
    --member="serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com" \
    --role="roles/artifactregistry.writer" \
    --condition=None

# Allow Cloud Build to read storage objects
gcloud projects add-iam-policy-binding $PROJECT_NUMBER \
    --member="serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com" \
    --role="roles/storage.objectViewer" \
    --condition=None

ขั้นตอนที่ 3: ให้สิทธิ์แก่ตัวแทนบริการ

ให้สิทธิ์เข้าถึงแบบอ่านแก่ผู้อ่าน Artifact Registry สำหรับตัวแทนบริการ AI Platform และ Reasoning Engine โดยทำดังนี้

gcloud projects add-iam-policy-binding $PROJECT_NUMBER \
    --member="serviceAccount:service-$PROJECT_NUMBER@gcp-sa-aiplatform-re.iam.gserviceaccount.com" \
    --role="roles/artifactregistry.reader"  --condition=None

gcloud projects add-iam-policy-binding $PROJECT_NUMBER \
    --member="serviceAccount:service-$PROJECT_NUMBER@gcp-sa-aiplatform.iam.gserviceaccount.com" \
    --role="roles/artifactregistry.reader"  --condition=None

ขั้นตอนที่ 4: สร้างและพุชอิมเมจ

ใช้ Cloud Build เพื่อสร้างและพุชอิมเมจคอนเทนเนอร์

gcloud builds submit \
    --project=$PROJECT_ID \
    --region=$LOCATION \
    --tag $LOCATION-docker.pkg.dev/$PROJECT_ID/$REPOSITORY_NAME/weather-agent-image:latest \
    .

6. ติดตั้งใช้งานเอเจนต์ด้วย SDK

เมื่อกำหนดค่าสิทธิ์แล้ว คุณก็สามารถติดตั้งใช้งานคอนเทนเนอร์ที่กำหนดเองได้

ขั้นตอนที่ 1: ติดตั้งใช้งานตัวแทน BYOC

สร้างไฟล์ Python deploy_byoc.py ภายในรูทของไดเรกทอรีโปรเจ็กต์เพื่อติดตั้งใช้งานคอนเทนเนอร์ที่โฮสต์รีจิสทรีไปยัง Agent Runtime

cat << 'EOF' > deploy_byoc.py
import json
import os
import vertexai
from google.cloud import aiplatform

config = json.load(open("weather_agent/config.json"))
PROJECT_ID = config["PROJECT_ID"]
LOCATION = config["LOCATION"]
REPOSITORY_NAME = "agents-repo"

vertexai.init(project=PROJECT_ID, location=LOCATION)
client = vertexai.Client(project=PROJECT_ID, location=LOCATION)

image_uri = f"{LOCATION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY_NAME}/weather-agent-image:latest"

print(f"Deploying custom container agent from {image_uri}...")
remote_agent = client.agent_engines.create(
    config={
        "display_name": "byoc_weather_agent",
        "description": "BYOC weather agent from custom container",
        "container_spec": {
            "image_uri": image_uri
        },
        "class_methods": [
            # For convenience to interact with the agent through the Python SDK
            # https://docs.cloud.google.com/gemini-enterprise-agent-platform/scale/runtime/use-an-adk-agent#supported-operations
            {"api_mode": "", "name": "get_session"},
            {"api_mode": "", "name": "list_sessions"},
            {"api_mode": "", "name": "create_session"},
            {"api_mode": "", "name": "delete_session"},
            {"api_mode": "async", "name": "async_get_session"},
            {"api_mode": "async", "name": "async_list_sessions"},
            {"api_mode": "async", "name": "async_create_session"},
            {"api_mode": "async", "name": "async_delete_session"},
            {"api_mode": "async", "name": "async_add_session_to_memory"},
            {"api_mode": "async", "name": "async_search_memory"},
            {"api_mode": "stream", "name": "stream_query"},
            {"api_mode": "async_stream", "name": "async_stream_query"},
            {"api_mode": "async_stream", "name": "streaming_agent_run_with_events"},
        ],
        "agent_framework": "google-adk",
    },
)

print(f"Agent successfully deployed!")
print(f"Resource Name: {remote_agent.api_resource.name}")

# Save resource name for testing
with open("agent_resource_name.txt", "w") as f:
    f.write(remote_agent.api_resource.name)
EOF

เรียกใช้สคริปต์การทำให้ใช้งานได้เพื่อทำให้ Agent ใช้งานได้ใน Agent Runtime โดยทำดังนี้

python3 deploy_byoc.py

7. ติดตั้งใช้งาน Agent ด้วย Terraform

หรือจะติดตั้งใช้งานเอเจนต์ที่อยู่ในคอนเทนเนอร์เดียวกันโดยใช้ Terraform ก็ได้ เราขอแนะนำให้ใช้ในสภาพแวดล้อมในการใช้งานจริงเพื่อจัดการโครงสร้างพื้นฐานเป็นโค้ด

ขั้นตอนที่ 1: ไปที่ไดเรกทอรี Terraform

สร้างไดเรกทอรี terraform ในรูทของโปรเจ็กต์ แล้วไปที่ไดเรกทอรีดังกล่าวโดยทำดังนี้

mkdir -p terraform
cd terraform

ขั้นตอนที่ 2: สร้างการกำหนดค่าผู้ให้บริการ

เรียกใช้สคริปต์ต่อไปนี้เพื่อเขียนการแมปผู้ให้บริการไปยัง providers.tf

cat << 'EOF' > providers.tf
terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = ">= 5.28.0"
    }
  }
}

provider "google" {
  project = var.project_id
  region  = var.location
}
EOF

ขั้นตอนที่ 3: สร้างคำจำกัดความของตัวแปร

เขียนบล็อกคำอธิบายอินพุตเป็น variables.tf

cat << 'EOF' > variables.tf
variable "project_id" {
  type        = string
  description = "The Google Cloud Project ID"
}

variable "location" {
  type        = string
  description = "The region to deploy the reasoning engine"
  default     = "us-central1"
}

variable "repository_name" {
  type        = string
  description = "The Artifact Registry repository name"
  default     = "agents-repo"
}

variable "image_tag" {
  type        = string
  description = "The tag of the container image to deploy"
  default     = "latest"
}
EOF

ขั้นตอนที่ 4: สร้างการกำหนดค่าหลัก

เขียนพารามิเตอร์คำจำกัดความของทรัพยากรหลักเป็น main.tf

cat << 'EOF' > main.tf
locals {
  class_methods = [
    {"api_mode" = "", "name" = "get_session"},
    {"api_mode" = "", "name" = "list_sessions"},
    {"api_mode" = "", "name" = "create_session"},
    {"api_mode" = "", "name" = "delete_session"},
    {"api_mode" = "async", "name" = "async_get_session"},
    {"api_mode" = "async", "name" = "async_list_sessions"},
    {"api_mode" = "async", "name" = "async_create_session"},
    {"api_mode" = "async", "name" = "async_delete_session"},
    {"api_mode" = "async", "name" = "async_add_session_to_memory"},
    {"api_mode" = "async", "name" = "async_search_memory"},
    {"api_mode" = "stream", "name" = "stream_query"},
    {"api_mode" = "async_stream", "name" = "async_stream_query"},
    {"api_mode" = "async_stream", "name" = "streaming_agent_run_with_events"}
  ]
}

# define the resource with the BYOC configuration, set agent_framework to "google-adk" to enable interactive features on the console.
resource "google_vertex_ai_reasoning_engine" "byoc_weather_agent" {
  display_name = "byoc_weather_agent_tf"
  description  = "BYOC weather agent deployed via Terraform"
  project      = var.project_id
  location     = var.location

  spec {
    class_methods = jsonencode(local.class_methods)
    agent_framework = "google-adk"
    container_spec {
      image_uri = "${var.location}-docker.pkg.dev/${var.project_id}/${var.repository_name}/weather-agent-image:${var.image_tag}"
    }
  }
}
EOF

ขั้นตอนที่ 5: สร้างคำจำกัดความเอาต์พุต

เขียนบล็อกเอาต์พุตไปยัง outputs.tf ดังนี้

cat << 'EOF' > outputs.tf
output "reasoning_engine_id" {
  value       = google_vertex_ai_reasoning_engine.byoc_weather_agent.id
  description = "The ID of the deployed reasoning engine"
}

output "reasoning_engine_resource_name" {
  value       = google_vertex_ai_reasoning_engine.byoc_weather_agent.id
  description = "The resource name of the deployed reasoning engine"
}
EOF

ขั้นตอนที่ 6: สร้างไฟล์ค่าตัวแปร (tfvars)

ติดตั้งใช้งานแบบไดนามิกโดยไม่ต้องแก้ไขตัวยึดตําแหน่งด้วยการป้อนตัวแปรสภาพแวดล้อมไปยัง terraform.tfvars โดยตรง

cat <<EOF > terraform.tfvars
project_id      = "${PROJECT_ID}"
location        = "${LOCATION}"
repository_name = "agents-repo"
image_tag       = "latest"
EOF

ขั้นตอนที่ 7: เริ่มต้นและใช้

เริ่มต้น Terraform และใช้การกำหนดค่า

terraform init
terraform apply

ยืนยันการสมัครโดยพิมพ์ yes เมื่อได้รับข้อความแจ้ง

เมื่อเสร็จแล้ว Terraform จะแสดงชื่อทรัพยากร บันทึกโดยใช้โปรแกรมไปยัง agent_resource_name.txt แล้วกลับไปที่โฟลเดอร์รูท

terraform output -raw reasoning_engine_resource_name > ../agent_resource_name.txt
cd ..

8. ค้นหา Agent

ตรวจสอบว่า Agent ทำงานและตอบสนอง

ขั้นตอนที่ 1: สร้างสคริปต์การค้นหา

เขียนสคริปต์การยืนยันเพื่อ query_agent.py โดยใช้การตรวจสอบการกำหนดค่าการตั้งค่าแบบไดนามิกเพื่อดึงพิกัดตำแหน่ง

cat << 'EOF' > query_agent.py
import json
import os
import requests
from google import auth as google_auth
from google.auth.transport import requests as google_requests

# Load config coordinates directly
config_json = json.load(open("weather_agent/config.json"))
LOCATION = config_json["LOCATION"]
PROJECT_ID = config_json["PROJECT_ID"]

# Load agent resource name
with open("agent_resource_name.txt", "r") as f:
    agent_resource_name = f.read().strip()

def get_identity_token():
    credentials, _ = google_auth.default()
    auth_request = google_requests.Request()
    credentials.refresh(auth_request)
    return credentials.token

# Access the agent at the fastapi endpoint that was specified in main.py
url = f"https://{LOCATION}-aiplatform.googleapis.com/reasoningEngines/v1/{agent_resource_name}/api/api/stream_reasoning_engine"

payload = {
    "class_method": "async_stream_query",
    "input": {
        "user_id": "codelab_test_user",
        "message": "What is the temperature in Tokyo?",
    },
}

print(f"Sending query to {url}...")
response = requests.post(
    url,
    headers={
        "Content-Type": "application/json",
        "Authorization": f"Bearer {get_identity_token()}",
    },
    data=json.dumps(payload),
    stream=True,
)

for chunk in response.iter_content(chunk_size=8192):
    if chunk:
        print(chunk.decode('utf-8'))
EOF

เรียกใช้สคริปต์การค้นหา

python3 query_agent.py

คุณควรเห็นเอาต์พุตที่สตรีมกลับจากเอเจนต์ รวมถึงอุณหภูมิจำลองสำหรับโตเกียว

ขั้นตอนที่ 2: ใช้คอนโซล

  1. ไปที่เอเจนต์ที่ติดตั้งใช้งานโดยเลือกแพลตฟอร์มเอเจนต์ > เอเจนต์ > การติดตั้งใช้งานเพื่อกรองรายการเอเจนต์

รูปภาพตัวแทน

  1. เลือก Playground จากแดชบอร์ดของเอเจนต์

แดชบอร์ด Agent

  1. สร้างเซสชันใหม่และพิมพ์คำค้นหาเพื่อตรวจสอบว่าตัวแทนตอบกลับคำขอตามที่แสดงหรือไม่

การโต้ตอบของตัวแทน

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

โปรดล้างข้อมูลทรัพยากรที่คุณสร้างขึ้นเพื่อหลีกเลี่ยงการเรียกเก็บเงิน

หากคุณติดตั้งใช้งานโดยใช้ Terraform ให้เปลี่ยนเป็นไดเรกทอรี terraform แล้วดำเนินการทำลาย

cd ~/weather-agent-byoc/terraform
terraform destroy
cd ..

หากคุณติดตั้งใช้งานโดยใช้ SDK ให้สร้างสคริปต์เพื่อลบ Agent ที่ติดตั้งใช้งานแล้ว

cat << 'EOF' > delete_agent.py
import json
import os
import vertexai
from google.cloud import aiplatform

config = json.load(open("weather_agent/config.json"))
PROJECT_ID = config["PROJECT_ID"]
LOCATION = config["LOCATION"]

vertexai.init(project=PROJECT_ID, location=LOCATION)
client = vertexai.Client(project=PROJECT_ID, location=LOCATION)

with open("agent_resource_name.txt", "r") as f:
    agent_resource_name = f.read().strip()

# 1. Delete the Agent
# Note: We retrieve the list first to ensure we delete the ones created in this session
try:
    page_size = 100
    reasoning_engines = client.agent_engines.list()
    for engine in reasoning_engines:
        if agent_resource_name in engine.api_resource.name:
            print(f"Deleting Reasoning Engine: {engine.api_resource.name}")
            engine.delete(force=True)
except Exception as e:
    print(f"Error deleting reasoning engines: {e}")
EOF

เรียกใช้สคริปต์เพื่อลบ Agent

python3 delete_agent.py

หากต้องการล้างข้อมูลทรัพยากรที่เหลือ ให้กลับไปที่ไดเรกทอรีหน้าแรกแล้วเรียกใช้คำสั่งต่อไปนี้ใน Cloud Shell

cd ~

# 1. Delete the Artifact Registry Repository
gcloud artifacts repositories delete $REPOSITORY_NAME --location=$LOCATION --quiet

# 2. Clean up files (Optional)
rm -rf ~/weather-agent-byoc

10. บทสรุป

ยินดีด้วย คุณสร้างคอนเทนเนอร์และติดตั้งใช้งาน AI Agent ใน Agent Runtime โดยใช้ BYOC เรียบร้อยแล้ว

คุณได้เรียนรู้วิธีต่อไปนี้

  • ใช้ ADK เพื่อกำหนด Agent และห่อหุ้มด้วย FastAPI
  • สร้าง Dockerfile และสร้างอิมเมจโดยใช้ Cloud Build
  • จัดการสิทธิ์ IAM สำหรับ Agent Runtime
  • ติดตั้งใช้งานคอนเทนเนอร์ที่กำหนดเองโดยใช้ทั้ง Python SDK และ Terraform
  • ทดสอบและค้นหา Agent ที่ใช้งานจริง