可易

规模化 AI 智能体:在 GKE Autopilot 上部署 ADK 的分步指南

可易团队阅读约 9 分钟

本教程用 ADK 构建天气智能体,容器化后推送到 Artifact Registry,经工作负载身份部署到 GKE Autopilot,并用 Gateway API 与托管证书提供 HTTPS。

目录

#规模化 AI 智能体:在 GKE Autopilot 上部署 ADK 的分步指南

在本地使用 Google 的智能体开发套件(Agent Development Kit,ADK)构建 AI 智能体(AI agent),是做原型的好办法,但可用于生产的智能体需要稳健、可扩展的基础设施。对于希望走出单实例、进入托管容器编排的开发者,Google Kubernetes Engine(GKE)Autopilot 在灵活性与易用性之间取得了平衡。

在本教程中,我将带你用 ADK 构建一个技术智能体,并将其部署到 GKE Autopilot。我们将以 Vertex AI 上的 Gemini 为核心模型,并通过工作负载身份(Workload Identity)管理权限,以满足更高的安全标准。

理解 GKE 上的 ADK 架构

把 ADK 智能体部署到 GKE Autopilot,并不只是运行一个容器。我们利用 GKE 的原生能力处理扩展与安全。架构由一个基于 ADK 的 Python 应用组成:它被打包为 Docker 镜像,存放在工件注册库(Artifact Registry)中。该容器在 GKE Autopilot 上以 Deployment 运行,并通过工作负载身份与 Vertex AI 安全通信——把 Kubernetes 服务账号(Kubernetes Service Account)映射到 Google Cloud IAM 服务账号(IAM Service Account)。

为了把智能体暴露到外部,我们使用 Kubernetes Gateway API。它是 Ingress 的现代后继,关注点分离更清晰,并原生支持 Google Cloud 负载均衡(Load Balancing)。

前提条件

开始之前,请准备好以下工具和账号:

  • Python 3.10 或更高版本。
  • 用于包管理的 uv。
  • 已安装并完成配置的 Google Cloud SDK(gcloud)。
  • 一个已启用结算的 Google Cloud 项目。
  • kubectl 命令行工具。
  • 用于解析 JSON 响应的 jq。
  • 已启用以下 API:Kubernetes Engine、Artifact Registry 和 Vertex AI。

步骤 0:配置 Google Cloud 与身份验证

在与 Google Cloud 服务交互之前,必须对环境完成身份验证并设置当前项目。这样 gcloud CLI 和本地 Python 环境才能访问 Vertex AI。

  1. 登录 Google Cloud SDK:
gcloud auth login
  1. 设置当前项目:
gcloud config set project [PROJECT_ID]
  1. 设置应用默认凭据(Application Default Credentials,ADC):这对 ADK 库在本地测试时向 Vertex AI 完成身份验证至关重要。
gcloud auth application-default login
  1. 定义环境变量:为了在后续步骤中复用配置,把项目、区域和集群名称导出为环境变量。
export PROJECT_ID=$(gcloud config get-value project)
export REGION=us-central1
export CLUSTER_NAME=adk-cluster

步骤 1:开通 GKE Autopilot

GKE Autopilot 是不管理节点而运行 Kubernetes 的推荐方式。你可以专注于智能体部署,由 Google 管理基础设施。现在开始创建集群,可以让它在后台开通,同时我们构建智能体。

gcloud container clusters create-auto $CLUSTER_NAME --region $REGION

集群开通期间,可以继续构建智能体。

步骤 2:用 ADK 构建智能体

首先创建智能体。先为智能体代码创建一个文件夹:

mkdir adk-agent
cd adk-agent

用 uv 初始化一个新的 Python 项目:

uv init

添加依赖

uv add google-adk

使用 adk cli 创建新智能体

uv run adk create weather_agent

系统会要求你为根智能体选择模型。选择 gemini-2.5-flash(编号 1)。接下来会要求你选择后端。选择 Vertex AI(编号 2)。接下来会要求你输入 Google Cloud 项目 ID。输入你的项目 ID。接下来会要求你输入 Google Cloud 区域。选择你想用的区域。示例:us-central1。

上一条命令搭建了新目录 weather_agent,结构如下:

weather_agent/
├── .env
├── __init__.py
└── agent.py

ADK 要求智能体代码位于 agent.py 文件中。我们来编辑 agent.py,为智能体添加一个简单工具。

 from google.adk import Agent
# Define a simple tool for the agent
def get_weather(city: str) -> str:
    """Returns the current weather in a city."""
    return f"The weather in {city} is 90 degrees Fahrenheit and sunny."
# Initialize the agent with Vertex AI and Gemini
root_agent = Agent(
    name="weather_agent",
    model="gemini-2.5-pro",
    tools=[get_weather]
)

agent.py 是智能体的入口文件。它用于定义智能体及其工具。get_weather 函数是一个简单工具,返回某个城市的当前天气。在本教程中,天气使用硬编码值。在真实场景中,你会调用 API 获取当前天气。

步骤 3:在本地测试智能体

把智能体部署到 GKE Autopilot 之前,需要在本地测试,确认它按预期工作。运行以下命令,以调试模式启动智能体并打开 Web UI:

uv run adk web

在浏览器中打开 http://localhost:8000,你应该能看到 ADK Web UI。随后可以在聊天界面中输入消息,与智能体交互。

如果智能体返回类似 “The weather in \[CITY\] is 90 degrees Fahrenheit and sunny.” 的消息,恭喜!你的 ADK 智能体已经可以工作。现在可以进入下一步。

步骤 4:为 GKE Autopilot 做准备

ADK cli 内置了把智能体部署到 GKE Autopilot 的命令。但默认设置不适合生产环境。例如,默认设置不会使用工作负载身份向 Vertex AI 做身份验证,也不会通过负载均衡器(Load Balancer)在 80 端口暴露 Web UI。

我们将改为自己管理容器的生命周期。首先需要把智能体容器化。

在 adk-agent 目录中创建 .dockerignore 文件,避免把本地虚拟环境复制进镜像:

.venv
.adk
__pycache__
*.pyc
.env

在 adk-agent 目录中为智能体创建 Dockerfile。我们将使用多阶段构建,让最终的生产镜像更轻、更安全:

# Stage 1: Build the virtual environment
FROM python:3.10-slim AS builder

# Install uv
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

# Set working directory
WORKDIR /app

# Force uv to use the system Python and use copy instead of symlinks
ENV UV_PYTHON_PREFERENCE=only-system
ENV UV_LINK_MODE=copy
ENV UV_COMPILE_BYTECODE=1
ENV UV_PYTHON=/usr/local/bin/python3

# Install dependencies
# We copy only files needed for installation to maximize cache
COPY pyproject.toml uv.lock ./
# Note: We don't use --frozen yet as the host lock file might be slightly out of sync
# but sync will update it in the builder stage.
RUN uv sync --no-install-project --no-dev --no-cache

# Copy the agent code
COPY . .
# Sync the project itself
RUN uv sync --no-dev --no-cache

# Stage 2: Runtime image
FROM python:3.10-slim

WORKDIR /app

# Copy the pre-built environment from the builder
COPY --from=builder /app/.venv /app/.venv
# Copy the application code (including weather_agent folder)
COPY . .

# Add the environment to the PATH
ENV PATH="/app/.venv/bin:$PATH"
ENV PYTHONUNBUFFERED=1

# Run the ADK API server
# We point to the weather_agent folder
CMD ["adk", "api_server", ".", "--host", "0.0.0.0", "--port", "8080"]

构建镜像并推送到 Artifact Registry:

# Create repository
gcloud artifacts repositories create adk-repo --repository-format=docker --location=$REGION

# Build and push
gcloud builds submit --tag $REGION-docker.pkg.dev/$PROJECT_ID/adk-repo/gke-agent:latest

步骤 5:用工作负载身份落实安全

安全至关重要。我们不把 API 密钥硬编码,而是使用工作负载身份,授予 GKE Pod 访问 Vertex AI 的权限。

1. 创建 IAM 服务账号:

gcloud iam service-accounts create adk-gke-sa

2. 授予 Vertex AI 权限:

gcloud projects add-iam-policy-binding $PROJECT_ID \

    --member="serviceAccount:adk-gke-sa@$PROJECT_ID.iam.gserviceaccount.com" \
    --role="roles/aiplatform.user"

3. 允许 Kubernetes 服务账号模拟该 IAM 服务账号:

gcloud iam service-accounts add-iam-policy-binding adk-gke-sa@$PROJECT_ID.iam.gserviceaccount.com \
    --role="roles/iam.workloadIdentityUser" \
    --member="serviceAccount:$PROJECT_ID.svc.id.goog[default/adk-ksa]"

步骤 6:把智能体部署到 GKE

现在定义 Kubernetes 资源。创建一个 deployment.yaml,其中包含用于工作负载身份的服务账号注解。把 $PROJECT_ID 和 $REGION 替换为你的实际项目 ID 和区域。

apiVersion: v1
kind: ServiceAccount
metadata:
  name: adk-ksa
  annotations:
    iam.gke.io/gcp-service-account: adk-gke-sa@$PROJECT_ID.iam.gserviceaccount.com
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: adk-agent
spec:
  replicas: 2
  selector:
    matchLabels:
      app: adk-agent
  template:
    metadata:
      labels:
        app: adk-agent
    spec:
      serviceAccountName: adk-ksa
      containers:
      - name: adk-agent
        image: $REGION-docker.pkg.dev/$PROJECT_ID/adk-repo/gke-agent:latest
        resources:
          requests:
            cpu: "500m"
            memory: "512Mi"
          limits:
            cpu: "1"
            memory: "1Gi"
        ports:
        - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: adk-service
spec:
  selector:
    app: adk-agent
  ports:
  - port: 80
    targetPort: 8080

应用该配置:

kubectl apply -f deployment.yaml

查看部署状态:

kubectl get pods -w

Pod 运行后,可以用 kubectl port-forward 在本地访问智能体:

kubectl port-forward svc/adk-service 8080:80

由于这次部署没有带 Web UI,不能在 http://localhost:8080 直接打开它。不过仍可以用 API 和 curl 与它交互。

在一个新终端中运行以下命令:

# Create a new session
curl -X POST http://localhost:8080/apps/weather_agent/users/u_123/sessions/s_123

# Run a message
curl -s -X POST http://localhost:8080/run \
-H "Content-Type: application/json" \
-d '{
"appName": "weather_agent",
"userId": "u_123",
"sessionId": "s_123",
"newMessage": {
    "role": "user",
    "parts": [{\
    "text": "Hey whats the weather in new york today"\
    }]
}
}' | jq .

curl 命令会以 JSON 格式返回响应。jq 命令用于解析 JSON 响应,并以更易读的格式显示。你应该会看到类似如下的响应:

{
    "sessionId": "s_123",
    "messages": [\
        {\
            "role": "assistant",\
            "parts": [\
                {\
                    "text": "The weather in New York today is sunny with a high of 90 degrees Fahrenheit."\
                }\
            ]\
        }\
    ]
}

(可选)步骤 7:通过 Gateway API 和 HTTPS 负载均衡器对外暴露

最后,我们用 GKE Gateway API 和 Google 托管的 TLS 证书把智能体暴露出去。这是推荐的生产级做法——Google 会为你的域名自动签发并续期证书。

注意:GKE 还支持其他证书开通方式。你可以使用带 cert-manager 的 Let's Encrypt、预共享证书,或其他证书颁发机构。更多细节见 GKE 文档。

首先为负载均衡器预留一个静态 IP 地址:

gcloud compute addresses create adk-agent-ip --global
export AGENT_IP=$(gcloud compute addresses describe adk-agent-ip --global --format="value(address)")
echo "Your IP: $AGENT_IP"

把域名的 DNS A 记录指向 $AGENT_IP。示例:adk.mydomain.com

创建 Google 托管证书。把 adk.yourdomain.com 替换为你的实际域名:

gcloud compute ssl-certificates create adk-cert --domains adk.yourdomain.com --global

创建包含以下内容的 gateway.yaml:

# Gateway: HTTPS load balancer with the managed certificate and static IP
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: adk-gateway
spec:
  gatewayClassName: gke-l7-global-external-managed
  listeners:
  - name: https
    protocol: HTTPS
    port: 443
    tls:
      mode: Terminate
      options:
        networking.gke.io/pre-shared-certs: adk-cert
  addresses:
  - type: NamedAddress
    value: adk-agent-ip
---
# HTTPRoute: forward traffic to the ADK service
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: adk-route
spec:
  parentRefs:
  - name: adk-gateway
  hostnames:
  - "api.yourdomain.com"
  rules:
  - backendRefs:
    - name: adk-service
      port: 80
---
apiVersion: networking.gke.io/v1
kind: HealthCheckPolicy
metadata:
  name: adk-health
  namespace: default
spec:
  default:
    checkIntervalSec: 15
    timeoutSec: 5
    healthyThreshold: 1
    unhealthyThreshold: 2
    logConfig:
      enabled: false
    config:
      type: HTTP
      httpHealthCheck:
        port: 8080
        requestPath: /health
  targetRef:
    group: ""
    kind: Service
    name: adk-service

应用该配置:

kubectl apply -f gateway.yaml

证书开通最多可能需要 20 分钟。用以下命令查看状态:

gcloud compute ssl-certificates describe adk-cert --global

状态变为 Active 后,智能体即可通过 https://api.yourdomain.com 访问。可以用以下命令测试:

# Create a new session
curl -X POST https://api.yourdomain.com/apps/weather_agent/users/u_124/sessions/s_124

# Run a message
curl -s -X POST https://api.yourdomain.com/run \
-H "Content-Type: application/json" \
-d '{
"appName": "weather_agent",
"userId": "u_124",
"sessionId": "s_124",
"newMessage": {
    "role": "user",
    "parts": [{\
    "text": "Hey whats the weather in new york today"\
    }]
}
}' | jq .

结论与后续展望

按照这些步骤,你已经把一个用 ADK 构建、可用于生产的 AI 智能体部署到 GKE Autopilot。它通过工作负载身份完成身份验证,并调用 Vertex AI 上的 Gemini。这一设置让智能体可以按需求水平扩展,同时保持较高的安全态势。

往前看,可以考虑接入更复杂的工具,或利用 GKE 的多集群能力获得更高韧性。关于这里所用技术的更多细节,请查阅官方 GKE 文档 和 ADK 仓库。

为避免持续产生费用,完成后请记得删除 GKE 集群和 Artifact Registry 仓库:

kubectl delete -f gateway.yaml
kubectl delete -f deployment.yaml
gcloud compute addresses delete adk-agent-ip --global
gcloud compute ssl-certificates delete adk-cert --global
gcloud container clusters delete $CLUSTER_NAME --region $REGION
gcloud artifacts repositories delete adk-repo --location $REGION

PRIMARY_SOURCE: https://cloud.google.com/blog/topics/developers-practitioners/scaling-ai-agents-a-step-by-step-guide-to-deploying-adk-on-gke-autopilot

  • #GKE
  • #ADK
  • #工作负载身份
  • #Vertex AI
  • #部署